python 积累4

2018-12-19  本文已影响0人  黄yy家的jby

摘要

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分开

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]
上一篇 下一篇

猜你喜欢

热点阅读