1- 讀倉位信息:
(1)先簡單存到dic中,時間是倒序抡四,在構(gòu)造time_list中reverse即可
(2) str,int轉(zhuǎn)換 int(''.join(str1.split('-'))
def read_date(file_name):
df_all = pd.read_excel(file_name+'.xlsx',header=None)
df_all = df_all.dropna(axis=0,how='all')
df_all.columns = ['股票代碼','股票名稱','占基金凈值比(%)']
df_all = df_all.reset_index(drop=True)
judge = df_all[df_all.iloc[:,0] == '股票代碼']
dic = {}
for i,s_index in enumerate(judge.index):
time = df_all['股票代碼'].iloc[s_index-1]
time = ''.join(time.split('-'))
if s_index != judge.index[-1]:
df_temp = df_all.iloc[s_index+1:judge.index[i+1]-1,:]
else:
df_temp = df_all.iloc[s_index+1:,:]
dic[time] = df_temp
return dic
2- 讀取收盤價:
取出來后的數(shù)據(jù)轉(zhuǎn)格式:
df_close_f = df_close.pivot(index='時間',columns='股票代碼',values='CLOSE')
取tb_object_1425 賦權(quán)收盤價腕够,代碼略
3- 計算股票端收益率:
(1) df.pct_change(1)
計算股票個券收益率
(2) 用np.dot(df_r,df_pos)
矩陣計算蜂桶,得到股票端收益率
(3) 用矩陣計算要實現(xiàn)對齊數(shù)據(jù)s_index = df_pos['股票代碼'] \ df_r = df_r.loc[:,s_index]
或用自定義函數(shù)ircp.ORDER_LIST(): df = df.set_index(target_columns) \ df = df.loc[s_index,:] \ df = df.reset_index()
def get_stock_r(dic, dic_close):
time_list = list(dic.keys())
time_list.reverse()
dic_stock_r ={}
for time in time_list:
df_pos = dic[time]
df_pos = df_pos.dropna()
df_close = dic_close[time]
df_r = df_close.pct_change(1)
df_r = df_r.dropna()
# df_r的 columns 和 df_pos 的index 要匹配
s_index = df_pos['股票代碼']
df_r = df_r.loc[:,s_index]
# 提高計算精度几晤,收益率乘以100
np_stock_r = np.dot(np.array(df_r), np.array(df_pos['占基金凈值比(%)']))
df_stock_r = pd.DataFrame(np_stock_r,index=df_r.index,columns=['stock_r'])
dic_stock_r[time] = df_stock_r
return dic_stock_r
4- 運行策略:
(1)逐漸建倉 倉位 np.linspace(0,0.8,len(xxx)
(2)非滿倉下認為投貨幣基金
(3)series 是對應(yīng)位置加減盛撑,dataframe與series運算.add, .sub , .div 再復(fù)雜的運算可轉(zhuǎn)為array檬姥,進行換算曾我, 注意換算后是否要轉(zhuǎn)置
def run_strategy(dic_stock_r, s_date):
time_list = list(dic_stock_r.keys())
start_date = int(time_list[0])
end_date = ircp.CLOSE_DATE(s_date,freq='quarter')
money_fund = 。健民。抒巢。
df_r = pd.DataFrame() # 記錄最后的總收益
for time in time_list:
df_stock_r = dic_stock_r[time]
df_stock_r.index = df_stock_r.index.astype(int)
df_fund_r = money_fund.loc[df_stock_r.index, 'N_RETURN']
df_fund_r = (df_fund_r - 1) * 100 # 提高計算精度,收益率乘以100
# 第一期逐漸建倉
if time == time_list[0]:
# 期末倉位0.8秉犹,期間倉位逐漸遞增
# 是占凈值的比例蛉谜,要根據(jù)0.8折算
stock_pos = np.linspace(0,0.8,len(df_stock_r))
fund_pos = 1-stock_pos
df_r_temp = np.array(df_stock_r.T)*stock_pos/0.8 + np.array(df_fund_r.T)*fund_pos
df_r_temp = pd.DataFrame(df_r_temp.T,index=df_stock_r.index,columns=['r'])
else:
# 0.8的股票倉位 0.2 的貨幣基金倉位 是占凈值的比例,不用再乘以0.8
df_r_temp = (df_stock_r ).add(df_fund_r * 0.2,axis=0)
df_r_temp.columns = ['r']
df_r = pd.concat([df_r,df_r_temp],axis=0)
print(time)
print('整體收益率提取完成')
return df_r
5- 策略評判:
(1)最大回撤
(2)真實收益
(3)基準
(4)勝率
(5)平均年化收益率