15.5风险控制建模-布林强盗,一个霸道的交易系统

用户头像Reflecti0N
2023-08-07 发布

作为策略锦集第五篇,再向大家介绍一个霸道的交易系统—布林强盗交易系统。

import pandas as pd 
import numpy as np 
# 初始化函数,全局只运行一次
def init(context):
    context.security = '159919.OF' #沪深300指数ETF为例 
    set_benchmark(context.security)
    context.steam = False
    context.mid50 = 0#储存中轨  每日更新以下5个数据
    context.up50 = 0#储存上轨
    context.close = 0#储存上个交易日的收盘价
    context.closemax = 0#储存过去30个交易日的收盘价最大值
    context.day = 50 #自适应均线计算,没持仓一天,减去1
    context.maday = 0 #储存自适应均线值

#每日开盘前9:00被调用一次,用于储存自定义参数、全局变量,执行盘前选股等
def before_trading(context):
    #开盘前获取中轨,上轨,自适应均线,昨日收盘价,前三十日收盘价,放置账户信息中,以便调用
    close = history(context.security, ['close'], 50, '1d', False, 'pre', is_panel=1)['close']
    context.maday = np.mean(close[-context.day:])
    context.mid50 = np.mean(close) #50日均线,中轨
    context.up50 = context.mid50 + np.std(close) #上轨=中规+1*标准差
    context.close = close[-1]
    context.closemax = max(close[-31:-1])

## 开盘时运行函数
def handle_bar(context, bar_dict):
#判断系统开启条件
    if context.steam == False:
        context.steam = steam(context,bar_dict)
        if context.steam == True:
            #满足系统开启条件买入
            order_target_percent(context.security,1)
        else:
            pass
    #判断系统是否需要止损或者止盈,以关闭系统
    elif context.steam == True:
        trade=giveuptrade(context,bar_dict)
        if trade =='sell':
            #需要止损,并关闭系统,自适应天数回复
            order_target(context.security,0)
            context.steam = False
            context.day = 50
        else:
            #不需要止损,但是需要将自适应天数减去1
            context.day=context.day-1
            if context.day <10:
                context.day = 10
            pass
#离场条件判断,系统是否需要关闭
def giveuptrade(context,bar_dict):#day参数主要是计算自适应均线
    if context.close < context.maday:
        if context.maday < context.up50:
            return 'sell'
        else:
            return None
    else:
        return None
#入场条件判断,系统是否需要开启
def steam(context,bar_dict):
    if context.close > context.up50:
        if context.close > context.closemax:
            return True 
        else:
            return False 
    else:
        return False
收益&风险
源码

评论