双动力策略

双动力策略是期货领域非常有名的策略,这里我们把这个策略移植到了股票领域,由于股票只能做多,因此我们把期货做空的策略逻辑直接删除,即可得股票的双动力策略。策略的逻辑如下图所示:

这里有做空的逻辑,我们把他删掉,直接利用做多的逻辑,程序代码如下:

import talib

def initialize(context):
    # 初始化此策略
    # 设置我们要操作的股票池, 这里我们只操作一支股票
    g.security = '600570.SS'
    set_universe(g.security)
    g.K1 = 0.4
    g.K2 = 0.6
    g.buy = 0
    
#当五日均线高于十日均线时买入,当五日均线低于十日均线时卖出
def handle_data(context, data):
    security = g.security
    # 获取历史价格,最高价
    H = get_history(30, '1d', field = 'high', fq = 'pre')
    # 获取历史价格,最低价
    L = get_history(30, '1d', field = 'low', fq = 'pre')
    # 获取历史价格,收盘价
    C = get_history(30, '1d', field = 'close', fq = 'pre')
    # 获取历史价格,开盘价
    O = get_history(30, '1d', field = 'open', fq = 'pre')
    # 最高价最高价
    HH = H[security].max()
    # 收盘价最低价
    LC = C[security].min()
    # 收盘价最高价
    HC = C[security].max()
    # 最低价最低价
    LL = L[security].min()
    
    # 用于计算入场指标
    Range = max(HH - LC, HC - LL)
    
    # 计算移动平均线
    ma10 = talib.MA(C[security].values, 20)
    
    JX = ma10[-1]
    ZSX = min(ma10[-11:-1])
    
    amount = context.portfolio.positions[security]['amount']
    cash = context.portfolio.cash
    
    if H[security][-1] > (O[security][-1] + g.K1 * Range) and C[security][-1] > JX and amount == 0:
        # 全部的可用资金买入
        order_target_value(security, cash)
        # 记录买入价格
        g.buy = C[security][-1]
    if (L[security][-1] < (O[security][-1] - g.K2 * Range) and amount > 0) or (L[security][-1] > g.buy and L[security][-1] < ZSX):
        order_target(security, 0)
        g.buy = 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章