def bond_var(period, percent, day): df_nav = base_ra_index_nav.load_series('120000011') df_inc = df_nav.pct_change(period) df_inc = df_inc.dropna() df_inc = df_inc[df_inc.index < day] df_inc = df_inc.iloc[-365*5:] var = np.percentile(df_inc, percent) #ib_inc = Asset('PO.IB0010').nav().pct_change() #lrb_inc = Asset('PO.LRB010').nav().pct_change() #dates = ib_inc.index & lrb_inc.index #ib_inc = ib_inc.loc[dates] #lrb_inc = lrb_inc.loc[dates] #ib_lrb_inc = ib_inc * 0.2 + lrb_inc * 0.8 #ib_lrb_inc = ib_lrb_inc.reindex(df_inc.index).fillna(0.0) #ib_lrb_inc[ib_lrb_inc == 0] = df_inc[ib_lrb_inc == 0] #df_inc = ib_lrb_inc #df_nav = (df_inc + 1).cumprod() #df_inc = df_nav.pct_change(period).fillna(0.0) #df_inc = df_inc[df_inc.index < day] #df_inc = df_inc.iloc[-365*5:] #var = np.percentile(df_inc, percent) return var
def macroview_retcompare(ctx, st_date, ed_date): startDate = parse(st_date) endDate = parse(ed_date) assetsID = { '120000001': '沪深300', '120000002': '中证500', '120000013': '标普500', '120000015': '恒生指数', '120000014': '沪金指数', '120000010': '中证国债', '120000011': '中证信用债' } #assetsRet = {'120000001':0.2743,'120000002':0.3576,'120000013':0.0953,'120000015':0.0997,'120000014':-0.0029,'120000010':0.0009,'120000011':0.0032} assets = dict([(asset_id, base_ra_index_nav.load_series(asset_id)) for asset_id in list(assetsID.keys())]) df_assets = pd.DataFrame(assets).loc[startDate:endDate, ].fillna( method='pad') assetsRet = dict([( asset_id, df_assets.loc[endDate, asset_id] / df_assets.loc[startDate, asset_id] - 1.0) for asset_id in list(assetsID.keys())]) # #计算给定指数和日期的持有期收益 df_assets = pd.DataFrame(assets) df_assets = df_assets.rolling(365).apply(lambda x: x[-1] / x[0] - 1, raw=True) df = df_assets.reset_index() tradedaysDiff = df[df.date == endDate].index.tolist()[0] - df[ df.date == startDate].index.tolist()[0] annualMulty = 365 / tradedaysDiff MacroCompare = [] for key, value in assetsRet.items(): values = value * annualMulty ser = df_assets[key].dropna() ser = ser.sort_values() if len(ser) == 0: continue MacroCompare.append( (assetsID[key], 1 - len(ser[ser < values]) / len(ser))) df_MacroCompare = pd.DataFrame(MacroCompare, columns=['ra_index', '分位数']) #print(df_MacroCompare) ser = pd.Series(assetsRet) ret_df = pd.DataFrame(columns=ser.index) ret_df.loc[endDate] = ser ret_df = ret_df.rename(columns=assetsID) print(ret_df) df_MacroCompare['date'] = endDate df_MacroCompare = df_MacroCompare.set_index(['date', 'ra_index']).unstack() df_MacroCompare.columns = df_MacroCompare.columns.get_level_values(1) df_MacroCompare = df_MacroCompare[ret_df.columns] df_MacroCompare.columns = df_MacroCompare.columns + ' 分位数' df = pd.concat([ret_df, df_MacroCompare], axis=1) print(df) df.to_csv('宏观观点数据.csv', encoding='gbk')
def load_nav_series(asset_id, reindex=None, begin_date=None, end_date=None): prefix = asset_id[0:2] if prefix.isdigit(): xtype = int(asset_id) // 10000000 if xtype == 1: # # 基金池资产 # asset_id = int(asset_id) % 10000000 (pool_id, category) = (asset_id // 100, asset_id % 100) ttype = pool_id // 10000 sr = asset_ra_pool_nav.load_series(pool_id, category, ttype, reindex=reindex, begin_date=begin_date, end_date=end_date) elif xtype == 3: # # 基金池资产 # sr = base_ra_fund_nav.load_series(asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) elif xtype == 4: # # 修型资产 # sr = asset_rs_reshape_nav.load_series(asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) elif xtype == 12: # # 指数资产 # sr = base_ra_index_nav.load_series(asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) else: sr = pd.Series() else: if prefix == 'AP': # # 基金池资产 # sr = asset_ra_pool_nav.load_series(asset_id, 0, 9, reindex=reindex, begin_date=begin_date, end_date=end_date) elif prefix == 'FD': # # 基金资产 # sr = base_ra_fund_nav.load_series(asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) elif prefix == 'RS': # # 修型资产 # sr = asset_rs_reshape_nav.load_series(asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) elif prefix == 'IX': # # 指数资产 # sr = base_ra_index_nav.load_series(asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) elif prefix == 'ER': sr = base_exchange_rate_index_nav.load_series( asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) elif prefix == 'SK': # # 股票资产 # sr = db.asset_stock.load_stock_nav_series( asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) elif prefix == 'MZ': # # Markowitz asset # sr = db.asset_mz_markowitz_nav.load_series( asset_id, reindex=reindex, begin_date=begin_date, end_date=end_date) elif prefix == 'PO': # # Markowitz asset # sr = db.asset_ra_portfolio_nav.load_series( asset_id, 9, reindex=reindex, begin_date=begin_date, end_date=end_date) else: sr = pd.Series() return sr
def allocate_benchmark_comp(ctx): index_ids = ['120000016', '120000010'] data = {} for _id in index_ids: data[_id] = base_ra_index_nav.load_series(_id) df = pd.DataFrame(data) composite_asset_ids = [ '20201', '20202', '20203', '20204', '20205', '20206', '20207', '20208' ] data = {} for _id in composite_asset_ids: nav = asset_ra_composite_asset_nav.load_nav(_id) nav = nav.reset_index() nav = nav[['ra_date', 'ra_nav']] nav = nav.set_index(['ra_date']) data[_id] = nav.ra_nav bench_df = pd.DataFrame(data) benchmark_df = pd.concat([bench_df, df], axis=1, join_axes=[bench_df.index]) conn = MySQLdb.connect(**config.db_asset) conn.autocommit(True) dfs = [] for i in range(0, 10): sql = 'select on_date as date, on_nav as nav from on_online_nav where on_online_id = 80000%d and on_type = 8' % i df = pd.read_sql(sql, conn, index_col=['date'], parse_dates=['date']) df.columns = ['risk_' + str(i)] dfs.append(df) df = pd.concat(dfs, axis=1) conn.close() df = pd.concat([df, benchmark_df], axis=1, join_axes=[df.index]) df = df.fillna(method='pad') df = df.rename( columns={ 'risk_0': '风险10', 'risk_1': '风险1', 'risk_2': '风险2', 'risk_3': '风险3', 'risk_4': '风险4', 'risk_5': '风险5', 'risk_6': '风险6', 'risk_7': '风险7', 'risk_8': '风险8', 'risk_9': '风险9', '20201': '风险2比较基准', '20202': '风险3比较基准', '20203': '风险4比较基准', '20204': '风险5比较基准', '20205': '风险6比较基准', '20206': '风险7比较基准', '20207': '风险8比较基准', '20208': '风险9比较基准', '120000016': '风险10比较基准', '120000010': '风险1比较基准' }) cols = [ '风险1', '风险2', '风险3', '风险4', '风险5', '风险6', '风险7', '风险8', '风险9', '风险10', '风险1比较基准', '风险2比较基准', '风险3比较基准', '风险4比较基准', '风险5比较基准', '风险6比较基准', '风险7比较基准', '风险8比较基准', '风险9比较基准', '风险10比较基准' ] df = df[cols] #df.to_csv('online_benchmark.csv', encoding='gbk') result_df = pd.DataFrame(columns=df.columns) last_day = df.index[-1] #print(last_day) result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 当日'] = df.pct_change().iloc[-1] result_df.loc[ df.index[-1].strftime('%Y-%m-%d') + ' 过去一周'] = df.loc[last_day] / df.loc[last_day - timedelta(weeks=1)] - 1 result_df.loc[ df.index[-1].strftime('%Y-%m-%d') + ' 过去一月'] = df.loc[last_day] / df.loc[last_day - timedelta(days=31)] - 1 result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去三个月'] = df.loc[last_day] / df.loc[last_day - timedelta(days=91)] - 1 result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去六个月'] = df.loc[last_day] / df.loc[last_day - timedelta( days=182)] - 1 result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一年'] = df.loc[last_day] / df.loc[last_day - timedelta(days=365)] - 1 #result_df.to_csv('智能组合收益与比较基准收益比较.csv', encoding='gbk') df = result_df df = df.reset_index() df['date'] = pd.Series(None) df['statistics_type'] = pd.Series(None) df = df.apply(split_ct, axis=1) df.pop('index') df.set_index('date', inplace=True) cols_list = list(df.columns) cols_list.insert(0, cols_list.pop(-1)) df = df[cols_list] if len(df) < 1: print("无数据需要插入") return # 开始注入数据 engine = database.connection('asset') Session = sessionmaker(bind=engine) session = Session() for i in range(len(df)): ins = asset_allocate.smart_risk(sir_date=df.index[i], sir_statistics_type=df.iloc[i, 0], sir_risk1=df.iloc[i, 1], sir_risk2=df.iloc[i, 2], sir_risk3=df.iloc[i, 3], sir_risk4=df.iloc[i, 4], sir_risk5=df.iloc[i, 5], sir_risk6=df.iloc[i, 6], sir_risk7=df.iloc[i, 7], sir_risk8=df.iloc[i, 8], sir_risk9=df.iloc[i, 9], sir_risk10=df.iloc[i, 10], sir_risk1_standard=df.iloc[i, 11], sir_risk2_standard=df.iloc[i, 12], sir_risk3_standard=df.iloc[i, 13], sir_risk4_standard=df.iloc[i, 14], sir_risk5_standard=df.iloc[i, 15], sir_risk6_standard=df.iloc[i, 16], sir_risk7_standard=df.iloc[i, 17], sir_risk8_standard=df.iloc[i, 18], sir_risk9_standard=df.iloc[i, 19], sir_risk10_standard=df.iloc[i, 20]) session.add(ins) session.commit() print("成功插入了 %d 条数据;" % (i + 1))
def macroview_retcompare(ctx, st_date, ed_date): startDate = parse(st_date) endDate = parse(ed_date) assetsID = { '120000001': '沪深300', '120000002': '中证500', '120000013': '标普500', '120000015': '恒生指数', '120000014': '沪金指数', '120000010': '中证国债', '120000011': '中证信用债' } #assetsRet = {'120000001':0.2743,'120000002':0.3576,'120000013':0.0953,'120000015':0.0997,'120000014':-0.0029,'120000010':0.0009,'120000011':0.0032} assets = dict([(asset_id, base_ra_index_nav.load_series(asset_id)) for asset_id in list(assetsID.keys())]) df_assets = pd.DataFrame(assets).loc[startDate:endDate, ].fillna( method='pad') assetsRet = dict([( asset_id, df_assets.loc[endDate, asset_id] / df_assets.loc[startDate, asset_id] - 1.0) for asset_id in list(assetsID.keys())]) # #计算给定指数和日期的持有期收益 df_assets = pd.DataFrame(assets) df_assets = df_assets.rolling(365).apply(lambda x: x[-1] / x[0] - 1, raw=True) df = df_assets.reset_index() tradedaysDiff = df[df.date == endDate].index.tolist()[0] - df[ df.date == startDate].index.tolist()[0] annualMulty = 365 / tradedaysDiff MacroCompare = [] for key, value in assetsRet.items(): values = value * annualMulty ser = df_assets[key].dropna() ser = ser.sort_values() if len(ser) == 0: continue MacroCompare.append( (assetsID[key], 1 - len(ser[ser < values]) / len(ser))) df_MacroCompare = pd.DataFrame(MacroCompare, columns=['ra_index', '分位数']) #print(df_MacroCompare) ser = pd.Series(assetsRet) ret_df = pd.DataFrame(columns=ser.index) ret_df.loc[endDate] = ser ret_df = ret_df.rename(columns=assetsID) print(ret_df) df_MacroCompare['date'] = endDate df_MacroCompare = df_MacroCompare.set_index(['date', 'ra_index']).unstack() df_MacroCompare.columns = df_MacroCompare.columns.get_level_values(1) df_MacroCompare = df_MacroCompare[ret_df.columns] df_MacroCompare.columns = df_MacroCompare.columns + ' 分位数' df = pd.concat([ret_df, df_MacroCompare], axis=1) print(df) # 开始注入数据 if len(df) < 1: print("无数据需要插入") return engine = database.connection('asset') Session = sessionmaker(bind=engine) session = Session() for count, index in enumerate(df.index): ins = asset_allocate.opinion( #id = None, oi_date=index, oi_return_CSI300=df.loc[index, df.columns[0]], oi_return_IC500=df.loc[index, df.columns[1]], oi_return_SP500=df.loc[index, df.columns[2]], oi_return_HSI=df.loc[index, df.columns[3]], oi_return_SQau=df.loc[index, df.columns[4]], oi_return_CSI_TB=df.loc[index, df.columns[5]], oi_return_CSI_DB=df.loc[index, df.columns[6]], #oi_comment = None ) session.add(ins) session.commit() print("成功插入 %d 条数据;" % (count + 1)) session.close()
def allocate_benchmark_comp(ctx): index_ids = ['120000016', '120000010'] data = {} for _id in index_ids: data[_id] = base_ra_index_nav.load_series(_id) df = pd.DataFrame(data) composite_asset_ids = [ '20201', '20202', '20203', '20204', '20205', '20206', '20207', '20208' ] data = {} for _id in composite_asset_ids: nav = asset_ra_composite_asset_nav.load_nav(_id) nav = nav.reset_index() nav = nav[['ra_date', 'ra_nav']] nav = nav.set_index(['ra_date']) data[_id] = nav.ra_nav bench_df = pd.DataFrame(data) benchmark_df = pd.concat([bench_df, df], axis=1, join_axes=[bench_df.index]) conn = MySQLdb.connect(**config.db_asset) conn.autocommit(True) dfs = [] for i in range(0, 10): sql = 'select on_date as date, on_nav as nav from on_online_nav where on_online_id = 80000%d and on_type = 8' % i df = pd.read_sql(sql, conn, index_col=['date'], parse_dates=['date']) df.columns = ['risk_' + str(i)] dfs.append(df) df = pd.concat(dfs, axis=1) conn.close() df = pd.concat([df, benchmark_df], axis=1, join_axes=[df.index]) df = df.fillna(method='pad') df = df.rename( columns={ 'risk_0': '风险10', 'risk_1': '风险1', 'risk_2': '风险2', 'risk_3': '风险3', 'risk_4': '风险4', 'risk_5': '风险5', 'risk_6': '风险6', 'risk_7': '风险7', 'risk_8': '风险8', 'risk_9': '风险9', '20201': '风险2比较基准', '20202': '风险3比较基准', '20203': '风险4比较基准', '20204': '风险5比较基准', '20205': '风险6比较基准', '20206': '风险7比较基准', '20207': '风险8比较基准', '20208': '风险9比较基准', '120000016': '风险10比较基准', '120000010': '风险1比较基准' }) cols = [ '风险1', '风险2', '风险3', '风险4', '风险5', '风险6', '风险7', '风险8', '风险9', '风险10', '风险1比较基准', '风险2比较基准', '风险3比较基准', '风险4比较基准', '风险5比较基准', '风险6比较基准', '风险7比较基准', '风险8比较基准', '风险9比较基准', '风险10比较基准' ] df = df[cols] result_df = pd.DataFrame(columns=df.columns) last_day = df.index[-1] result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 当日'] = df.pct_change().iloc[-1] result_df.loc[ df.index[-1].strftime('%Y-%m-%d') + ' 过去一周'] = df.loc[last_day] / df.loc[last_day - timedelta(weeks=1)] - 1 result_df.loc[ df.index[-1].strftime('%Y-%m-%d') + ' 过去一月'] = df.loc[last_day] / df.loc[last_day - timedelta(days=31)] - 1 result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去三个月'] = df.loc[last_day] / df.loc[last_day - timedelta(days=91)] - 1 result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去六个月'] = df.loc[last_day] / df.loc[last_day - timedelta( days=182)] - 1 result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一年'] = df.loc[last_day] / df.loc[last_day - timedelta(days=365)] - 1 result_df.to_csv('智能组合收益与比较基准收益比较.csv', encoding='gbk')
def cal_layer_type(): engine = database.connection('asset') Session = sessionmaker(bind=engine) session = Session() sql1 = session.query(factor_cluster_asset.fc_asset_id).filter( factor_cluster_asset.globalid == 'FC.000004') asset_ids = [asset[0] for asset in sql1.all()] assets = {} for asset_id in asset_ids: assets[asset_id] = load_nav_series(asset_id) trade_dates = DBData.trade_dates(start_date='2010-06-01', end_date='2018-12-01') df_assets = pd.DataFrame(assets) # df_assets = df_assets[df_assets.index >= start_date] # df_assets = df_assets[df_assets.index <= end_date] df_assets = df_assets.reindex(trade_dates).dropna() df_ret = df_assets.pct_change().dropna() layer_info = pd.read_csv('data/df_result.csv', index_col=0, parse_dates=True) dates = layer_info.index.unique() sh300 = base_ra_index_nav.load_series('120000001') sh300 = sh300.reindex(trade_dates).pct_change().dropna() zz500 = base_ra_index_nav.load_series('120000002') zz500 = zz500.reindex(trade_dates).pct_change().dropna() cyb = base_ra_index_nav.load_series('120000018') cyb = cyb.reindex(trade_dates).pct_change().dropna() for i in range(12, len(dates)): start_date = dates[i - 12] end_date = dates[i] layers = layer_info.loc[end_date].layer.unique() tmp_sh300 = sh300.loc[start_date.date():end_date.date()] tmp_zz500 = zz500.loc[start_date.date():end_date.date()] tmp_cyb = cyb.loc[start_date.date():end_date.date()] for layer in layers: layer_factor_id = layer_info[layer_info.layer == layer].loc[end_date].factor_id if type(layer_factor_id) == str: layer_factor_id = np.array([layer_factor_id]) else: layer_factor_id = layer_factor_id.values layer_ret = df_ret.loc[start_date.date():end_date.date(), layer_factor_id] layer_ret = layer_ret.mean(1) # layer_nav = (1+layer_ret.mean(1)).cumprod() sh300_corr = np.corrcoef(layer_ret, tmp_sh300)[0][1] zz500_corr = np.corrcoef(layer_ret, tmp_zz500)[0][1] cyb_corr = np.corrcoef(layer_ret, tmp_cyb)[0][1] corr_list = [sh300_corr, zz500_corr, cyb_corr] max_corr = max(corr_list) if max_corr < 0.85: sign = 'unknown' elif sh300_corr == max_corr: sign = 'sh300' elif zz500_corr == max_corr: sign = 'zz500' elif cyb_corr == max_corr: sign = 'cybzs' print end_date, layer, sign, sh300_corr, zz500_corr, cyb_corr
def allocate_benchmark_comp(): index_ids = ['120000016', '120000010'] data = {} for _id in index_ids: data[_id] = base_ra_index_nav.load_series(_id) df = pd.DataFrame(data) composite_asset_ids = [ '20201', '20202', '20203', '20204', '20205', '20206', '20207', '20208' ] data = {} for _id in composite_asset_ids: nav = asset_ra_composite_asset_nav.load_nav(_id) nav = nav.reset_index() nav = nav[['ra_date', 'ra_nav']] nav = nav.set_index(['ra_date']) data[_id] = nav.ra_nav bench_df = pd.DataFrame(data) benchmark_df = pd.concat([bench_df, df], axis=1, join_axes=[bench_df.index]) conn = MySQLdb.connect(**config.db_asset) conn.autocommit(True) dfs = [] for i in range(0, 10): sql = 'select on_date as date, on_nav as nav from on_online_nav where on_online_id = 80000%d and on_type = 8' % i df = pd.read_sql(sql, conn, index_col=['date'], parse_dates=['date']) df.columns = ['risk_' + str(i)] dfs.append(df) df = pd.concat(dfs, axis=1) conn.close() df = pd.concat([df, benchmark_df], axis=1, join_axes=[df.index]) df = df.fillna(method='pad') df = df.rename( columns={ 'risk_0': '风险10', 'risk_1': '风险1', 'risk_2': '风险2', 'risk_3': '风险3', 'risk_4': '风险4', 'risk_5': '风险5', 'risk_6': '风险6', 'risk_7': '风险7', 'risk_8': '风险8', 'risk_9': '风险9', '20201': '风险2比较基准', '20202': '风险3比较基准', '20203': '风险4比较基准', '20204': '风险5比较基准', '20205': '风险6比较基准', '20206': '风险7比较基准', '20207': '风险8比较基准', '20208': '风险9比较基准', '120000016': '风险10比较基准', '120000010': '风险1比较基准' }) cols = [ '风险1', '风险2', '风险3', '风险4', '风险5', '风险6', '风险7', '风险8', '风险9', '风险10', '风险1比较基准', '风险2比较基准', '风险3比较基准', '风险4比较基准', '风险5比较基准', '风险6比较基准', '风险7比较基准', '风险8比较基准', '风险9比较基准', '风险10比较基准' ] df = df[cols] result_df = pd.DataFrame(columns=df.columns) last_day = df.index[-1] print(last_day) first_day = df.index[0] print(first_day) #result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 当日'] = df.pct_change().iloc[-1] #result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一周'] = df.loc[last_day] / df.loc[last_day - timedelta(weeks = 1)] - 1 #result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一月'] = df.loc[last_day] / df.loc[last_day - timedelta(days = 31)] - 1 #result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去三个月'] = df.loc[last_day] / df.loc[last_day - timedelta(days = 91)] - 1 #result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去六个月'] = df.loc[last_day] / df.loc[last_day - timedelta(days = 182)] - 1 #result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一年'] = df.loc[last_day] / df.loc[last_day - timedelta(days = 365)] - 1 # 非滚动战胜概率 length = len(df) // 7 # length = len(df)//31 # length = len(df)//91 # length = len(df)//182 # length = len(df)//365 k1 = 0 k2 = 0 k3 = 0 k4 = 0 k5 = 0 k6 = 0 k7 = 0 k8 = 0 k9 = 0 k10 = 0 days = df.index.values for i in range(length): num = -1 - i * 7 # num = -1 - i*31 # num = -1 - i*91 # num = -1 - i*182 # num = -1 - i*365 last_day = pd.to_datetime(str(days[num])) result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一周'] = df.loc[last_day] / df.loc[ last_day - timedelta(weeks=1)] - 1 # result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一月'] = df.loc[last_day] / df.loc[last_day - timedelta(days = 31)] - 1 # result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去三个月'] = df.loc[last_day] / df.loc[last_day - timedelta(days = 91)] - 1 # result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去六个月'] = df.loc[last_day] / df.loc[last_day - timedelta(days = 182)] - 1 # result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一年'] = df.loc[last_day] / df.loc[last_day - timedelta(days = 365)] - 1 if result_df['风险1'][0] > result_df['风险1比较基准'][0]: k1 += 1 if result_df['风险2'][0] > result_df['风险2比较基准'][0]: k2 += 1 if result_df['风险3'][0] > result_df['风险3比较基准'][0]: k3 += 1 if result_df['风险4'][0] > result_df['风险4比较基准'][0]: k4 += 1 if result_df['风险5'][0] > result_df['风险5比较基准'][0]: k5 += 1 if result_df['风险6'][0] > result_df['风险6比较基准'][0]: k6 += 1 if result_df['风险7'][0] > result_df['风险7比较基准'][0]: k7 += 1 if result_df['风险8'][0] > result_df['风险8比较基准'][0]: k8 += 1 if result_df['风险9'][0] > result_df['风险9比较基准'][0]: k9 += 1 if result_df['风险10'][0] > result_df['风险10比较基准'][0]: k10 += 1 # 滚动战胜概率 # length = len(df)-7 # length = len(df)//7 length = len(df) // 30 k1 = 0 k2 = 0 k3 = 0 k4 = 0 k5 = 0 k6 = 0 k7 = 0 k8 = 0 k9 = 0 k10 = 0 days = df.index.values for i in range(length): # num = -1 - i # num = -1 - i*7 # num = -1 - i*30 last_day = pd.to_datetime(str(days[num])) delta_day = last_day - timedelta(days=31) choose_dates = df[df.index <= delta_day].index.values if len(choose_dates) == 0: break delta_day = pd.to_datetime(str(choose_dates.max())) # result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一周'] = df.loc[last_day] / df.loc[delta_day] - 1 result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去一月'] = df.loc[last_day] / df.loc[delta_day] - 1 # result_df.loc[df.index[-1].strftime('%Y-%m-%d') + ' 过去三个月'] = df.loc[last_day] / df.loc[delta_day] - 1 if result_df['风险1'][0] > result_df['风险1比较基准'][0]: k1 += 1 if result_df['风险2'][0] > result_df['风险2比较基准'][0]: k2 += 1 if result_df['风险3'][0] > result_df['风险3比较基准'][0]: k3 += 1 if result_df['风险4'][0] > result_df['风险4比较基准'][0]: k4 += 1 if result_df['风险5'][0] > result_df['风险5比较基准'][0]: k5 += 1 if result_df['风险6'][0] > result_df['风险6比较基准'][0]: k6 += 1 if result_df['风险7'][0] > result_df['风险7比较基准'][0]: k7 += 1 if result_df['风险8'][0] > result_df['风险8比较基准'][0]: k8 += 1 if result_df['风险9'][0] > result_df['风险9比较基准'][0]: k9 += 1 if result_df['风险10'][0] > result_df['风险10比较基准'][0]: k10 += 1 r1 = k1 / length r2 = k2 / length r3 = k3 / length r4 = k4 / length r5 = k5 / length r6 = k6 / length r7 = k7 / length r8 = k8 / length r9 = k9 / length r10 = k10 / length print([r1, r2, r3, r4, r5, r6, r7, r8, r9, r10])