摘要
1.时间序列用字典存储
dic ={}
for date in close.index:
***
dic[date] = [...]
result = pd.DataFrame(dic_result,index=['...']).T
#注意要转置
方便之处在于不用切片,书写时直接写变量即可
2.加布尔变量表示
for i,date in enumerate(close.index):
change = False
index = index*(1+index_change[date])
if (hs_change_pct + zz_change_pct) > 0.2 and (pos >= 0.15):
pos -= 0.05
change = True
signal = -1
elif (hs_change_pct + zz_change_pct) < -0.2 and (pos <= 0.75):
pos += 0.05
change = True
signal = 1
if change:
...
方便之处在于加仓减仓公式是一致的(带正负号)不用书写两遍
3.变量
写策略时,cash和equity分开
- 1.加减仓时
equity(t) = total_return(t-1) * pos(t) - ** 因此需要在信号时就把pos给改变 **
num_temp(t) = equity(t) * weight(t) / close(t) - 用temp来记录现在的num,来计算delta_num
cash(t) = cash(t-1) +(num(t-1)-temp_num(t))*close(t) - 在赋值给现在的num
num = num_temp - 2.条件外
不管加仓不加仓都要进行的操作
equity = num*close
return = equity+cash
4.策略代码
dic_result = {}
index_change = pd.Series((df_close['沪深300']/df_close['沪深300'].shift(1)+df_close['中证500']/df_close['中证500'].shift(1)-2)/2)
index_change[0] = 0
for i,date in enumerate(df_close.index):
change_rolling_time = False
change = False
index = index*(1+index_change[date])
hs_change_pct = df_close.loc[date, '沪深300'] / hs_benchmark - 1
zz_change_pct = df_close.loc[date, '中证500'] / zz_benchmark - 1
[hs_pct, zz_pct] = calc_pct(date)
if date == rolling_time[i]: #rolling-time时刻的调仓
pos = calc_total_pos(hs_pct, zz_pct) #更新仓位
change_rolling_time = True
signal_rolling = 1
else:
signal_rolling = 0
if (hs_change_pct + zz_change_pct) > 0.2 and (pos >= 0.15):
pos -= 0.05
# pos = calc_total_pos(hs_pct, zz_pct)
change = True
signal = -1
elif (hs_change_pct + zz_change_pct) < -0.2 and (pos <= 0.75):
pos += 0.05
# pos = calc_total_pos(hs_pct, zz_pct)
change = True
signal = 1
else:
signal = 0
change = False
if change or change_rolling_time:
# [hs_pct, zz_pct] = calc_pct(date)
hs_weight = calc_hs_weight(hs_pct, zz_pct)
euqity = total_return * pos
hs_num_temp = equity * hs_weight / df_close.loc[date, '沪深300']
zz_num_temp = equity * (1 - hs_weight) / df_close.loc[date, '中证500']
cash = cash + (hs_num - hs_num_temp) * df_close.loc[date, '沪深300'] + (zz_num - zz_num_temp) * df_close.loc[date, '中证500']
hs_num = hs_num_temp
zz_num = zz_num_temp
hs_benchmark = df_close.loc[date, '沪深300']
zz_benchmark = df_close.loc[date, '中证500']
euqity = hs_num * df_close.loc[date, '沪深300'] + zz_num * df_close.loc[date, '中证500']
total_return = euqity + cash
dic_result[date] = [total_return,pos,signal_rolling,signal,index]