复制链接
克隆策略

双均线模板策略

版本 v1.0

目录

策略交易规则

策略构建步骤

正文

一、双均线模板策略的交易规则

金叉死叉策略其实就是双均线策略。策略思想是:当短期均线上穿长期均线时,形成金叉,此时买入股票。当短期均线下穿长期均线时,形成死叉,此时卖出股票。研究表明,双均线系统虽然简单,但只要严格执行,也能长期盈利。

二、策略构建步骤

1、确定股票池和回测时间

通过证券代码列表输入要回测的两只股票,以及回测的起止日期。

2、确定买卖原则

当短期均线上穿长期均线时,形成金叉,此时买入股票。当短期均线下穿长期均线时,形成死叉,此时卖出股票。

3、模拟回测

通过 trade 模块中的初始化函数定义交易手续费。 通过 trade 模块中的主函数(handle函数)形成金叉买入股票;形成死叉卖出股票。并打印交易日志。

4、标的

广发纳指100ETF:159941.ZOF

华夏新汽车ETF:515030.HOF

5、仓位

等权重,单个基金50%

    {"description":"实验创建于2021/11/25","graph":{"edges":[{"to_node_id":"-16:instruments","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"}],"nodes":[{"node_id":"-16","module_id":"BigQuantSpace.trade.trade-v4","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"initialize","value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n \n for sid in context.instruments:\n # 标的为字符串格式\n sid = context.symbol(sid)# 标的为字符串格\n price = data.current(sid, 'price') # 最新价格\n short_mavg = data.history(sid, 'price', 3, '1d').mean() # 短期均线\n long_mavg = data.history(sid, 'price', 30, '1d').mean() # 长期均线\n cur_position = context.portfolio.positions[sid].amount # 持仓数量 \n weight = 1 / len(context.instruments) # 等权重\n\n #交易逻辑\n # 如果短期均线大于长期均线形成金叉,并且没有持仓,并且该股票可以交易\n if short_mavg > long_mavg and cur_position == 0 and data.can_trade(sid): \n context.order_target_percent(sid, weight) # 买入\n print('{}全仓买入{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))\n # 如果短期均线小于长期均线形成死叉,并且有持仓,并且该股票可以交易\n elif short_mavg < long_mavg and cur_position > 0 and data.can_trade(sid): \n context.order_target_percent(sid, 0) # 全部卖出\n print('{}卖出{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))\n \n \n","type":"Literal","bound_global_parameter":null},{"name":"prepare","value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\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":"volume_limit","value":"0","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_buy","value":"open","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_sell","value":"open","type":"Literal","bound_global_parameter":null},{"name":"capital_base","value":1000000,"type":"Literal","bound_global_parameter":null},{"name":"auto_cancel_non_tradable_orders","value":"True","type":"Literal","bound_global_parameter":null},{"name":"data_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":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"backtest_only","value":"False","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-16"},{"name":"options_data","node_id":"-16"},{"name":"history_ds","node_id":"-16"},{"name":"benchmark_ds","node_id":"-16"},{"name":"trading_calendar","node_id":"-16"}],"output_ports":[{"name":"raw_perf","node_id":"-16"}],"cacheable":false,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2017-01-20","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-09-01","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_FUND","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"159941.ZOF\n515030.HOF","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":"0","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"output_ports":[{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"cacheable":true,"seq_num":7,"comment":"预测数据,用于回测和模拟","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-16' Position='320,152,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='329,9,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [2]:
    # 本代码由可视化策略环境自动生成 2023年5月24日 18:17
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
     
    # 显式导入 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 zipline.finance.commission import PerOrder
    
    # 回测引擎:初始化函数,只执行一次
    def m2_initialize_bigquant_run(context):
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    # 回测引擎:每日数据处理函数,每天执行一次
    def m2_handle_data_bigquant_run(context, data):
        # 按日期过滤得到今日的预测数据
        
        for sid in context.instruments:
            # 标的为字符串格式
            sid = context.symbol(sid)# 标的为字符串格
            price = data.current(sid, 'price') # 最新价格
            short_mavg = data.history(sid, 'price', 3, '1d').mean() # 短期均线
            long_mavg = data.history(sid, 'price', 30, '1d').mean() # 长期均线
            cur_position =  context.portfolio.positions[sid].amount # 持仓数量 
            weight = 1 / len(context.instruments) # 等权重
    
            #交易逻辑
            # 如果短期均线大于长期均线形成金叉,并且没有持仓,并且该股票可以交易
            if short_mavg > long_mavg and cur_position == 0 and data.can_trade(sid):  
                context.order_target_percent(sid, weight) # 买入
                print('{}全仓买入{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))
            # 如果短期均线小于长期均线形成死叉,并且有持仓,并且该股票可以交易
            elif short_mavg < long_mavg and cur_position > 0 and data.can_trade(sid):  
                context.order_target_percent(sid, 0) # 全部卖出
                print('{}卖出{}股票'.format(data.current_dt.strftime('%Y-%m-%d'),sid.symbol))
            
            
    
    # 回测引擎:准备数据,只执行一次
    def m2_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m2_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m7 = M.instruments.v2(
        start_date='2017-01-20',
        end_date='2021-09-01',
        market='CN_FUND',
        instrument_list="""159941.ZOF
    515030.HOF""",
        max_count=0
    )
    
    m2 = M.trade.v4(
        instruments=m7.data,
        start_date='',
        end_date='',
        initialize=m2_initialize_bigquant_run,
        handle_data=m2_handle_data_bigquant_run,
        prepare=m2_prepare_bigquant_run,
        before_trading_start=m2_before_trading_start_bigquant_run,
        volume_limit=0,
        order_price_field_buy='open',
        order_price_field_sell='open',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='真实价格',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    [2023-05-24 18:18:14.491683] INFO moduleinvoker: instruments.v2 开始运行..
    [2023-05-24 18:18:14.501165] INFO moduleinvoker: 命中缓存
    [2023-05-24 18:18:14.502744] INFO moduleinvoker: instruments.v2 运行完成[0.011088s].
    [2023-05-24 18:18:14.573574] INFO moduleinvoker: backtest.v8 开始运行..
    [2023-05-24 18:18:14.578241] INFO backtest: biglearning backtest:V8.6.3
    [2023-05-24 18:18:14.579832] INFO backtest: product_type:stock by specified
    [2023-05-24 18:18:14.666665] INFO moduleinvoker: cached.v2 开始运行..
    [2023-05-24 18:18:14.672578] INFO moduleinvoker: 命中缓存
    [2023-05-24 18:18:14.674287] INFO moduleinvoker: cached.v2 运行完成[0.007669s].
    [2023-05-24 18:18:14.766790] INFO backtest: algo history_data=DataSource(0dc063ee92bd496f810d4effa24181afT)
    [2023-05-24 18:18:14.768661] INFO algo: TradingAlgorithm V1.8.9
    [2023-05-24 18:18:15.472845] INFO algo: trading transform...
    2017-01-20全仓买入159941.ZOF股票
    
    /var/app/enabled/bigline/zipline/data/us_equity_pricing.py:990: FutureWarning: Indexing a timezone-naive DatetimeIndex with a timezone-aware datetime is deprecated and will raise KeyError in a future version.  Use a timezone-naive object instead.
      return df.loc[dt, field]
    /usr/local/python3/lib/python3.8/site-packages/pandas/core/indexing.py:1124: FutureWarning: Indexing a timezone-naive DatetimeIndex with a timezone-aware datetime is deprecated and will raise KeyError in a future version.  Use a timezone-naive object instead.
      return self._get_label(key, axis=axis)
    
    2017-01-23卖出159941.ZOF股票
    2017-01-26全仓买入159941.ZOF股票
    2017-03-23卖出159941.ZOF股票
    2017-04-26全仓买入159941.ZOF股票
    2017-05-19卖出159941.ZOF股票
    2017-05-25全仓买入159941.ZOF股票
    2017-06-13卖出159941.ZOF股票
    2017-07-17全仓买入159941.ZOF股票
    2017-08-14卖出159941.ZOF股票
    2017-08-17全仓买入159941.ZOF股票
    2017-08-18卖出159941.ZOF股票
    2017-09-19全仓买入159941.ZOF股票
    2017-09-26卖出159941.ZOF股票
    2017-09-29全仓买入159941.ZOF股票
    2017-12-06卖出159941.ZOF股票
    2017-12-12全仓买入159941.ZOF股票
    2017-12-29卖出159941.ZOF股票
    2018-01-02全仓买入159941.ZOF股票
    2018-02-05卖出159941.ZOF股票
    2018-02-27全仓买入159941.ZOF股票
    2018-03-26卖出159941.ZOF股票
    2018-05-04全仓买入159941.ZOF股票
    2018-09-10卖出159941.ZOF股票
    2018-09-12全仓买入159941.ZOF股票
    2018-09-20卖出159941.ZOF股票
    2018-09-25全仓买入159941.ZOF股票
    2018-10-09卖出159941.ZOF股票
    2018-12-03全仓买入159941.ZOF股票
    2018-12-06卖出159941.ZOF股票
    2019-01-16全仓买入159941.ZOF股票
    2019-03-11卖出159941.ZOF股票
    2019-03-12全仓买入159941.ZOF股票
    2019-05-14卖出159941.ZOF股票
    2019-06-12全仓买入159941.ZOF股票
    2019-08-06卖出159941.ZOF股票
    2019-08-12全仓买入159941.ZOF股票
    2019-08-15卖出159941.ZOF股票
    2019-08-21全仓买入159941.ZOF股票
    2019-08-27卖出159941.ZOF股票
    2019-09-02全仓买入159941.ZOF股票
    2019-09-27卖出159941.ZOF股票
    2019-10-15全仓买入159941.ZOF股票
    2020-02-26卖出159941.ZOF股票
    2020-03-09全仓买入515030.HOF股票
    2020-03-11卖出515030.HOF股票
    2020-04-09全仓买入159941.ZOF股票
    2020-04-16全仓买入515030.HOF股票
    2020-04-28卖出515030.HOF股票
    2020-04-30全仓买入515030.HOF股票
    2020-05-25卖出515030.HOF股票
    2020-05-28全仓买入515030.HOF股票
    2020-07-28卖出515030.HOF股票
    2020-07-30全仓买入515030.HOF股票
    2020-08-13卖出515030.HOF股票
    2020-08-14全仓买入515030.HOF股票
    2020-08-20卖出515030.HOF股票
    2020-09-01全仓买入515030.HOF股票
    2020-09-07卖出515030.HOF股票
    2020-09-17全仓买入515030.HOF股票
    2020-09-21卖出159941.ZOF股票
    2020-09-25卖出515030.HOF股票
    2020-09-30全仓买入515030.HOF股票
    2020-10-13全仓买入159941.ZOF股票
    2020-10-16卖出159941.ZOF股票
    2020-11-09全仓买入159941.ZOF股票
    2020-11-10卖出159941.ZOF股票
    2020-12-01全仓买入159941.ZOF股票
    2021-01-07卖出159941.ZOF股票
    2021-01-08全仓买入159941.ZOF股票
    2021-02-01卖出515030.HOF股票
    2021-02-03全仓买入515030.HOF股票
    2021-02-05卖出515030.HOF股票
    2021-02-18全仓买入515030.HOF股票
    2021-02-19卖出515030.HOF股票
    2021-02-25卖出159941.ZOF股票
    2021-03-18全仓买入159941.ZOF股票
    2021-03-19卖出159941.ZOF股票
    2021-04-01全仓买入159941.ZOF股票
    2021-04-07全仓买入515030.HOF股票
    2021-04-12卖出515030.HOF股票
    2021-04-15全仓买入515030.HOF股票
    2021-05-10卖出159941.ZOF股票
    2021-06-09全仓买入159941.ZOF股票
    2021-08-17卖出515030.HOF股票
    2021-08-23全仓买入515030.HOF股票
    [2023-05-24 18:18:28.631585] INFO Performance: Simulated 1124 trading days out of 1124.
    [2023-05-24 18:18:28.633737] INFO Performance: first open: 2017-01-20 09:30:00+00:00
    [2023-05-24 18:18:28.635705] INFO Performance: last close: 2021-09-01 15:00:00+00:00
    
    /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->block5_values] [items->Index(['positions', 'transactions', 'orders', 'LOG', 'TRA_FAC', 'POS_FAC',
           'period_label'],
          dtype='object')]
    
      pytables.to_hdf(
    /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:18:30.135151] INFO: bigcharts.impl.render:render.py:407:render_chart Data is None, skip loading it to chart.
    
    • 收益率115.55%
    • 年化收益率18.79%
    • 基准收益率46.26%
    • 阿尔法0.14
    • 贝塔0.3
    • 夏普比率1.02
    • 胜率0.45
    • 盈亏比4.96
    • 收益波动率15.13%
    • 信息比率0.03
    • 最大回撤13.97%
    日期 时间 股票代码 股票名称 买/卖 数量 成交价 总成本 交易佣金
    Loading... (need help?)
    日期 股票代码 股票名称 持仓均价 收盘价 股数 持仓价值 收益
    Loading... (need help?)
    时间 级别 内容
    Loading... (need help?)
    [2023-05-24 18:18:30.742148] INFO moduleinvoker: backtest.v8 运行完成[16.168566s].
    
    INFO:moduleinvoker:backtest.v8 运行完成[16.168566s].
    
    [2023-05-24 18:18:30.748134] INFO moduleinvoker: trade.v4 运行完成[16.237518s].
    
    INFO:moduleinvoker:trade.v4 运行完成[16.237518s].
    
    In [ ]: