概述
1- 读仓位信息:
(1)先简单存到dic中,时间是倒序,在构造time_list中reverse即可
(2) str,int转换 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- 读取收盘价:
取出来后的数据转格式:
df_close_f = df_close.pivot(index='时间',columns='股票代码',values='CLOSE')
取tb_object_1425 赋权收盘价,代码略
3- 计算股票端收益率:
(1) df.pct_change(1)
计算股票个券收益率
(2) 用np.dot(df_r,df_pos)
矩阵计算,得到股票端收益率
(3) 用矩阵计算要实现对齐数据s_index = df_pos['股票代码'] df_r = df_r.loc[:,s_index]
或用自定义函数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 是对应位置加减,dataframe与series运算.add, .sub , .div 再复杂的运算可转为array,进行换算, 注意换算后是否要转置
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,期间仓位逐渐递增
# 是占净值的比例,要根据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)平均年化收益率
最后
以上就是正直发带为你收集整理的python 股票策略_每季度仓位写回测的全部内容,希望文章能够帮你解决python 股票策略_每季度仓位写回测所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复