复制链接
克隆策略

多头排列回踩均线选股策略

版本 v1.0

目录

  • ### 多头排列回踩均线选股策略的交易规则

  • ### 策略构建步骤

  • ### 策略的实现

正文

一、多头排列回踩均线选股策略的交易规则

  • 买入条件:满足条件 1)5日均线大于10日均线,10日均线大于20日均线,20日均线大于40日均线,40日均线大于120日均线;2)今日最低价小于10日收盘价均线 的股票,次日以开盘价买入;
  • 买入后,如果5日均线小于40日均线,则次日以开盘价卖出。
  • 允许最多同时持有20只股票

二、策略构建步骤

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

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

2、确定买卖条件信号

  • 在输入特征列表中通过表达式引擎定义 buy_condition=where((mean(close_0,5)>mean(close_0,10))&(mean(close_0,10)>mean(close_0,20))&(mean(close_0,20)>mean(close_0,40))&(mean(close_0,40)>mean(close_0,120))&(low_0<mean(close_0,10)),1,0) ,实现买入信号。
  • 在输入特征列表中通过表达式引擎定义 sell_condition=where(mean(close_0,5)<mean(close_0,40),1,0),实现卖出信号。
  • 通过基础特征和衍生特征抽取模块实现买卖条件指标 buy_condition 和 sell_condition 数据的抽取。
  • 通过缺失数据处理模块删去有缺失值的数据。

3、确定买卖原则

  • 已有持仓中满足卖出条件的股票为卖出股票列表,如果设置的卖出规则是早盘买入早盘卖出则执行卖出操作后更新可用现金,如果是早盘买入尾盘卖出则执行卖出操作后不更新可用现金。
  • 满足买入条件且没有持仓的股票为买入股票列表,如果持仓股票数量不足20只,需根据可用现金执行等资金买入操作,此例采用整百股数下单。

4、模拟回测

  • 通过 trade 模块中的初始化函数定义交易手续费和滑点;
  • 通过 trade 模块中的准备函数定义 context.daily_stock_buy 和 context.daily_stock_sell 变量来获取并存放每日符合买卖条件的股票列表;
  • 通过 trade 模块中的主函数(handle函数)查看每日的买卖交易信号,按照买卖原则执行相应的买入/卖出操作。

三、策略的实现

可视化策略实现如下:

    {"description":"实验创建于2017/8/26","graph":{"edges":[{"to_node_id":"-202:features","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"to_node_id":"-209:features","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"to_node_id":"-202:instruments","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"to_node_id":"-53:instruments","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"to_node_id":"-209:input_data","from_node_id":"-202:data"},{"to_node_id":"-1575:input_data","from_node_id":"-209:data"},{"to_node_id":"-53:options_data","from_node_id":"-1575:data"}],"nodes":[{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition=where((mean(close_0,5)>mean(close_0,10))&(mean(close_0,10)>mean(close_0,20))&(mean(close_0,20)>mean(close_0,40))&(mean(close_0,40)>mean(close_0,120))&(low_0<mean(close_0,10)),1,0)\nsell_condition=where(mean(close_0,5)<mean(close_0,40),1,0)","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"output_ports":[{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2013-01-01","type":"Literal","bound_global_parameter":"交易日期"},{"name":"end_date","value":"2013-05-01","type":"Literal","bound_global_parameter":"交易日期"},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"","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":2,"comment":"预测数据,用于回测和模拟","comment_collapsed":false},{"node_id":"-202","module_id":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":"300","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-202"},{"name":"features","node_id":"-202"}],"output_ports":[{"name":"data","node_id":"-202"}],"cacheable":true,"seq_num":7,"comment":"","comment_collapsed":true},{"node_id":"-209","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":"-209"},{"name":"features","node_id":"-209"}],"output_ports":[{"name":"data","node_id":"-209"}],"cacheable":true,"seq_num":8,"comment":"","comment_collapsed":true},{"node_id":"-53","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 # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n context.stock_max_num = 20 # 最多同时持有20只股票\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 回测引擎:每日数据处理函数,每天执行一次\n today = data.current_dt.strftime('%Y-%m-%d') # 日期\n # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表和对应的最新市值\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n hold_num=len(stock_hold_now)\n \n # 记录用于买入股票的可用现金,因为是早盘卖股票,需要记录卖出的股票市值并在买入下单前更新可用现金;\n # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用\n cash_for_buy = context.portfolio.cash\n \n # 获取当日符合买入/卖出条件的股票列表\n try:\n buy_stock = context.daily_stock_buy[today] # 当日符合买入条件的股票\n except:\n buy_stock=[]\n try:\n sell_stock = context.daily_stock_sell[today] # 当日符合卖出条件的股票\n except:\n sell_stock = []\n\n # 需要卖出的股票:已有持仓中符合卖出条件的股票\n stock_to_sell = [i for i in stock_hold_now if i in sell_stock]\n # 需要买入的股票:没有持仓且符合买入条件的股票\n stock_to_buy = [i for i in buy_stock if i not in stock_hold_now]\n # 卖出\n for instrument in stock_to_sell:\n # 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态\n # 如果返回真值,则可以正常下单,否则会出错\n # 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式\n if data.can_trade(context.symbol(instrument)):\n # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,即卖出全部股票,可参考回测文档\n context.order_target_percent(context.symbol(instrument), 0)\n # 因为设置的是早盘卖出早盘买入,需要根据卖出的股票更新可用现金;如果设置尾盘卖出早盘买入,则不需更新可用现金(可以删除下面的语句)\n cash_for_buy += stock_hold_now[instrument]\n hold_num-=1\n\n # 当日还允许买入建仓的股票数目\n stock_can_buy_num = context.stock_max_num - hold_num\n stock_to_buy_num = min(stock_can_buy_num,len(stock_to_buy))\n \n # 如果当天没有买入的股票,就返回\n if stock_to_buy_num == 0:\n return\n \n # 记录已经买入的股票数量\n buy_num = 0\n for instrument in stock_to_buy:\n # 使用当日可用现金等资金比例下单买入\n cash = cash_for_buy / stock_to_buy_num\n if data.can_trade(context.symbol(instrument)) and buy_num<stock_to_buy_num:\n # 整百下单\n current_price = data.current(context.symbol(instrument), 'price')\n amount = math.floor(cash / current_price / 100) * 100\n context.order(context.symbol(instrument), amount)\n buy_num += 1\n\n","type":"Literal","bound_global_parameter":null},{"name":"prepare","value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n df = context.options['data'].read_df()\n\n # 函数:求满足开仓条件的股票列表\n def open_pos_con(df):\n return list(df[df['buy_condition']>0].instrument)\n\n # 函数:求满足平仓条件的股票列表\n def close_pos_con(df):\n return list(df[df['sell_condition']>0].instrument)\n\n # 每日买入股票的数据框\n context.daily_stock_buy= df.groupby('date').apply(open_pos_con)\n # 每日卖出股票的数据框\n context.daily_stock_sell= df.groupby('date').apply(close_pos_con)","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"","type":"Literal","bound_global_parameter":null},{"name":"volume_limit","value":0.025,"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":"000300.HIX","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-53"},{"name":"options_data","node_id":"-53"},{"name":"history_ds","node_id":"-53"},{"name":"benchmark_ds","node_id":"-53"},{"name":"trading_calendar","node_id":"-53"}],"output_ports":[{"name":"raw_perf","node_id":"-53"}],"cacheable":false,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-1575","module_id":"BigQuantSpace.dropnan.dropnan-v2","parameters":[],"input_ports":[{"name":"input_data","node_id":"-1575"},{"name":"features","node_id":"-1575"}],"output_ports":[{"name":"data","node_id":"-1575"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='1285,99,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='800,101,200,200'/><node_position Node='-202' Position='1078,232,200,200'/><node_position Node='-209' Position='1076,328,200,200'/><node_position Node='-53' Position='976,539,200,200'/><node_position Node='-1575' Position='1077,425,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [1]:
    # 本代码由可视化策略环境自动生成 2021年12月6日 22:14
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m3_initialize_bigquant_run(context):
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
        context.stock_max_num = 20 # 最多同时持有20只股票
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m3_handle_data_bigquant_run(context, data):
        # 回测引擎:每日数据处理函数,每天执行一次
        today = data.current_dt.strftime('%Y-%m-%d') # 日期
        # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表和对应的最新市值
        stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
        hold_num=len(stock_hold_now)
        
        # 记录用于买入股票的可用现金,因为是早盘卖股票,需要记录卖出的股票市值并在买入下单前更新可用现金;
        # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用
        cash_for_buy = context.portfolio.cash
        
        # 获取当日符合买入/卖出条件的股票列表
        try:
            buy_stock = context.daily_stock_buy[today]  # 当日符合买入条件的股票
        except:
            buy_stock=[]
        try:
            sell_stock = context.daily_stock_sell[today]  # 当日符合卖出条件的股票
        except:
            sell_stock = []
    
        # 需要卖出的股票:已有持仓中符合卖出条件的股票
        stock_to_sell = [i for i in stock_hold_now if i in sell_stock]
        # 需要买入的股票:没有持仓且符合买入条件的股票
        stock_to_buy = [i for i in buy_stock if i not in stock_hold_now]
        # 卖出
        for instrument in stock_to_sell:
            # 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态
            # 如果返回真值,则可以正常下单,否则会出错
            # 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式
            if data.can_trade(context.symbol(instrument)):
                # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,即卖出全部股票,可参考回测文档
                context.order_target_percent(context.symbol(instrument), 0)
                # 因为设置的是早盘卖出早盘买入,需要根据卖出的股票更新可用现金;如果设置尾盘卖出早盘买入,则不需更新可用现金(可以删除下面的语句)
                cash_for_buy += stock_hold_now[instrument]
                hold_num-=1
    
        # 当日还允许买入建仓的股票数目
        stock_can_buy_num = context.stock_max_num - hold_num
        stock_to_buy_num = min(stock_can_buy_num,len(stock_to_buy))
        
        # 如果当天没有买入的股票,就返回
        if stock_to_buy_num == 0:
            return
        
        # 记录已经买入的股票数量
        buy_num = 0
        for instrument in stock_to_buy:
            # 使用当日可用现金等资金比例下单买入
            cash = cash_for_buy / stock_to_buy_num
            if data.can_trade(context.symbol(instrument)) and buy_num<stock_to_buy_num:
                # 整百下单
                current_price = data.current(context.symbol(instrument), 'price')
                amount = math.floor(cash / current_price / 100) * 100
                context.order(context.symbol(instrument), amount)
                buy_num += 1
    
    
    # 回测引擎:准备数据,只执行一次
    def m3_prepare_bigquant_run(context):
        # 加载预测数据
        df = context.options['data'].read_df()
    
        # 函数:求满足开仓条件的股票列表
        def open_pos_con(df):
            return list(df[df['buy_condition']>0].instrument)
    
        # 函数:求满足平仓条件的股票列表
        def close_pos_con(df):
            return list(df[df['sell_condition']>0].instrument)
    
        # 每日买入股票的数据框
        context.daily_stock_buy= df.groupby('date').apply(open_pos_con)
        # 每日卖出股票的数据框
        context.daily_stock_sell= df.groupby('date').apply(close_pos_con)
    
    m1 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    buy_condition=where((mean(close_0,5)>mean(close_0,10))&(mean(close_0,10)>mean(close_0,20))&(mean(close_0,20)>mean(close_0,40))&(mean(close_0,40)>mean(close_0,120))&(low_0<mean(close_0,10)),1,0)
    sell_condition=where(mean(close_0,5)<mean(close_0,40),1,0)"""
    )
    
    m2 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2013-01-01'),
        end_date=T.live_run_param('trading_date', '2013-05-01'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m7 = M.general_feature_extractor.v7(
        instruments=m2.data,
        features=m1.data,
        start_date='',
        end_date='',
        before_start_days=300
    )
    
    m8 = M.derived_feature_extractor.v3(
        input_data=m7.data,
        features=m1.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False
    )
    
    m4 = M.dropnan.v2(
        input_data=m8.data
    )
    
    m3 = M.trade.v4(
        instruments=m2.data,
        options_data=m4.data,
        start_date='',
        end_date='',
        initialize=m3_initialize_bigquant_run,
        handle_data=m3_handle_data_bigquant_run,
        prepare=m3_prepare_bigquant_run,
        volume_limit=0.025,
        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='000300.HIX'
    )
    
    • 收益率5.58%
    • 年化收益率20.32%
    • 基准收益率-3.0%
    • 阿尔法0.27
    • 贝塔0.84
    • 夏普比率0.76
    • 胜率0.34
    • 盈亏比1.98
    • 收益波动率24.29%
    • 信息比率0.13
    • 最大回撤10.24%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-4dc9c1b127ad49b28f39c0be91a496e2"}/bigcharts-data-end