克隆策略

价值投资选股策略

版本 v1.0

目录

策略交易规则

策略构建步骤

一、交易规则

开始买入市盈率小于20倍、市净率小于2倍且按照净资产收益率(TTM)排序的前30只股票,持有22个交易日再调仓,等权重买入(没有单票仓位上限控制、无止盈止损)

二、策略构建步骤

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

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

2、确定买卖原则

买入市盈率小于20倍、市净率小于2倍且按照净资产收益率(TTM)排序的前30只股票。

3、模拟回测

通过 trade 模块中的初始化函数定义交易手续费。

通过 trade 模块中的主函数(handle函数)实现交易规则,并打印交易日志。

    {"description":"实验创建于2019/4/24","graph":{"edges":[{"to_node_id":"-64:input_ds","from_node_id":"-6:data"},{"to_node_id":"-6:instruments","from_node_id":"-21:data"},{"to_node_id":"-43:instruments","from_node_id":"-21:data"},{"to_node_id":"-6:features","from_node_id":"-35:data"},{"to_node_id":"-30:input_data","from_node_id":"-64:sorted_data"},{"to_node_id":"-43:options_data","from_node_id":"-30:data"}],"nodes":[{"node_id":"-6","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":90,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-6"},{"name":"features","node_id":"-6"}],"output_ports":[{"name":"data","node_id":"-6"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-21","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2019-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-11-26","type":"Literal","bound_global_parameter":null},{"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":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-21"}],"output_ports":[{"name":"data","node_id":"-21"}],"cacheable":true,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-35","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"pb_lf_0\npe_ttm_0\namount_0\nfs_roe_ttm_0","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-35"}],"output_ports":[{"name":"data","node_id":"-35"}],"cacheable":true,"seq_num":5,"comment":"","comment_collapsed":true},{"node_id":"-43","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 # 加载股票指标数据,数据继承自m4模块\n context.indicator_data = context.options['data'].read_df().set_index('date')\n print('indicator_data:', context.indicator_data.head()) \n # 设置交易费用,买入是万三,卖出是千分之1.3,如果不足5元按5元算\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 设置股票数量\n context.stock_num = 30\n \n # 调仓天数,22个交易日大概就是一个月。可以理解为一个月换仓一次\n context.rebalance_days = 22\n \n # 如果策略运行中,需要将数据进行保存,可以借用extension这个对象,类型为dict\n # 比如当前运行的k线的索引,比如个股持仓天数、买入均价\n if 'index' not in context.extension:\n context.extension['index'] = 0\n \n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n # 按每个K线递增\n context.extension['index'] += 1\n \n # 每隔22个交易日进行换仓\n if context.extension['index'] % context.rebalance_days != 0:\n return \n \n # 日期\n date = data.current_dt.strftime('%Y-%m-%d')\n \n # 买入股票列表\n stock_to_buy = context.indicator_data.loc[date]['instrument'][:context.stock_num]\n \n # 目前持仓列表 \n stock_hold_now = [equity.symbol for equity in context.portfolio.positions]\n # 继续持有股票列表\n no_need_to_sell = [i for i in stock_hold_now if i in stock_to_buy]\n # 卖出股票列表 \n stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]\n # 执行卖出\n for stock in stock_to_sell:\n if data.can_trade(context.symbol(stock)):\n context.order_target_percent(context.symbol(stock), 0)\n \n # 如果当天没有买入就返回\n if len(stock_to_buy) == 0:\n return\n \n # 等权重\n weight = 1 / len(stock_to_buy)\n # 执行买入\n for cp in stock_to_buy:\n if data.can_trade(context.symbol(cp)):\n context.order_target_percent(context.symbol(cp), weight)","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.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":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-43"},{"name":"options_data","node_id":"-43"},{"name":"history_ds","node_id":"-43"},{"name":"benchmark_ds","node_id":"-43"},{"name":"trading_calendar","node_id":"-43"}],"output_ports":[{"name":"raw_perf","node_id":"-43"}],"cacheable":false,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"-64","module_id":"BigQuantSpace.sort.sort-v4","parameters":[{"name":"sort_by","value":"fs_roe_ttm_0","type":"Literal","bound_global_parameter":null},{"name":"group_by","value":"date","type":"Literal","bound_global_parameter":null},{"name":"keep_columns","value":"--","type":"Literal","bound_global_parameter":null},{"name":"ascending","value":"True","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_ds","node_id":"-64"},{"name":"sort_by_ds","node_id":"-64"}],"output_ports":[{"name":"sorted_data","node_id":"-64"}],"cacheable":true,"seq_num":6,"comment":"按多个因子进行排序","comment_collapsed":true},{"node_id":"-30","module_id":"BigQuantSpace.filter.filter-v3","parameters":[{"name":"expr","value":"pb_lf_0 < 2 & pe_ttm_0 < 20 & amount_0 > 0 & pb_lf_0 > 0 & pe_ttm_0 > 0","type":"Literal","bound_global_parameter":null},{"name":"output_left_data","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-30"}],"output_ports":[{"name":"data","node_id":"-30"},{"name":"left_data","node_id":"-30"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-6' Position='259,164,200,200'/><node_position Node='-21' Position='16,66,200,200'/><node_position Node='-35' Position='469,69,200,200'/><node_position Node='-43' Position='160,385,200,200'/><node_position Node='-64' Position='235,230,200,200'/><node_position Node='-30' Position='237,302,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [1]:
    # 本代码由可视化策略环境自动生成 2021年12月4日 11:46
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m2_initialize_bigquant_run(context):
        
        # 加载股票指标数据,数据继承自m4模块
        context.indicator_data = context.options['data'].read_df().set_index('date')
        print('indicator_data:', context.indicator_data.head()) 
        # 设置交易费用,买入是万三,卖出是千分之1.3,如果不足5元按5元算
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
         # 设置股票数量
        context.stock_num = 30
        
        # 调仓天数,22个交易日大概就是一个月。可以理解为一个月换仓一次
        context.rebalance_days = 22
        
        # 如果策略运行中,需要将数据进行保存,可以借用extension这个对象,类型为dict
        # 比如当前运行的k线的索引,比如个股持仓天数、买入均价
        if 'index' not in context.extension:
            context.extension['index'] = 0
            
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m2_handle_data_bigquant_run(context, data):
        
        # 按每个K线递增
        context.extension['index']  += 1
        
        # 每隔22个交易日进行换仓
        if context.extension['index'] % context.rebalance_days != 0:
            return 
            
        # 日期
        date = data.current_dt.strftime('%Y-%m-%d')
        
        # 买入股票列表
        stock_to_buy = context.indicator_data.loc[date]['instrument'][:context.stock_num]
        
        # 目前持仓列表    
        stock_hold_now = [equity.symbol for equity in context.portfolio.positions]
        # 继续持有股票列表
        no_need_to_sell = [i for i in stock_hold_now  if i in stock_to_buy]
        # 卖出股票列表 
        stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]
        # 执行卖出
        for stock in stock_to_sell:
            if data.can_trade(context.symbol(stock)):
                context.order_target_percent(context.symbol(stock), 0)
                
        # 如果当天没有买入就返回
        if len(stock_to_buy) == 0:
            return
        
        # 等权重
        weight = 1 / len(stock_to_buy)
        # 执行买入
        for  cp in stock_to_buy:
            if data.can_trade(context.symbol(cp)):
                context.order_target_percent(context.symbol(cp), weight)
    # 回测引擎:准备数据,只执行一次
    def m2_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m2_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m3 = M.instruments.v2(
        start_date='2019-01-01',
        end_date='2021-11-26',
        market='CN_STOCK_A',
        instrument_list=''
    )
    
    m5 = M.input_features.v1(
        features="""pb_lf_0
    pe_ttm_0
    amount_0
    fs_roe_ttm_0"""
    )
    
    m1 = M.general_feature_extractor.v7(
        instruments=m3.data,
        features=m5.data,
        start_date='',
        end_date='',
        before_start_days=90
    )
    
    m6 = M.sort.v4(
        input_ds=m1.data,
        sort_by='fs_roe_ttm_0',
        group_by='date',
        keep_columns='--',
        ascending=True
    )
    
    m4 = M.filter.v3(
        input_data=m6.sorted_data,
        expr='pb_lf_0 < 2 & pe_ttm_0 < 20 & amount_0 > 0 & pb_lf_0 > 0 & pe_ttm_0 > 0',
        output_left_data=False
    )
    
    m2 = M.trade.v4(
        instruments=m3.data,
        options_data=m4.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.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=''
    )
    
    indicator_data:               amount_0  fs_roe_ttm_0  instrument   pb_lf_0   pe_ttm_0
    date                                                                 
    2018-10-08  81723693.0        3.8235  601898.SHA  0.764548  19.996084
    2018-10-08  25674450.0        3.9840  000698.SZA  0.762213  19.132044
    2018-10-08  25748423.0        4.1403  300158.SZA  0.752570  18.176720
    2018-10-08  19215739.0        4.2376  600894.SHA  0.721665  17.030197
    2018-10-08  44271809.0        4.3718  600811.SHA  0.710191  16.182467
    
    • 收益率60.92%
    • 年化收益率18.54%
    • 基准收益率61.43%
    • 阿尔法0.06
    • 贝塔0.66
    • 夏普比率0.78
    • 胜率0.48
    • 盈亏比1.68
    • 收益波动率20.81%
    • 信息比率-0.0
    • 最大回撤26.13%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-bc35305e6b61466cae5a0c7423ca5621"}/bigcharts-data-end