复制链接
克隆策略

策略名称

通道突破策略——布林带指标

策略思路

指标计算: \ 中轨 = N时间段的简单移动平均线 \ 上轨 = 中轨 + K × N时间段的标准差 \ 下轨 = 中轨 − K × N时间段的标准差 \ 一般情况下,设定N=20和K=2,这两个数值也是在布林带当中使用最多的。在日线图里,N=20其实就是“月均线”(MA20)。依照正态分布规则,约有95%的数值会分布在距离平均值有正负2个标准差的范围内 交易规则:价格突破上轨(%b大于等于1),买入开仓,价格突破下轨(%b小于等于0),卖出开仓

    {"description":"实验创建于2023/2/10","graph":{"edges":[{"to_node_id":"-71:instruments","from_node_id":"-5:data"},{"to_node_id":"-127:instruments","from_node_id":"-5:data"},{"to_node_id":"-62:features","from_node_id":"-13:data"},{"to_node_id":"-71:features","from_node_id":"-13:data"},{"to_node_id":"-97:input_data","from_node_id":"-62:data"},{"to_node_id":"-62:input_data","from_node_id":"-71:data"},{"to_node_id":"-127:options_data","from_node_id":"-97:data"}],"nodes":[{"node_id":"-5","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2021-02-17","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-11-26","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_FUTURE","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"JM2201.DCE","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-5"}],"output_ports":[{"name":"data","node_id":"-5"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-13","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nbbands_up = ta_bbands_u(close, 20)\nbbands = ta_bbands_m(close, 20)\nbbands_low = ta_bbands_l(close, 20)","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-13"}],"output_ports":[{"name":"data","node_id":"-13"}],"cacheable":true,"seq_num":5,"comment":"","comment_collapsed":true},{"node_id":"-62","module_id":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","parameters":[{"name":"date_col","value":"date","type":"Literal","bound_global_parameter":null},{"name":"instrument_col","value":"instrument","type":"Literal","bound_global_parameter":null},{"name":"drop_na","value":"False","type":"Literal","bound_global_parameter":null},{"name":"remove_extra_columns","value":"False","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-62"},{"name":"features","node_id":"-62"}],"output_ports":[{"name":"data","node_id":"-62"}],"cacheable":true,"seq_num":6,"comment":"","comment_collapsed":true},{"node_id":"-71","module_id":"BigQuantSpace.use_datasource.use_datasource-v1","parameters":[{"name":"datasource_id","value":"bar1d_CN_FUTURE","type":"Literal","bound_global_parameter":null},{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-71"},{"name":"features","node_id":"-71"}],"output_ports":[{"name":"data","node_id":"-71"}],"cacheable":true,"seq_num":7,"comment":"","comment_collapsed":true},{"node_id":"-97","module_id":"BigQuantSpace.dropnan.dropnan-v2","parameters":[],"input_ports":[{"name":"input_data","node_id":"-97"},{"name":"features","node_id":"-97"}],"output_ports":[{"name":"data","node_id":"-97"}],"cacheable":true,"seq_num":8,"comment":"","comment_collapsed":true},{"node_id":"-127","module_id":"BigQuantSpace.hftrade.hftrade-v1","parameters":[{"name":"start_date","value":"2021-05-14","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-10-18","type":"Literal","bound_global_parameter":null},{"name":"initialize","value":"# 交易引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n context.all_data = context.options[\"data\"].read()\n \n","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"# 交易引擎:每个单位时间开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"handle_tick","value":"# 交易引擎:tick数据处理函数,每个tick执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 交易引擎:bar数据处理函数,每个时间单位执行一次\ndef bigquant_run(context, data):\n import pandas as pd \n today = data.current_dt.strftime('%Y-%m-%d') # 当前交易日期\n all_data = context.all_data[context.all_data.date == today]\n all_data = pd.DataFrame(all_data)\n if len(all_data) == 0:#过滤没有指标的数据\n return\n \n price = all_data['close'].iloc[0]\n high_line = all_data['bbands_up'].iloc[0]\n low_line = all_data['bbands_low'].iloc[0]\n instrument = context.future_symbol(context.instruments[0]) # 交易标的\n long_position = context.get_account_position(instrument, direction=Direction.LONG).avail_qty#多头持仓\n short_position = context.get_account_position(instrument, direction=Direction.SHORT).avail_qty#空头持仓\n curr_position = short_position + long_position#总持仓\n if short_position > 0:\n if price > high_line:\n context.buy_close(instrument, short_position, price, order_type=OrderType.MARKET)\n context.buy_open(instrument, 4, price, order_type=OrderType.MARKET)\n print(today,'先平空再开多')\n elif long_position > 0:\n if price < low_line:\n context.sell_close(instrument, long_position, price, order_type=OrderType.MARKET)\n context.sell_open(instrument, 4, price, order_type=OrderType.MARKET)\n print(today,'先平多再开空',curr_position)\n elif curr_position==0:\n if price > high_line:\n context.buy_open(instrument, 4, price, order_type=OrderType.MARKET)\n print('空仓开多')\n elif price<low_line:\n context.sell_open(instrument, 4, price, order_type=OrderType.MARKET)\n print('空仓开空')","type":"Literal","bound_global_parameter":null},{"name":"handle_trade","value":"# 交易引擎:成交回报处理函数,每个成交发生时执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"handle_order","value":"# 交易引擎:委托回报处理函数,每个委托变化时执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"after_trading","value":"# 交易引擎:盘后处理函数,每日盘后执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"capital_base","value":1000000,"type":"Literal","bound_global_parameter":null},{"name":"frequency","value":"daily","type":"Literal","bound_global_parameter":null},{"name":"price_type","value":"真实价格","type":"Literal","bound_global_parameter":null},{"name":"product_type","value":"期货","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":"","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"000300.HIX","type":"Literal","bound_global_parameter":null},{"name":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"disable_cache","value":"False","type":"Literal","bound_global_parameter":null},{"name":"show_debug_info","value":"False","type":"Literal","bound_global_parameter":null},{"name":"backtest_only","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-127"},{"name":"history_ds","node_id":"-127"},{"name":"benchmark_ds","node_id":"-127"},{"name":"options_data","node_id":"-127"}],"output_ports":[{"name":"raw_perf","node_id":"-127"}],"cacheable":false,"seq_num":9,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-5' Position='293,113,200,200'/><node_position Node='-13' Position='602,109,200,200'/><node_position Node='-62' Position='420,280,200,200'/><node_position Node='-71' Position='258,194,200,200'/><node_position Node='-97' Position='406,357,200,200'/><node_position Node='-127' Position='350,452,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [11]:
    # 本代码由可视化策略环境自动生成 2023年5月24日 18:13
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
     
    # 显式导入 BigQuant 相关 SDK 模块
    from bigdatasource.api import DataSource
    from biglearning.api import M
    from biglearning.api import tools as T
    from biglearning.module2.common.data import Outputs
    from bigtrader.constant import Direction
    
    # 交易引擎:初始化函数,只执行一次
    def m9_initialize_bigquant_run(context):
        context.all_data = context.options["data"].read()
        
    
    # 交易引擎:每个单位时间开盘前调用一次。
    def m9_before_trading_start_bigquant_run(context, data):
        pass
    
    # 交易引擎:tick数据处理函数,每个tick执行一次
    def m9_handle_tick_bigquant_run(context, data):
        pass
    
    # 交易引擎:bar数据处理函数,每个时间单位执行一次
    def m9_handle_data_bigquant_run(context, data):
        import pandas as pd 
        today = data.current_dt.strftime('%Y-%m-%d') # 当前交易日期
        all_data = context.all_data[context.all_data.date == today]
        all_data = pd.DataFrame(all_data)
        if len(all_data) == 0:#过滤没有指标的数据
            return
        
        price = all_data['close'].iloc[0]
        high_line = all_data['bbands_up'].iloc[0]
        low_line = all_data['bbands_low'].iloc[0]
        instrument = context.future_symbol(context.instruments[0]) # 交易标的
        long_position = context.get_account_position(instrument, direction=Direction.LONG).avail_qty#多头持仓
        short_position = context.get_account_position(instrument, direction=Direction.SHORT).avail_qty#空头持仓
        curr_position = short_position + long_position#总持仓
        if short_position > 0:
            if price > high_line:
                context.buy_close(instrument, short_position, price, order_type=OrderType.MARKET)
                context.buy_open(instrument, 4, price, order_type=OrderType.MARKET)
                print(today,'先平空再开多')
        elif long_position > 0:
            if price < low_line:
                context.sell_close(instrument, long_position, price, order_type=OrderType.MARKET)
                context.sell_open(instrument, 4, price, order_type=OrderType.MARKET)
                print(today,'先平多再开空',curr_position)
        elif curr_position==0:
            if price > high_line:
                context.buy_open(instrument, 4, price, order_type=OrderType.MARKET)
                print('空仓开多')
            elif price<low_line:
                context.sell_open(instrument, 4, price, order_type=OrderType.MARKET)
                print('空仓开空')
    # 交易引擎:成交回报处理函数,每个成交发生时执行一次
    def m9_handle_trade_bigquant_run(context, data):
        pass
    
    # 交易引擎:委托回报处理函数,每个委托变化时执行一次
    def m9_handle_order_bigquant_run(context, data):
        pass
    
    # 交易引擎:盘后处理函数,每日盘后执行一次
    def m9_after_trading_bigquant_run(context, data):
        pass
    
    
    m4 = M.instruments.v2(
        start_date='2021-02-17',
        end_date='2021-11-26',
        market='CN_FUTURE',
        instrument_list='JM2201.DCE',
        max_count=0
    )
    
    m5 = M.input_features.v1(
        features="""# #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    bbands_up = ta_bbands_u(close, 20)
    bbands = ta_bbands_m(close, 20)
    bbands_low = ta_bbands_l(close, 20)"""
    )
    
    m7 = M.use_datasource.v1(
        instruments=m4.data,
        features=m5.data,
        datasource_id='bar1d_CN_FUTURE',
        start_date='',
        end_date=''
    )
    
    m6 = M.derived_feature_extractor.v3(
        input_data=m7.data,
        features=m5.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m8 = M.dropnan.v2(
        input_data=m6.data
    )
    
    m9 = M.hftrade.v1(
        instruments=m4.data,
        options_data=m8.data,
        start_date='2021-05-14',
        end_date='2021-10-18',
        initialize=m9_initialize_bigquant_run,
        before_trading_start=m9_before_trading_start_bigquant_run,
        handle_tick=m9_handle_tick_bigquant_run,
        handle_data=m9_handle_data_bigquant_run,
        handle_trade=m9_handle_trade_bigquant_run,
        handle_order=m9_handle_order_bigquant_run,
        after_trading=m9_after_trading_bigquant_run,
        capital_base=1000000,
        frequency='daily',
        price_type='真实价格',
        product_type='期货',
        before_start_days='',
        benchmark='000300.HIX',
        plot_charts=True,
        disable_cache=False,
        show_debug_info=False,
        backtest_only=False
    )
    
    [2023-05-24 18:13:35.774940] INFO moduleinvoker: instruments.v2 开始运行..
    
    INFO:moduleinvoker:instruments.v2 开始运行..
    
    [2023-05-24 18:13:35.783077] INFO moduleinvoker: 命中缓存
    
    INFO:moduleinvoker:命中缓存
    
    [2023-05-24 18:13:35.786808] INFO moduleinvoker: instruments.v2 运行完成[0.011875s].
    
    INFO:moduleinvoker:instruments.v2 运行完成[0.011875s].
    
    [2023-05-24 18:13:35.794403] INFO moduleinvoker: input_features.v1 开始运行..
    
    INFO:moduleinvoker:input_features.v1 开始运行..
    
    [2023-05-24 18:13:35.802062] INFO moduleinvoker: 命中缓存
    
    INFO:moduleinvoker:命中缓存
    
    [2023-05-24 18:13:35.805765] INFO moduleinvoker: input_features.v1 运行完成[0.011345s].
    
    INFO:moduleinvoker:input_features.v1 运行完成[0.011345s].
    
    [2023-05-24 18:13:35.815227] INFO moduleinvoker: use_datasource.v1 开始运行..
    
    INFO:moduleinvoker:use_datasource.v1 开始运行..
    
    [2023-05-24 18:13:35.823086] INFO moduleinvoker: 命中缓存
    
    INFO:moduleinvoker:命中缓存
    
    [2023-05-24 18:13:35.825880] INFO moduleinvoker: use_datasource.v1 运行完成[0.010658s].
    
    INFO:moduleinvoker:use_datasource.v1 运行完成[0.010658s].
    
    [2023-05-24 18:13:35.837408] INFO moduleinvoker: derived_feature_extractor.v3 开始运行..
    
    INFO:moduleinvoker:derived_feature_extractor.v3 开始运行..
    
    [2023-05-24 18:13:35.846364] INFO moduleinvoker: 命中缓存
    
    INFO:moduleinvoker:命中缓存
    
    [2023-05-24 18:13:35.851578] INFO moduleinvoker: derived_feature_extractor.v3 运行完成[0.014142s].
    
    INFO:moduleinvoker:derived_feature_extractor.v3 运行完成[0.014142s].
    
    [2023-05-24 18:13:35.869063] INFO moduleinvoker: dropnan.v2 开始运行..
    
    INFO:moduleinvoker:dropnan.v2 开始运行..
    
    [2023-05-24 18:13:35.877525] INFO moduleinvoker: 命中缓存
    
    INFO:moduleinvoker:命中缓存
    
    [2023-05-24 18:13:35.881349] INFO moduleinvoker: dropnan.v2 运行完成[0.012295s].
    
    INFO:moduleinvoker:dropnan.v2 运行完成[0.012295s].
    
    [2023-05-24 18:13:35.893332] WARNING moduleinvoker: 此模块版本 M.hftrade.v1 已不再维护。你仍然可以使用,但建议升级到最新版本:请更新到 hftrade 最新版本
    
    WARNING:moduleinvoker:此模块版本 M.hftrade.v1 已不再维护。你仍然可以使用,但建议升级到最新版本:请更新到 hftrade 最新版本
    
    [2023-05-24 18:13:35.917281] INFO moduleinvoker: hfbacktest.v1 开始运行..
    
    INFO:moduleinvoker:hfbacktest.v1 开始运行..
    
    [2023-05-24 18:13:35.924136] INFO hfbacktest: biglearning V1.4.21
    
    INFO:hfbacktest:biglearning V1.4.21
    
    [2023-05-24 18:13:35.928490] INFO hfbacktest: bigtrader v1.10.2 2023-05-18
    
    INFO:hfbacktest:bigtrader v1.10.2 2023-05-18
    
    [2023-05-24 18:13:35.951933] INFO moduleinvoker: cached.v2 开始运行..
    
    INFO:moduleinvoker:cached.v2 开始运行..
    
    [2023-05-24 18:13:35.959159] INFO moduleinvoker: 命中缓存
    
    INFO:moduleinvoker:命中缓存
    
    [2023-05-24 18:13:35.962078] INFO moduleinvoker: cached.v2 运行完成[0.01022s].
    
    INFO:moduleinvoker:cached.v2 运行完成[0.01022s].
    
    [2023-05-24 18:13:36.075972] INFO moduleinvoker: cached.v2 开始运行..
    
    INFO:moduleinvoker:cached.v2 开始运行..
    
    [2023-05-24 18:13:36.084166] INFO moduleinvoker: 命中缓存
    
    INFO:moduleinvoker:命中缓存
    
    [2023-05-24 18:13:36.086814] INFO moduleinvoker: cached.v2 运行完成[0.010881s].
    
    INFO:moduleinvoker:cached.v2 运行完成[0.010881s].
    
    2023-05-24 18:13:36.309464 init history datas... 
    2023-05-24 18:13:36.313229 init history datas done. 
    2023-05-24 18:13:36.318151 run_backtest() capital_base:1000000, frequency:1d, product_type:future, date:2021-05-14 ~ 2021-10-18 
    2023-05-24 18:13:36.321194 run_backtest() running... 
    2023-05-24 18:13:36.331095 initial contracts len=0 
    2023-05-24 18:13:36.334330 backtest inited. 
    2023-05-24 18:13:36.433310 backtest transforming 1d, bars=1... 
    2023-05-24 18:13:36.439869 transform start_trading_day=2021-05-14 00:00:00, simulation period=2021-05-14 ~ 2021-10-18 
    2023-05-24 18:13:36.443326 transform before_start_days=0 
    2023-05-24 18:13:36.446396 transform replay_func=<cyfunction BacktestEngine.transform.<locals>.replay_bars_dt at 0x7f0e9047f380> 
    空仓开空
    2021-07-16 先平空再开多
    2023-05-24 18:13:36.818118 backtest run end! 
    
    /usr/local/python3/lib/python3.8/site-packages/empyrical/stats.py:710: RuntimeWarning: divide by zero encountered in divide
      np.divide(
    /usr/local/python3/lib/python3.8/site-packages/empyrical/stats.py:799: RuntimeWarning: invalid value encountered in divide
      np.divide(average_annual_return, annualized_downside_risk, out=out)
    
    2023-05-24 18:13:37.121934 run_backtest() finished! time cost 0.798s! 
    
    /usr/local/python3/lib/python3.8/site-packages/pandas/core/generic.py:2605: PerformanceWarning: 
    your performance may suffer as PyTables will pickle object types that it cannot
    map directly to c-types [inferred_type->mixed,key->block3_values] [items->Index(['orders', 'transactions', 'positions', 'POS_FAC', 'TRA_FAC', 'LOG'], dtype='object')]
    
      pytables.to_hdf(
    
    [2023-05-24 18:13:38.481640] INFO hfbacktest: backtest done, raw_perf_ds:DataSource(b582eea494694f818d5d27e5b5aaa540T)
    
    INFO:hfbacktest:backtest done, raw_perf_ds:DataSource(b582eea494694f818d5d27e5b5aaa540T)
    /usr/local/python3/lib/python3.8/site-packages/pandas/core/indexing.py:1637: SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame
    
    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
      self._setitem_single_block(indexer, value, name)
    [2023-05-24 18:13:39.455264] INFO: bigcharts.impl.render:render.py:407:render_chart Data is None, skip loading it to chart.
    
    • 收益率40.96%
    • 年化收益率122.31%
    • 基准收益率-4.61%
    • 阿尔法1.35
    • 贝塔0.15
    • 夏普比率3.26
    • 胜率0.0
    • 盈亏比0.0
    • 收益波动率25.61%
    • 最大回撤7.21%
    成交时间 合约代码 合约名称 买/卖 开/平 数量 成交价 交易金额 交易佣金
    Loading... (need help?)
    日期 合约代码 合约名称 持仓均价 收盘价 数量 持仓保证金 浮动盈亏 平仓盈亏
    Loading... (need help?)
    时间 级别 内容
    Loading... (need help?)
    [2023-05-24 18:13:39.931284] INFO moduleinvoker: hfbacktest.v1 运行完成[4.014003s].
    
    INFO:moduleinvoker:hfbacktest.v1 运行完成[4.014003s].
    
    [2023-05-24 18:13:39.935331] INFO moduleinvoker: hftrade.v1 运行完成[4.038216s].
    
    INFO:moduleinvoker:hftrade.v1 运行完成[4.038216s].