随机森林策略初步尝试

策略分享
标签: #<Tag:0x00007fcf71e00d60>

(zengliang1995) #1

本文主要有以下几点改进:
1.特征:加入新特征,beta,macd,willr等。
2.模型:使用随机森林,其中树的个数限制为15,树的最大深度为25,防止过拟合。使用回归算法而不是分类算法。
3.标注:使用(卖出价格-买入价格)/ 买入价格作为标签。
4.回测:股票资金分配,使得排名靠前的股票能分配到更多资金投入,加入止损策略(跌破3%止损)。

T.norm([1 / math.exp(i) for i in range(0, stock_count)]) #[0.3391,0.2139,0.1695,0.1460,0.1312]
T.norm([1 / math.log(i+2) for i in range(0, stock_count)]) #[0.6364,0.2341,0.0861,0.0316,0.0116]
克隆策略

    {"Description":"实验创建于2018/1/3","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-324:instruments","SourceOutputPortId":"-316:data"},{"DestinationInputPortId":"-952:instruments","SourceOutputPortId":"-316:data"},{"DestinationInputPortId":"-1103:data1","SourceOutputPortId":"-324:data"},{"DestinationInputPortId":"-952:features","SourceOutputPortId":"-822:data"},{"DestinationInputPortId":"-959:features","SourceOutputPortId":"-822:data"},{"DestinationInputPortId":"-1402:features","SourceOutputPortId":"-822:data"},{"DestinationInputPortId":"-1575:features","SourceOutputPortId":"-822:data"},{"DestinationInputPortId":"-1582:features","SourceOutputPortId":"-822:data"},{"DestinationInputPortId":"-959:input_data","SourceOutputPortId":"-952:data"},{"DestinationInputPortId":"-1103:data2","SourceOutputPortId":"-959:data"},{"DestinationInputPortId":"-1252:input_data","SourceOutputPortId":"-1103:data"},{"DestinationInputPortId":"-1402:training_ds","SourceOutputPortId":"-1252:data"},{"DestinationInputPortId":"-1766:model","SourceOutputPortId":"-1402:model"},{"DestinationInputPortId":"-1575:instruments","SourceOutputPortId":"-1566:data"},{"DestinationInputPortId":"-2137:instruments","SourceOutputPortId":"-1566:data"},{"DestinationInputPortId":"-1582:input_data","SourceOutputPortId":"-1575:data"},{"DestinationInputPortId":"-1762:input_data","SourceOutputPortId":"-1582:data"},{"DestinationInputPortId":"-1766:data","SourceOutputPortId":"-1762:data"},{"DestinationInputPortId":"-2137:options_data","SourceOutputPortId":"-1766:predictions"}],"ModuleNodes":[{"Id":"-316","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2012-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-316"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-316","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-324","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格) - 1\nshift(close, -5) / shift(open, -1) - 1 \n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用10个分类\nall_wbins(label, 10)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na_label","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"cast_label_int","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-324"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-324","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-822","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nreturn_5\nclose_0 / close_1\nreturn_10\nreturn_20\navg_amount_0/avg_amount_5\navg_amount_5/avg_amount_20\npe_ttm_0\nbeta_csi800_5_0\nswing_volatility_5_0\nta_macd_macd_12_26_9_0\nta_willr_14_0\nta_mom_10_0\nta_sar_0\nrank_avg_amount_0/rank_avg_amount_5\nrank_avg_amount_5/rank_avg_amount_10\nrank_return_0\nrank_return_5\nrank_return_10\nrank_return_0/rank_return_5\nrank_return_5/rank_return_10","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-822"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-822","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-952","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v6","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-952"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-952"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-952","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-959","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v2","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-959"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-959"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-959","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1103","ModuleId":"BigQuantSpace.join.join-v3","ModuleParameters":[{"Name":"on","Value":"date,instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"how","Value":"inner","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"sort","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data1","NodeId":"-1103"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-1103"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1103","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1252","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-1252"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1252","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1402","ModuleId":"BigQuantSpace.random_forest_train.random_forest_train-v2","ModuleParameters":[{"Name":"n_estimators","Value":"15","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_features","Value":"auto","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_depth","Value":"25","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"min_samples_leaf","Value":200,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"n_jobs","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"algo","Value":"regressor","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-1402"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1402"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-1402"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-1402","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1566","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-1566"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1566","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1575","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v6","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1575"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1575"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1575","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1582","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v2","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-1582"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1582"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1582","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":11,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1762","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-1762"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1762","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1766","ModuleId":"BigQuantSpace.random_forest_predict.random_forest_predict-v2","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"sort","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"model","NodeId":"-1766"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"-1766"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"-1766","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2137","ModuleId":"BigQuantSpace.trade.trade-v3","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n\n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.hold_days # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.hold_days\n cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)\n cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n \n '''\n date = data.current_dt.strftime('%Y-%m-%d') \n #------------------------------------------止损模块START--------------------------------------------\n current_stoploss_stock = [] \n if len(positions) > 0:\n for i in positions.keys():\n stock_cost = positions[i] \n stock_market_price = data.current(context.symbol(i), 'price') \n # 亏3%就止损\n if (stock_market_price - stock_cost) / stock_cost <= -0.03: \n context.order_target_percent(context.symbol(i),0) \n current_stoploss_stock.append(i)\n #print('日期:',date,'股票:',i,'出现止损状况')\n #-------------------------------------------止损模块END---------------------------------------------\n '''\n \n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票\n buy_cash_weights = context.stock_weights\n buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])\n max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument\n for i, instrument in enumerate(buy_instruments):\n cash = cash_for_buy * buy_cash_weights[i]\n if cash > max_cash_per_instrument - positions.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n cash = max_cash_per_instrument - positions.get(instrument, 0)\n if cash > 0:\n context.order_value(context.symbol(instrument), cash)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n #context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = T.norm([1 / math.exp(i) for i in range(0, stock_count)])\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.2\n context.hold_days = 5\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"后复权","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"amount_integer","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-2137"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-2137"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-2137","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='-316' Position='346,133,200,200'/><NodePosition Node='-324' Position='159,264,200,200'/><NodePosition Node='-822' Position='815,26,200,200'/><NodePosition Node='-952' Position='503,272,200,200'/><NodePosition Node='-959' Position='516,387,200,200'/><NodePosition Node='-1103' Position='264,520,200,200'/><NodePosition Node='-1252' Position='358,676,200,200'/><NodePosition Node='-1402' Position='634,764,200,200'/><NodePosition Node='-1566' Position='1195,149,200,200'/><NodePosition Node='-1575' Position='1174,295,200,200'/><NodePosition Node='-1582' Position='1151,442,200,200'/><NodePosition Node='-1762' Position='1204,556,200,200'/><NodePosition Node='-1766' Position='1174,898,200,200'/><NodePosition Node='-2137' Position='953,1031,200,200'/></NodePositions><NodeGroups /></DataV1>"},"IsDraft":true,"ParentExperimentId":null,"WebService":{"IsWebServiceExperiment":false,"Inputs":[],"Outputs":[],"Parameters":[{"Name":"交易日期","Value":"","ParameterDefinition":{"Name":"交易日期","FriendlyName":"交易日期","DefaultValue":"","ParameterType":"String","HasDefaultValue":true,"IsOptional":true,"ParameterRules":[],"HasRules":false,"MarkupType":0,"CredentialDescriptor":null}}],"WebServiceGroupId":null,"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions></NodePositions><NodeGroups /></DataV1>"},"DisableNodesUpdate":false,"Category":"user","Tags":[],"IsPartialRun":false}
    In [7]:
    # 本代码由可视化策略环境自动生成 2018年1月4日 16:10
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date='2012-01-01',
        end_date='2016-01-01',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m2 = M.advanced_auto_labeler.v2(
        instruments=m1.data,
        label_expr="""# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html
    #   添加benchmark_前缀,可使用对应的benchmark数据
    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_
    
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格) - 1
    shift(close, -5) / shift(open, -1) - 1  
    
    # 极值处理:用1%和99%分位的值做clip
    clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
    
    # 将分数映射到分类,这里使用10个分类
    all_wbins(label, 10)
    
    # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
    where(shift(high, -1) == shift(low, -1), NaN, label)
    """,
        start_date='',
        end_date='',
        benchmark='000300.SHA',
        drop_na_label=True,
        cast_label_int=True,
        user_functions={}
    )
    
    m3 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    return_5
    close_0 / close_1
    return_10
    return_20
    avg_amount_0/avg_amount_5
    avg_amount_5/avg_amount_20
    pe_ttm_0
    beta_csi800_5_0
    swing_volatility_5_0
    ta_macd_macd_12_26_9_0
    ta_willr_14_0
    ta_mom_10_0
    ta_sar_0
    rank_avg_amount_0/rank_avg_amount_5
    rank_avg_amount_5/rank_avg_amount_10
    rank_return_0
    rank_return_5
    rank_return_10
    rank_return_0/rank_return_5
    rank_return_5/rank_return_10"""
    )
    
    m4 = M.general_feature_extractor.v6(
        instruments=m1.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m5 = M.derived_feature_extractor.v2(
        input_data=m4.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        user_functions={}
    )
    
    m6 = M.join.v3(
        data1=m2.data,
        data2=m5.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m7 = M.dropnan.v1(
        input_data=m6.data
    )
    
    m8 = M.random_forest_train.v2(
        training_ds=m7.data,
        features=m3.data,
        n_estimators=15,
        max_features='auto',
        max_depth=25,
        min_samples_leaf=200,
        n_jobs=1,
        algo='regressor'
    )
    
    m9 = M.instruments.v2(
        start_date='2016-01-01',
        end_date='2017-01-01',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m10 = M.general_feature_extractor.v6(
        instruments=m9.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m11 = M.derived_feature_extractor.v2(
        input_data=m10.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        user_functions={}
    )
    
    m12 = M.dropnan.v1(
        input_data=m11.data
    )
    
    m13 = M.random_forest_predict.v2(
        model=m8.model,
        data=m12.data,
        date_col='date',
        instrument_col='instrument',
        sort=True
    )
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m14_handle_data_bigquant_run(context, data):
        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
    
        # 1. 资金分配
        # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
        # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
        is_staging = context.trading_day_index < context.hold_days # 是否在建仓期间(前 hold_days 天)
        cash_avg = context.portfolio.portfolio_value / context.hold_days
        cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
        cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
        positions = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
        
        '''
        date = data.current_dt.strftime('%Y-%m-%d')   
        #------------------------------------------止损模块START--------------------------------------------
        current_stoploss_stock = [] 
        if len(positions) > 0:
            for i in positions.keys():
                stock_cost = positions[i] 
                stock_market_price = data.current(context.symbol(i), 'price') 
                # 亏3%就止损
                if (stock_market_price - stock_cost) / stock_cost <= -0.03:   
                    context.order_target_percent(context.symbol(i),0)     
                    current_stoploss_stock.append(i)
                    #print('日期:',date,'股票:',i,'出现止损状况')
        #-------------------------------------------止损模块END---------------------------------------------
        '''
        
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
        if not is_staging and cash_for_sell > 0:
            equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
            instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                    lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
            # print('rank order for sell %s' % instruments)
            for instrument in instruments:
                context.order_target(context.symbol(instrument), 0)
                cash_for_sell -= positions[instrument]
                if cash_for_sell <= 0:
                    break
    
        # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票
        buy_cash_weights = context.stock_weights
        buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])
        max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
        for i, instrument in enumerate(buy_instruments):
            cash = cash_for_buy * buy_cash_weights[i]
            if cash > max_cash_per_instrument - positions.get(instrument, 0):
                # 确保股票持仓量不会超过每次股票最大的占用资金量
                cash = max_cash_per_instrument - positions.get(instrument, 0)
            if cash > 0:
                context.order_value(context.symbol(instrument), cash)
    
    # 回测引擎:准备数据,只执行一次
    def m14_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:初始化函数,只执行一次
    def m14_initialize_bigquant_run(context):
        # 加载预测数据
        context.ranker_prediction = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        #context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
        # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        stock_count = 5
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        context.stock_weights = T.norm([1 / math.exp(i) for i in range(0, stock_count)])
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 0.2
        context.hold_days = 5
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m14_before_trading_start_bigquant_run(context, data):
        pass
    
    m14 = M.trade.v3(
        instruments=m9.data,
        options_data=m13.predictions,
        start_date='',
        end_date='',
        handle_data=m14_handle_data_bigquant_run,
        prepare=m14_prepare_bigquant_run,
        initialize=m14_initialize_bigquant_run,
        before_trading_start=m14_before_trading_start_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='close',
        capital_base=1000000,
        benchmark='000300.SHA',
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        plot_charts=True,
        backtest_only=False,
        amount_integer=False
    )
    
    [2018-01-04 14:54:29.434248] INFO: bigquant: instruments.v2 开始运行..
    [2018-01-04 14:54:29.438649] INFO: bigquant: 命中缓存
    [2018-01-04 14:54:29.439599] INFO: bigquant: instruments.v2 运行完成[0.005406s].
    [2018-01-04 14:54:29.448660] INFO: bigquant: advanced_auto_labeler.v2 开始运行..
    [2018-01-04 14:54:29.451582] INFO: bigquant: 命中缓存
    [2018-01-04 14:54:29.452529] INFO: bigquant: advanced_auto_labeler.v2 运行完成[0.003865s].
    [2018-01-04 14:54:29.457999] INFO: bigquant: input_features.v1 开始运行..
    [2018-01-04 14:54:29.461224] INFO: bigquant: 命中缓存
    [2018-01-04 14:54:29.462437] INFO: bigquant: input_features.v1 运行完成[0.004467s].
    [2018-01-04 14:54:29.471448] INFO: bigquant: general_feature_extractor.v6 开始运行..
    [2018-01-04 14:54:29.474809] INFO: bigquant: 命中缓存
    [2018-01-04 14:54:29.476027] INFO: bigquant: general_feature_extractor.v6 运行完成[0.00459s].
    [2018-01-04 14:54:29.483184] INFO: bigquant: derived_feature_extractor.v2 开始运行..
    [2018-01-04 14:54:29.486810] INFO: bigquant: 命中缓存
    [2018-01-04 14:54:29.487947] INFO: bigquant: derived_feature_extractor.v2 运行完成[0.004739s].
    [2018-01-04 14:54:29.496281] INFO: bigquant: join.v3 开始运行..
    [2018-01-04 14:54:29.499481] INFO: bigquant: 命中缓存
    [2018-01-04 14:54:29.500717] INFO: bigquant: join.v3 运行完成[0.00445s].
    [2018-01-04 14:54:29.508383] INFO: bigquant: dropnan.v1 开始运行..
    [2018-01-04 14:54:29.511351] INFO: bigquant: 命中缓存
    [2018-01-04 14:54:29.512720] INFO: bigquant: dropnan.v1 运行完成[0.004384s].
    [2018-01-04 14:54:29.521122] INFO: bigquant: random_forest_train.v2 开始运行..
    [2018-01-04 15:26:57.981913] INFO: random_forest_train: 模型在训练集分数是:0.16
    [2018-01-04 15:26:58.035136] INFO: bigquant: random_forest_train.v2 运行完成[1948.513938s].
    [2018-01-04 15:26:58.054860] INFO: bigquant: instruments.v2 开始运行..
    [2018-01-04 15:26:58.059209] INFO: bigquant: 命中缓存
    [2018-01-04 15:26:58.060758] INFO: bigquant: instruments.v2 运行完成[0.005922s].
    [2018-01-04 15:26:58.070541] INFO: bigquant: general_feature_extractor.v6 开始运行..
    [2018-01-04 15:26:58.073871] INFO: bigquant: 命中缓存
    [2018-01-04 15:26:58.075293] INFO: bigquant: general_feature_extractor.v6 运行完成[0.004759s].
    [2018-01-04 15:26:58.083648] INFO: bigquant: derived_feature_extractor.v2 开始运行..
    [2018-01-04 15:26:58.087495] INFO: bigquant: 命中缓存
    [2018-01-04 15:26:58.088976] INFO: bigquant: derived_feature_extractor.v2 运行完成[0.005351s].
    [2018-01-04 15:26:58.096653] INFO: bigquant: dropnan.v1 开始运行..
    [2018-01-04 15:26:58.099882] INFO: bigquant: 命中缓存
    [2018-01-04 15:26:58.100913] INFO: bigquant: dropnan.v1 运行完成[0.004286s].
    [2018-01-04 15:26:58.108382] INFO: bigquant: random_forest_predict.v2 开始运行..
    [2018-01-04 15:27:05.315420] INFO: bigquant: random_forest_predict.v2 运行完成[7.206957s].
    [2018-01-04 15:27:05.352793] INFO: bigquant: backtest.v7 开始运行..
    [2018-01-04 15:27:05.467240] INFO: algo: set price type:backward_adjusted
    [2018-01-04 15:27:43.244830] INFO: Performance: Simulated 244 trading days out of 244.
    [2018-01-04 15:27:43.246365] INFO: Performance: first open: 2016-01-04 01:30:00+00:00
    [2018-01-04 15:27:43.247355] INFO: Performance: last close: 2016-12-30 07:00:00+00:00
    
    • 收益率31.53%
    • 年化收益率32.72%
    • 基准收益率-11.28%
    • 阿尔法0.46
    • 贝塔1.1
    • 夏普比率0.82
    • 胜率0.552
    • 盈亏比1.088
    • 收益波动率35.58%
    • 信息比率1.72
    • 最大回撤19.59%
    [2018-01-04 15:27:45.296911] INFO: bigquant: backtest.v7 运行完成[39.944128s].
    
    In [8]:
    #查看feature的贡献值
    m8.feature_gains.read_df()
    
    Out[8]:
    feature gain
    13 return_20 0.138858
    14 return_5 0.106447
    2 beta_csi800_5_0 0.097277
    3 close_0 / close_1 0.090453
    16 ta_macd_macd_12_26_9_0 0.079822
    12 return_10 0.066604
    10 rank_return_5 0.061116
    15 swing_volatility_5_0 0.051593
    9 rank_return_10 0.045513
    7 rank_return_0 0.039309
    1 avg_amount_5/avg_amount_20 0.035154
    0 avg_amount_0/avg_amount_5 0.029777
    19 ta_willr_14_0 0.027887
    17 ta_mom_10_0 0.027451
    4 pe_ttm_0 0.020573
    18 ta_sar_0 0.019055
    11 rank_return_5/rank_return_10 0.017307
    6 rank_avg_amount_5/rank_avg_amount_10 0.016754
    5 rank_avg_amount_0/rank_avg_amount_5 0.015697
    8 rank_return_0/rank_return_5 0.013355
    In [10]:
    #数据处理之后,训练数据的shape
    m7.data.read_df().shape
    
    Out[10]:
    (2228836, 36)
    In [11]:
    #数据处理之后,训练数据的前5行
    m7.data.read_df().head()
    
    Out[11]:
    avg_amount_0 avg_amount_20 avg_amount_5 beta_csi800_5_0 close_0 close_1 date instrument pe_ttm_0 rank_avg_amount_0 ... rank_avg_amount_0/rank_avg_amount_5 rank_avg_amount_5/rank_avg_amount_10 rank_return_0/rank_return_5 rank_return_5/rank_return_10 m:amount m:open m:high m:low m:close label
    0 227563712.0 212787168.0 221585424.0 0.857026 544.327881 559.767273 2012-01-04 000001.SZA 8.408521 0.981124 ... 1.000052 1.006531 0.619428 0.873159 227563712.0 559.767273 559.767273 543.968811 544.327881 6
    1 375880608.0 216905296.0 265260960.0 0.690610 552.586121 544.327881 2012-01-05 000001.SZA 8.536091 0.990979 ... 1.004610 1.008809 1.051886 0.978607 375880608.0 544.327881 558.330994 543.250671 552.586121 6
    2 204143664.0 218020976.0 263458256.0 0.649115 551.149902 552.586121 2012-01-06 000001.SZA 8.513905 0.978962 ... 0.991878 1.006446 0.351722 0.839901 204143664.0 551.149902 556.894775 543.968811 551.149902 5
    3 345938688.0 223153184.0 292223520.0 0.678302 566.589294 551.149902 2012-01-09 000001.SZA 8.752404 0.981590 ... 0.994558 1.007863 0.186488 0.879588 345938688.0 551.508972 567.666443 547.559387 566.589294 4
    4 972826816.0 255242704.0 421510400.0 0.904071 602.494812 566.589294 2012-01-20 000001.SZA 9.307056 0.997319 ... 1.012265 1.009210 1.000036 1.657656 972826816.0 600.699524 608.239685 585.978271 602.494812 4

    5 rows × 36 columns