【研报复现大赛】基础篇(评审中)

研报复现大赛
标签: #<Tag:0x00007f51f95d8278>

#1

一、 比赛时间安排:2019年6月24日-2019年7月22日

1. 研报复现期:6月24日-7月15日,参赛者可进行多次策略修改和优化
2. 策略提交期:6月24日-7月15日,将复现的策略分享至当前赛道的评论区,之后分享的策略不计入比赛
3. 策略评审期:7月15日-7月22日,策略展示获得获点赞和BigQuant专家评审
4. 排名公布期:7月23日公布排名榜单

二、 比赛简介:

精选3个研报进行复现,任务策略排名top5的参赛者将获得现金奖励。

三、比赛研报:

  1. 华泰单因子测试之动量类因子
  2. 华泰单因子测试之估值类因子
  3. 华泰单因子测试之财务质量因子

四、 策略编写规则

1. 参照模板策略构建策略:
    训练集时间范围:2010-01-01 - 2016-12-31
    测试集时间范围:2017-01-01 - 2019-06-01
    标注及轮仓周期:22个交易日
    算法: StockRanker
2.  策略构建要求:
    因子特征必须来自上述三篇研报;
    可以单因子/多因子组合
    必须提交可视化策略

五、 考核原则:

    每个用户只能通过本贴的回帖方式提交一次最满意的策略结果
    总评分=策略点赞评分+专家评审评分+提交时间评分
    专家评审评分原则:给定测试集时间范围的策略阶段收益率,夏普比率,1/最大回撤三个指标的综合排名
    策略排名top5的参赛者将获得现金奖励

六、 模板链接:

https://i.bigquant.com/user/tmao1996/lab/share/%E7%AD%96%E7%95%A5%E6%A8%A1%E6%9D%BF_%E4%B8%8A%E4%BC%A0.ipynb


BigQuant研报复现PK赛(有奖竞赛)
(江旭奇) #3
克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-143:input_1","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-143:data_1"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nsum((close_0/shift(close_0,1)-1) * turn_0,22)/22\nEP = fs_net_profit_0/market_cap_0\nSP = fs_operating_revenue_0/market_cap_0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, N):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read_df().set_index('date')\n def cal(x):\n weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])\n result = np.dot(x,weights)\n return result\n df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})\n df1 = df1.merge(df.reset_index(),on=['date','instrument'])\n data_1 = DataSource.write_df(df1)\n return Outputs(data_1=data_1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'N':1\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-143","OutputType":null},{"Name":"data_2","NodeId":"-143","OutputType":null},{"Name":"data_3","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='757.4182739257812,-111.5837367773056,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='923.897216796875,116.8839111328125,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='348.72247314453125,600.758544921875,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='316.4789123535156,202.4676513671875,200,200'/><NodePosition Node='-222' Position='378.6063537597656,334.9239501953125,200,200'/><NodePosition Node='-231' Position='914.188232421875,303.12542724609375,200,200'/><NodePosition Node='-238' Position='943.04931640625,416.6824645996094,200,200'/><NodePosition Node='-143' Position='1013,605.5190124511719,200,200'/><NodePosition Node='-1228' Position='956.5950927734375,985.0761108398438,200,200'/><NodePosition Node='-7106' Position='451.08740234375,771.6064453125,200,200'/><NodePosition Node='-7117' Position='589.937255859375,84.36691284179688,200,200'/><NodePosition Node='-2618' Position='520.190185546875,970.21484375,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":true}
    In [22]:
    # 本代码由可视化策略环境自动生成 2019年6月28日 19:33
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m5_run_bigquant_run(input_1, N):
        # 示例代码如下。在这里编写您的代码
        df=input_1.read_df().set_index('date')
        def cal(x):
            weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])
            result = np.dot(x,weights)
            return result
        df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})
        df1 = df1.merge(df.reset_index(),on=['date','instrument'])
        data_1 = DataSource.write_df(df1)
        return Outputs(data_1=data_1)
    
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m5_post_run_bigquant_run(outputs):
        return outputs
    
    # 回测引擎:初始化函数,只执行一次
    def m23_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))
    
        context.options['hold_days'] = 22
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m23_handle_data_bigquant_run(context, data):
    
        if context.trading_day_index%context.options['hold_days'] !=0:
            return
        
        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
              context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
        layer = len(ranker_prediction)
        if layer==0:
            return
        ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
        ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
        stock_to_buy = list(ranker_prediction.instrument)
        
        # 定期轮仓卖出
        positions = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.portfolio.positions.items()}
       
        stock_to_sell = [k for k in positions if k not in stock_to_buy]
    
        for instrument in stock_to_sell:
            context.order_target(context.symbol(instrument), 0)
    
        # 定期买入
        weight = [1/len(stock_to_buy) for k in stock_to_buy]
        #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
        for i,instrument in enumerate(stock_to_buy):
            context.order_target_percent(context.symbol(instrument), weight[i])
    
    # 回测引擎:准备数据,只执行一次
    def m23_prepare_bigquant_run(context):
        pass
    
    
    m1 = M.instruments.v2(
        start_date='2010-01-01',
        end_date='2016-12-31',
        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/develop/datasource/deprecated/history_data.html
    #   添加benchmark_前缀,可使用对应的benchmark数据
    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
    
    # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    shift(close, -22) / shift(open, -1)
    
    # 极值处理:用1%和99%分位的值做clip
    clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
    
    # 将分数映射到分类,这里使用20个分类
    all_wbins(label, 20)
    
    # 过滤掉一字涨停的情况 (设置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
    )
    
    m3 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    #每日换手率作为权重对每日收益率求算术平均值
    sum((close_0/shift(close_0,1)-1) * turn_0,22)/22
    EP = fs_net_profit_0/market_cap_0
    SP = fs_operating_revenue_0/market_cap_0"""
    )
    
    m6 = M.input_features.v1(
        features_ds=m3.data,
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    shift(close_0,-22)/close_0-1
    """
    )
    
    m15 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m6.data,
        start_date='',
        end_date='',
        before_start_days=120
    )
    
    m16 = M.derived_feature_extractor.v3(
        input_data=m15.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=True,
        remove_extra_columns=False
    )
    
    m7 = M.join.v3(
        data1=m2.data,
        data2=m16.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m13 = M.dropnan.v1(
        input_data=m7.data
    )
    
    m9 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2017-01-01'),
        end_date=T.live_run_param('trading_date', '2019-06-01'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m17 = M.general_feature_extractor.v7(
        instruments=m9.data,
        features=m6.data,
        start_date='',
        end_date='',
        before_start_days=200
    )
    
    m18 = M.derived_feature_extractor.v3(
        input_data=m17.data,
        features=m6.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=True,
        remove_extra_columns=False
    )
    
    m5 = M.cached.v3(
        input_1=m18.data,
        run=m5_run_bigquant_run,
        post_run=m5_post_run_bigquant_run,
        input_ports='',
        params="""{
        'N':1
    }""",
        output_ports=''
    )
    
    m14 = M.dropnan.v1(
        input_data=m5.data_1
    )
    
    m12 = M.stock_ranker.v2(
        training_ds=m13.data,
        features=m3.data,
        predict_ds=m14.data,
        learning_algorithm='排序',
        number_of_leaves=30,
        minimum_docs_per_leaf=1000,
        number_of_trees=20,
        learning_rate=0.1,
        max_bins=1023,
        feature_fraction=1,
        slim_data=True
    )
    
    m23 = M.trade.v4(
        instruments=m9.data,
        options_data=m12.predictions,
        start_date='',
        end_date='',
        initialize=m23_initialize_bigquant_run,
        handle_data=m23_handle_data_bigquant_run,
        prepare=m23_prepare_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='close',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark='000300.SHA'
    )
    
    m4 = M.StockRanker_grouptest.v3(
        input_1=m9.data,
        input_2=m12.predictions,
        input_3=m14.data,
        ret_column='shift(close_0,-22)/close_0-1',
        N=22,
        m_cached=False
    )
    
    设置测试数据集,查看训练迭代过程的NDCG
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-2ec8f3143c7d4d34bb2e475f0fb59ec6"}/bigcharts-data-end
    • 收益率-25.2%
    • 年化收益率-11.74%
    • 基准收益率9.66%
    • 阿尔法-0.16
    • 贝塔0.53
    • 夏普比率-0.99
    • 胜率0.42
    • 盈亏比1.05
    • 收益波动率14.58%
    • 信息比率-0.08
    • 最大回撤36.91%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-27686ef9962b490da59c663bce8d42c4"}/bigcharts-data-end

    (c2ba31) #4
    克隆策略

      {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-143:input_1","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-143:data_1"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nsum(turn_0*return_0,66)/66\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, N):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read_df().set_index('date')\n def cal(x):\n weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])\n result = np.dot(x,weights)\n return result\n df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})\n df1 = df1.merge(df.reset_index(),on=['date','instrument'])\n data_1 = DataSource.write_df(df1)\n return Outputs(data_1=data_1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'N':1\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-143","OutputType":null},{"Name":"data_2","NodeId":"-143","OutputType":null},{"Name":"data_3","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='724,-25,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1012,246,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='291,660,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='438,245,200,200'/><NodePosition Node='-222' Position='450,341,200,200'/><NodePosition Node='-231' Position='1019,373,200,200'/><NodePosition Node='-238' Position='1019,482,200,200'/><NodePosition Node='-143' Position='1013,604,200,200'/><NodePosition Node='-1228' Position='949,979,200,200'/><NodePosition Node='-7106' Position='524,843,200,200'/><NodePosition Node='-7117' Position='555,95,200,200'/><NodePosition Node='-2618' Position='505,993,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":true}
      In [2]:
      # 本代码由可视化策略环境自动生成 2019年7月5日 16:24
      # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
      
      
      # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
      def m5_run_bigquant_run(input_1, N):
          # 示例代码如下。在这里编写您的代码
          df=input_1.read_df().set_index('date')
          def cal(x):
              weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])
              result = np.dot(x,weights)
              return result
          df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})
          df1 = df1.merge(df.reset_index(),on=['date','instrument'])
          data_1 = DataSource.write_df(df1)
          return Outputs(data_1=data_1)
      
      
      # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
      def m5_post_run_bigquant_run(outputs):
          return outputs
      
      # 回测引擎:初始化函数,只执行一次
      def m23_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))
      
          context.options['hold_days'] = 22
      
      # 回测引擎:每日数据处理函数,每天执行一次
      def m23_handle_data_bigquant_run(context, data):
      
          if context.trading_day_index%context.options['hold_days'] !=0:
              return
          
          # 按日期过滤得到今日的预测数据
          ranker_prediction = context.ranker_prediction[
                context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
          layer = len(ranker_prediction)
          if layer==0:
              return
          ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
          ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
          stock_to_buy = list(ranker_prediction.instrument)
          
          # 定期轮仓卖出
          positions = {e.symbol: p.amount * p.last_sale_price
                       for e, p in context.portfolio.positions.items()}
         
          stock_to_sell = [k for k in positions if k not in stock_to_buy]
      
          for instrument in stock_to_sell:
              context.order_target(context.symbol(instrument), 0)
      
          # 定期买入
          weight = [1/len(stock_to_buy) for k in stock_to_buy]
          #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
          for i,instrument in enumerate(stock_to_buy):
              context.order_target_percent(context.symbol(instrument), weight[i])
      
      # 回测引擎:准备数据,只执行一次
      def m23_prepare_bigquant_run(context):
          pass
      
      
      m1 = M.instruments.v2(
          start_date='2010-01-01',
          end_date='2016-12-31',
          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/develop/datasource/deprecated/history_data.html
      #   添加benchmark_前缀,可使用对应的benchmark数据
      # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
      
      # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
      shift(close, -22) / shift(open, -1)
      
      # 极值处理:用1%和99%分位的值做clip
      clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
      
      # 将分数映射到分类,这里使用20个分类
      all_wbins(label, 20)
      
      # 过滤掉一字涨停的情况 (设置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
      )
      
      m3 = M.input_features.v1(
          features="""# #号开始的表示注释
      # 多个特征,每行一个,可以包含基础特征和衍生特征
      #每日换手率作为权重对每日收益率求算术平均值
      sum(turn_0*return_0,66)/66
      """
      )
      
      m6 = M.input_features.v1(
          features_ds=m3.data,
          features="""
      # #号开始的表示注释,注释需单独一行
      # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
      shift(close_0,-22)/close_0-1"""
      )
      
      m15 = M.general_feature_extractor.v7(
          instruments=m1.data,
          features=m6.data,
          start_date='',
          end_date='',
          before_start_days=120
      )
      
      m16 = M.derived_feature_extractor.v3(
          input_data=m15.data,
          features=m6.data,
          date_col='date',
          instrument_col='instrument',
          drop_na=True,
          remove_extra_columns=False
      )
      
      m7 = M.join.v3(
          data1=m2.data,
          data2=m16.data,
          on='date,instrument',
          how='inner',
          sort=False
      )
      
      m13 = M.dropnan.v1(
          input_data=m7.data
      )
      
      m9 = M.instruments.v2(
          start_date=T.live_run_param('trading_date', '2017-01-01'),
          end_date=T.live_run_param('trading_date', '2019-06-01'),
          market='CN_STOCK_A',
          instrument_list='',
          max_count=0
      )
      
      m17 = M.general_feature_extractor.v7(
          instruments=m9.data,
          features=m6.data,
          start_date='',
          end_date='',
          before_start_days=200
      )
      
      m18 = M.derived_feature_extractor.v3(
          input_data=m17.data,
          features=m6.data,
          date_col='date',
          instrument_col='instrument',
          drop_na=True,
          remove_extra_columns=False
      )
      
      m5 = M.cached.v3(
          input_1=m18.data,
          run=m5_run_bigquant_run,
          post_run=m5_post_run_bigquant_run,
          input_ports='',
          params="""{
          'N':1
      }""",
          output_ports=''
      )
      
      m14 = M.dropnan.v1(
          input_data=m5.data_1
      )
      
      m12 = M.stock_ranker.v2(
          training_ds=m13.data,
          features=m3.data,
          predict_ds=m14.data,
          learning_algorithm='排序',
          number_of_leaves=30,
          minimum_docs_per_leaf=1000,
          number_of_trees=20,
          learning_rate=0.1,
          max_bins=1023,
          feature_fraction=1,
          slim_data=True
      )
      
      m23 = M.trade.v4(
          instruments=m9.data,
          options_data=m12.predictions,
          start_date='',
          end_date='',
          initialize=m23_initialize_bigquant_run,
          handle_data=m23_handle_data_bigquant_run,
          prepare=m23_prepare_bigquant_run,
          volume_limit=0.025,
          order_price_field_buy='open',
          order_price_field_sell='close',
          capital_base=1000000,
          auto_cancel_non_tradable_orders=True,
          data_frequency='daily',
          price_type='后复权',
          product_type='股票',
          plot_charts=True,
          backtest_only=False,
          benchmark='000300.SHA'
      )
      
      m4 = M.StockRanker_grouptest.v3(
          input_1=m9.data,
          input_2=m12.predictions,
          input_3=m14.data,
          ret_column='shift(close_0,-22)/close_0-1',
          N=22,
          m_cached=False
      )
      
      设置测试数据集,查看训练迭代过程的NDCG
      bigcharts-data-start/{"__id":"bigchart-7857560897404e9ca280846d46339760","__type":"tabs"}/bigcharts-data-end
      设置测试数据集,查看训练迭代过程的NDCG
      bigcharts-data-start/{"__id":"bigchart-255581abff0848768dfff58695d1824f","__type":"tabs"}/bigcharts-data-end
      • 收益率-26.96%
      • 年化收益率-12.64%
      • 基准收益率9.66%
      • 阿尔法-0.17
      • 贝塔0.61
      • 夏普比率-0.96
      • 胜率0.45
      • 盈亏比0.9
      • 收益波动率15.88%
      • 信息比率-0.09
      • 最大回撤40.03%
      bigcharts-data-start/{"__id":"bigchart-0f1811e6cd284a118d95399f313df2a4","__type":"tabs"}/bigcharts-data-end

      (jamesbb) #6
      克隆策略

        {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-143:input_1","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-143:data_1"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nfs_roe_0\nsum(turn_0*return_0,264)/264\nfs_net_profit_ttm_0/market_cap_0\nfs_net_cash_flow_0/market_cap_0\nsum(turn_0*return_0,66)/66\n(fs_bps_0*fs_paicl_up_capital_0)/market_cap_0\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, N):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read_df().set_index('date')\n def cal(x):\n weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])\n result = np.dot(x,weights)\n return result\n df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})\n df1 = df1.merge(df.reset_index(),on=['date','instrument'])\n data_1 = DataSource.write_df(df1)\n return Outputs(data_1=data_1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'N':1\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-143","OutputType":null},{"Name":"data_2","NodeId":"-143","OutputType":null},{"Name":"data_3","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='724,-25,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1012,246,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='291,660,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='438,245,200,200'/><NodePosition Node='-222' Position='450,341,200,200'/><NodePosition Node='-231' Position='1019,373,200,200'/><NodePosition Node='-238' Position='1019,482,200,200'/><NodePosition Node='-143' Position='1013,604,200,200'/><NodePosition Node='-1228' Position='949,979,200,200'/><NodePosition Node='-7106' Position='524,843,200,200'/><NodePosition Node='-7117' Position='555,95,200,200'/><NodePosition Node='-2618' Position='505,993,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":true}
        In [1]:
        # 本代码由可视化策略环境自动生成 2019年7月5日 17:15
        # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
        
        
        # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
        def m5_run_bigquant_run(input_1, N):
            # 示例代码如下。在这里编写您的代码
            df=input_1.read_df().set_index('date')
            def cal(x):
                weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])
                result = np.dot(x,weights)
                return result
            df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})
            df1 = df1.merge(df.reset_index(),on=['date','instrument'])
            data_1 = DataSource.write_df(df1)
            return Outputs(data_1=data_1)
        
        
        # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
        def m5_post_run_bigquant_run(outputs):
            return outputs
        
        # 回测引擎:初始化函数,只执行一次
        def m23_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))
        
            context.options['hold_days'] = 22
        
        # 回测引擎:每日数据处理函数,每天执行一次
        def m23_handle_data_bigquant_run(context, data):
        
            if context.trading_day_index%context.options['hold_days'] !=0:
                return
            
            # 按日期过滤得到今日的预测数据
            ranker_prediction = context.ranker_prediction[
                  context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
            layer = len(ranker_prediction)
            if layer==0:
                return
            ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
            ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
            stock_to_buy = list(ranker_prediction.instrument)
            
            # 定期轮仓卖出
            positions = {e.symbol: p.amount * p.last_sale_price
                         for e, p in context.portfolio.positions.items()}
           
            stock_to_sell = [k for k in positions if k not in stock_to_buy]
        
            for instrument in stock_to_sell:
                context.order_target(context.symbol(instrument), 0)
        
            # 定期买入
            weight = [1/len(stock_to_buy) for k in stock_to_buy]
            #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
            for i,instrument in enumerate(stock_to_buy):
                context.order_target_percent(context.symbol(instrument), weight[i])
        
        # 回测引擎:准备数据,只执行一次
        def m23_prepare_bigquant_run(context):
            pass
        
        
        m1 = M.instruments.v2(
            start_date='2010-01-01',
            end_date='2016-12-31',
            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/develop/datasource/deprecated/history_data.html
        #   添加benchmark_前缀,可使用对应的benchmark数据
        # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
        
        # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
        shift(close, -22) / shift(open, -1)
        
        # 极值处理:用1%和99%分位的值做clip
        clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
        
        # 将分数映射到分类,这里使用20个分类
        all_wbins(label, 20)
        
        # 过滤掉一字涨停的情况 (设置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
        )
        
        m3 = M.input_features.v1(
            features="""# #号开始的表示注释
        # 多个特征,每行一个,可以包含基础特征和衍生特征
        #每日换手率作为权重对每日收益率求算术平均值
        fs_roe_0
        sum(turn_0*return_0,264)/264
        fs_net_profit_ttm_0/market_cap_0
        fs_net_cash_flow_0/market_cap_0
        sum(turn_0*return_0,66)/66
        (fs_bps_0*fs_paicl_up_capital_0)/market_cap_0
        """
        )
        
        m6 = M.input_features.v1(
            features_ds=m3.data,
            features="""
        # #号开始的表示注释,注释需单独一行
        # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
        shift(close_0,-22)/close_0-1"""
        )
        
        m15 = M.general_feature_extractor.v7(
            instruments=m1.data,
            features=m6.data,
            start_date='',
            end_date='',
            before_start_days=120
        )
        
        m16 = M.derived_feature_extractor.v3(
            input_data=m15.data,
            features=m6.data,
            date_col='date',
            instrument_col='instrument',
            drop_na=True,
            remove_extra_columns=False
        )
        
        m7 = M.join.v3(
            data1=m2.data,
            data2=m16.data,
            on='date,instrument',
            how='inner',
            sort=False
        )
        
        m13 = M.dropnan.v1(
            input_data=m7.data
        )
        
        m9 = M.instruments.v2(
            start_date=T.live_run_param('trading_date', '2017-01-01'),
            end_date=T.live_run_param('trading_date', '2019-06-01'),
            market='CN_STOCK_A',
            instrument_list='',
            max_count=0
        )
        
        m17 = M.general_feature_extractor.v7(
            instruments=m9.data,
            features=m6.data,
            start_date='',
            end_date='',
            before_start_days=200
        )
        
        m18 = M.derived_feature_extractor.v3(
            input_data=m17.data,
            features=m6.data,
            date_col='date',
            instrument_col='instrument',
            drop_na=True,
            remove_extra_columns=False
        )
        
        m5 = M.cached.v3(
            input_1=m18.data,
            run=m5_run_bigquant_run,
            post_run=m5_post_run_bigquant_run,
            input_ports='',
            params="""{
            'N':1
        }""",
            output_ports=''
        )
        
        m14 = M.dropnan.v1(
            input_data=m5.data_1
        )
        
        m12 = M.stock_ranker.v2(
            training_ds=m13.data,
            features=m3.data,
            predict_ds=m14.data,
            learning_algorithm='排序',
            number_of_leaves=30,
            minimum_docs_per_leaf=1000,
            number_of_trees=20,
            learning_rate=0.1,
            max_bins=1023,
            feature_fraction=1,
            slim_data=True
        )
        
        m23 = M.trade.v4(
            instruments=m9.data,
            options_data=m12.predictions,
            start_date='',
            end_date='',
            initialize=m23_initialize_bigquant_run,
            handle_data=m23_handle_data_bigquant_run,
            prepare=m23_prepare_bigquant_run,
            volume_limit=0.025,
            order_price_field_buy='open',
            order_price_field_sell='close',
            capital_base=1000000,
            auto_cancel_non_tradable_orders=True,
            data_frequency='daily',
            price_type='后复权',
            product_type='股票',
            plot_charts=True,
            backtest_only=False,
            benchmark='000300.SHA'
        )
        
        m4 = M.StockRanker_grouptest.v3(
            input_1=m9.data,
            input_2=m12.predictions,
            input_3=m14.data,
            ret_column='shift(close_0,-22)/close_0-1',
            N=22,
            m_cached=False
        )
        
        设置测试数据集,查看训练迭代过程的NDCG
        bigcharts-data-start/{"__type":"tabs","__id":"bigchart-315dc8df9c094fb3a05ecdcf00b25a9a"}/bigcharts-data-end
        设置测试数据集,查看训练迭代过程的NDCG
        bigcharts-data-start/{"__type":"tabs","__id":"bigchart-3792e74966364319aa1e402c8cb4fd03"}/bigcharts-data-end
        • 收益率-24.8%
        • 年化收益率-11.54%
        • 基准收益率9.66%
        • 阿尔法-0.16
        • 贝塔0.63
        • 夏普比率-0.83
        • 胜率0.37
        • 盈亏比0.95
        • 收益波动率16.58%
        • 信息比率-0.08
        • 最大回撤42.1%
        bigcharts-data-start/{"__type":"tabs","__id":"bigchart-071bfb58d37a493faea08d5dc1ba5560"}/bigcharts-data-end

        (aason) #7
        克隆策略

          {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-143:input_1","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-143:data_1"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nsum((close_0/shift(close_0,1)-1) * turn_0,22)/22\n(fs_bps_0*fs_paicl_up_capital_0)/market_cap_0\nsum(turn_0*return_0,66)/66\nfs_net_cash_flow_ttm_0/market_cap_0\nsum(turn_0*return_0,264)/264\nfs_net_profit_ttm_0/market_cap_0\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, N):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read_df().set_index('date')\n def cal(x):\n weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])\n result = np.dot(x,weights)\n return result\n df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})\n df1 = df1.merge(df.reset_index(),on=['date','instrument'])\n data_1 = DataSource.write_df(df1)\n return Outputs(data_1=data_1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'N':1\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-143","OutputType":null},{"Name":"data_2","NodeId":"-143","OutputType":null},{"Name":"data_3","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='724,-25,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1012,246,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='291,660,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='438,245,200,200'/><NodePosition Node='-222' Position='450,341,200,200'/><NodePosition Node='-231' Position='1019,373,200,200'/><NodePosition Node='-238' Position='1019,482,200,200'/><NodePosition Node='-143' Position='1013,604,200,200'/><NodePosition Node='-1228' Position='949,979,200,200'/><NodePosition Node='-7106' Position='524,843,200,200'/><NodePosition Node='-7117' Position='555,95,200,200'/><NodePosition Node='-2618' Position='505,993,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":true}
          In [1]:
          # 本代码由可视化策略环境自动生成 2019年7月5日 18:55
          # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
          
          
          # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
          def m5_run_bigquant_run(input_1, N):
              # 示例代码如下。在这里编写您的代码
              df=input_1.read_df().set_index('date')
              def cal(x):
                  weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])
                  result = np.dot(x,weights)
                  return result
              df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})
              df1 = df1.merge(df.reset_index(),on=['date','instrument'])
              data_1 = DataSource.write_df(df1)
              return Outputs(data_1=data_1)
          
          
          # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
          def m5_post_run_bigquant_run(outputs):
              return outputs
          
          # 回测引擎:初始化函数,只执行一次
          def m23_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))
          
              context.options['hold_days'] = 22
          
          # 回测引擎:每日数据处理函数,每天执行一次
          def m23_handle_data_bigquant_run(context, data):
          
              if context.trading_day_index%context.options['hold_days'] !=0:
                  return
              
              # 按日期过滤得到今日的预测数据
              ranker_prediction = context.ranker_prediction[
                    context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
              layer = len(ranker_prediction)
              if layer==0:
                  return
              ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
              ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
              stock_to_buy = list(ranker_prediction.instrument)
              
              # 定期轮仓卖出
              positions = {e.symbol: p.amount * p.last_sale_price
                           for e, p in context.portfolio.positions.items()}
             
              stock_to_sell = [k for k in positions if k not in stock_to_buy]
          
              for instrument in stock_to_sell:
                  context.order_target(context.symbol(instrument), 0)
          
              # 定期买入
              weight = [1/len(stock_to_buy) for k in stock_to_buy]
              #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
              for i,instrument in enumerate(stock_to_buy):
                  context.order_target_percent(context.symbol(instrument), weight[i])
          
          # 回测引擎:准备数据,只执行一次
          def m23_prepare_bigquant_run(context):
              pass
          
          
          m1 = M.instruments.v2(
              start_date='2010-01-01',
              end_date='2016-12-31',
              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/develop/datasource/deprecated/history_data.html
          #   添加benchmark_前缀,可使用对应的benchmark数据
          # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
          
          # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
          shift(close, -22) / shift(open, -1)
          
          # 极值处理:用1%和99%分位的值做clip
          clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
          
          # 将分数映射到分类,这里使用20个分类
          all_wbins(label, 20)
          
          # 过滤掉一字涨停的情况 (设置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
          )
          
          m3 = M.input_features.v1(
              features="""# #号开始的表示注释
          # 多个特征,每行一个,可以包含基础特征和衍生特征
          #每日换手率作为权重对每日收益率求算术平均值
          sum((close_0/shift(close_0,1)-1) * turn_0,22)/22
          (fs_bps_0*fs_paicl_up_capital_0)/market_cap_0
          sum(turn_0*return_0,66)/66
          fs_net_cash_flow_ttm_0/market_cap_0
          sum(turn_0*return_0,264)/264
          fs_net_profit_ttm_0/market_cap_0
          """
          )
          
          m6 = M.input_features.v1(
              features_ds=m3.data,
              features="""
          # #号开始的表示注释,注释需单独一行
          # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
          shift(close_0,-22)/close_0-1"""
          )
          
          m15 = M.general_feature_extractor.v7(
              instruments=m1.data,
              features=m6.data,
              start_date='',
              end_date='',
              before_start_days=120
          )
          
          m16 = M.derived_feature_extractor.v3(
              input_data=m15.data,
              features=m6.data,
              date_col='date',
              instrument_col='instrument',
              drop_na=True,
              remove_extra_columns=False
          )
          
          m7 = M.join.v3(
              data1=m2.data,
              data2=m16.data,
              on='date,instrument',
              how='inner',
              sort=False
          )
          
          m13 = M.dropnan.v1(
              input_data=m7.data
          )
          
          m9 = M.instruments.v2(
              start_date=T.live_run_param('trading_date', '2017-01-01'),
              end_date=T.live_run_param('trading_date', '2019-06-01'),
              market='CN_STOCK_A',
              instrument_list='',
              max_count=0
          )
          
          m17 = M.general_feature_extractor.v7(
              instruments=m9.data,
              features=m6.data,
              start_date='',
              end_date='',
              before_start_days=200
          )
          
          m18 = M.derived_feature_extractor.v3(
              input_data=m17.data,
              features=m6.data,
              date_col='date',
              instrument_col='instrument',
              drop_na=True,
              remove_extra_columns=False
          )
          
          m5 = M.cached.v3(
              input_1=m18.data,
              run=m5_run_bigquant_run,
              post_run=m5_post_run_bigquant_run,
              input_ports='',
              params="""{
              'N':1
          }""",
              output_ports=''
          )
          
          m14 = M.dropnan.v1(
              input_data=m5.data_1
          )
          
          m12 = M.stock_ranker.v2(
              training_ds=m13.data,
              features=m3.data,
              predict_ds=m14.data,
              learning_algorithm='排序',
              number_of_leaves=30,
              minimum_docs_per_leaf=1000,
              number_of_trees=20,
              learning_rate=0.1,
              max_bins=1023,
              feature_fraction=1,
              slim_data=True
          )
          
          m23 = M.trade.v4(
              instruments=m9.data,
              options_data=m12.predictions,
              start_date='',
              end_date='',
              initialize=m23_initialize_bigquant_run,
              handle_data=m23_handle_data_bigquant_run,
              prepare=m23_prepare_bigquant_run,
              volume_limit=0.025,
              order_price_field_buy='open',
              order_price_field_sell='close',
              capital_base=1000000,
              auto_cancel_non_tradable_orders=True,
              data_frequency='daily',
              price_type='后复权',
              product_type='股票',
              plot_charts=True,
              backtest_only=False,
              benchmark='000300.SHA'
          )
          
          m4 = M.StockRanker_grouptest.v3(
              input_1=m9.data,
              input_2=m12.predictions,
              input_3=m14.data,
              ret_column='shift(close_0,-22)/close_0-1',
              N=22,
              m_cached=False
          )
          
          设置测试数据集,查看训练迭代过程的NDCG
          bigcharts-data-start/{"__type":"tabs","__id":"bigchart-248dcb6f38bd415e8f5c444361a972d6"}/bigcharts-data-end
          设置测试数据集,查看训练迭代过程的NDCG
          bigcharts-data-start/{"__type":"tabs","__id":"bigchart-710850a66b6a4ad8b5d0c6196ca7ac93"}/bigcharts-data-end
          • 收益率-26.17%
          • 年化收益率-12.23%
          • 基准收益率9.66%
          • 阿尔法-0.16
          • 贝塔0.59
          • 夏普比率-0.87
          • 胜率0.39
          • 盈亏比1.03
          • 收益波动率16.73%
          • 信息比率-0.07
          • 最大回撤40.65%
          bigcharts-data-start/{"__type":"tabs","__id":"bigchart-6916facf137c4391b2c59e196854ba5c"}/bigcharts-data-end

          (zhangzilan) #8
          克隆策略

            {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-143:input_1","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-143:data_1"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nsum((close_0/shift(close_0,1)-1) * turn_0,22)/22\nsum(turn_0*return_0,264)/264\nfs_net_cash_flow_ttm_0/market_cap_0\nsum(turn_0*return_0,66)/66\nfs_net_profit_ttm_0/market_cap_0\nfs_roe_0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, N):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read_df().set_index('date')\n def cal(x):\n weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])\n result = np.dot(x,weights)\n return result\n df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})\n df1 = df1.merge(df.reset_index(),on=['date','instrument'])\n data_1 = DataSource.write_df(df1)\n return Outputs(data_1=data_1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'N':1\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-143","OutputType":null},{"Name":"data_2","NodeId":"-143","OutputType":null},{"Name":"data_3","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='724,-25,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1012,246,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='291,660,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='438,245,200,200'/><NodePosition Node='-222' Position='450,341,200,200'/><NodePosition Node='-231' Position='1019,373,200,200'/><NodePosition Node='-238' Position='1019,482,200,200'/><NodePosition Node='-143' Position='1013,604,200,200'/><NodePosition Node='-1228' Position='949,979,200,200'/><NodePosition Node='-7106' Position='524,843,200,200'/><NodePosition Node='-7117' Position='555,95,200,200'/><NodePosition Node='-2618' Position='505,993,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":true}
            In [2]:
            # 本代码由可视化策略环境自动生成 2019年7月5日 19:02
            # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
            
            
            # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
            def m5_run_bigquant_run(input_1, N):
                # 示例代码如下。在这里编写您的代码
                df=input_1.read_df().set_index('date')
                def cal(x):
                    weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])
                    result = np.dot(x,weights)
                    return result
                df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})
                df1 = df1.merge(df.reset_index(),on=['date','instrument'])
                data_1 = DataSource.write_df(df1)
                return Outputs(data_1=data_1)
            
            
            # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
            def m5_post_run_bigquant_run(outputs):
                return outputs
            
            # 回测引擎:初始化函数,只执行一次
            def m23_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))
            
                context.options['hold_days'] = 22
            
            # 回测引擎:每日数据处理函数,每天执行一次
            def m23_handle_data_bigquant_run(context, data):
            
                if context.trading_day_index%context.options['hold_days'] !=0:
                    return
                
                # 按日期过滤得到今日的预测数据
                ranker_prediction = context.ranker_prediction[
                      context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
                layer = len(ranker_prediction)
                if layer==0:
                    return
                ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
                ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
                stock_to_buy = list(ranker_prediction.instrument)
                
                # 定期轮仓卖出
                positions = {e.symbol: p.amount * p.last_sale_price
                             for e, p in context.portfolio.positions.items()}
               
                stock_to_sell = [k for k in positions if k not in stock_to_buy]
            
                for instrument in stock_to_sell:
                    context.order_target(context.symbol(instrument), 0)
            
                # 定期买入
                weight = [1/len(stock_to_buy) for k in stock_to_buy]
                #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
                for i,instrument in enumerate(stock_to_buy):
                    context.order_target_percent(context.symbol(instrument), weight[i])
            
            # 回测引擎:准备数据,只执行一次
            def m23_prepare_bigquant_run(context):
                pass
            
            
            m1 = M.instruments.v2(
                start_date='2010-01-01',
                end_date='2016-12-31',
                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/develop/datasource/deprecated/history_data.html
            #   添加benchmark_前缀,可使用对应的benchmark数据
            # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
            
            # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
            shift(close, -22) / shift(open, -1)
            
            # 极值处理:用1%和99%分位的值做clip
            clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
            
            # 将分数映射到分类,这里使用20个分类
            all_wbins(label, 20)
            
            # 过滤掉一字涨停的情况 (设置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
            )
            
            m3 = M.input_features.v1(
                features="""# #号开始的表示注释
            # 多个特征,每行一个,可以包含基础特征和衍生特征
            #每日换手率作为权重对每日收益率求算术平均值
            sum((close_0/shift(close_0,1)-1) * turn_0,22)/22
            sum(turn_0*return_0,264)/264
            fs_net_cash_flow_ttm_0/market_cap_0
            sum(turn_0*return_0,66)/66
            fs_net_profit_ttm_0/market_cap_0
            fs_roe_0"""
            )
            
            m6 = M.input_features.v1(
                features_ds=m3.data,
                features="""
            # #号开始的表示注释,注释需单独一行
            # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
            shift(close_0,-22)/close_0-1"""
            )
            
            m15 = M.general_feature_extractor.v7(
                instruments=m1.data,
                features=m6.data,
                start_date='',
                end_date='',
                before_start_days=120
            )
            
            m16 = M.derived_feature_extractor.v3(
                input_data=m15.data,
                features=m6.data,
                date_col='date',
                instrument_col='instrument',
                drop_na=True,
                remove_extra_columns=False
            )
            
            m7 = M.join.v3(
                data1=m2.data,
                data2=m16.data,
                on='date,instrument',
                how='inner',
                sort=False
            )
            
            m13 = M.dropnan.v1(
                input_data=m7.data
            )
            
            m9 = M.instruments.v2(
                start_date=T.live_run_param('trading_date', '2017-01-01'),
                end_date=T.live_run_param('trading_date', '2019-06-01'),
                market='CN_STOCK_A',
                instrument_list='',
                max_count=0
            )
            
            m17 = M.general_feature_extractor.v7(
                instruments=m9.data,
                features=m6.data,
                start_date='',
                end_date='',
                before_start_days=200
            )
            
            m18 = M.derived_feature_extractor.v3(
                input_data=m17.data,
                features=m6.data,
                date_col='date',
                instrument_col='instrument',
                drop_na=True,
                remove_extra_columns=False
            )
            
            m5 = M.cached.v3(
                input_1=m18.data,
                run=m5_run_bigquant_run,
                post_run=m5_post_run_bigquant_run,
                input_ports='',
                params="""{
                'N':1
            }""",
                output_ports=''
            )
            
            m14 = M.dropnan.v1(
                input_data=m5.data_1
            )
            
            m12 = M.stock_ranker.v2(
                training_ds=m13.data,
                features=m3.data,
                predict_ds=m14.data,
                learning_algorithm='排序',
                number_of_leaves=30,
                minimum_docs_per_leaf=1000,
                number_of_trees=20,
                learning_rate=0.1,
                max_bins=1023,
                feature_fraction=1,
                slim_data=True
            )
            
            m23 = M.trade.v4(
                instruments=m9.data,
                options_data=m12.predictions,
                start_date='',
                end_date='',
                initialize=m23_initialize_bigquant_run,
                handle_data=m23_handle_data_bigquant_run,
                prepare=m23_prepare_bigquant_run,
                volume_limit=0.025,
                order_price_field_buy='open',
                order_price_field_sell='close',
                capital_base=1000000,
                auto_cancel_non_tradable_orders=True,
                data_frequency='daily',
                price_type='后复权',
                product_type='股票',
                plot_charts=True,
                backtest_only=False,
                benchmark='000300.SHA'
            )
            
            m4 = M.StockRanker_grouptest.v3(
                input_1=m9.data,
                input_2=m12.predictions,
                input_3=m14.data,
                ret_column='shift(close_0,-22)/close_0-1',
                N=22,
                m_cached=False
            )
            
            设置测试数据集,查看训练迭代过程的NDCG
            bigcharts-data-start/{"__type":"tabs","__id":"bigchart-f0b79539df784d408c56a0c3b1037abe"}/bigcharts-data-end
            设置测试数据集,查看训练迭代过程的NDCG
            bigcharts-data-start/{"__type":"tabs","__id":"bigchart-0837fe7681f041f980ad160cba0ebcb2"}/bigcharts-data-end
            • 收益率-23.47%
            • 年化收益率-10.87%
            • 基准收益率9.66%
            • 阿尔法-0.15
            • 贝塔0.64
            • 夏普比率-0.73
            • 胜率0.39
            • 盈亏比1.1
            • 收益波动率17.74%
            • 信息比率-0.07
            • 最大回撤42.4%
            bigcharts-data-start/{"__type":"tabs","__id":"bigchart-7247a38fccdf4d34bf92650f6a931c99"}/bigcharts-data-end

            (yangziriver) #9

            发错了,后面运行的没有存盘。


            (yangziriver) #10

            还是不行啊


            (yangziriver) #11
            克隆策略

              {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nlog(market_cap_0)","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='732,-26,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1012,243,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='291,660,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='438,245,200,200'/><NodePosition Node='-222' Position='450,341,200,200'/><NodePosition Node='-231' Position='1019,373,200,200'/><NodePosition Node='-238' Position='1019,482,200,200'/><NodePosition Node='-1228' Position='949,979,200,200'/><NodePosition Node='-7106' Position='524,843,200,200'/><NodePosition Node='-7117' Position='555,95,200,200'/><NodePosition Node='-2618' Position='505,993,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":true}
              In [2]:
              # 本代码由可视化策略环境自动生成 2019年7月10日 19:22
              # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
              
              
              # 回测引擎:初始化函数,只执行一次
              def m23_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))
              
                  context.options['hold_days'] = 22
              
              # 回测引擎:每日数据处理函数,每天执行一次
              def m23_handle_data_bigquant_run(context, data):
              
                  if context.trading_day_index%context.options['hold_days'] !=0:
                      return
                  
                  # 按日期过滤得到今日的预测数据
                  ranker_prediction = context.ranker_prediction[
                        context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
                  layer = len(ranker_prediction)
                  if layer==0:
                      return
                  ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
                  ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
                  stock_to_buy = list(ranker_prediction.instrument)
                  
                  # 定期轮仓卖出
                  positions = {e.symbol: p.amount * p.last_sale_price
                               for e, p in context.portfolio.positions.items()}
                 
                  stock_to_sell = [k for k in positions if k not in stock_to_buy]
              
                  for instrument in stock_to_sell:
                      context.order_target(context.symbol(instrument), 0)
              
                  # 定期买入
                  weight = [1/len(stock_to_buy) for k in stock_to_buy]
                  #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
                  for i,instrument in enumerate(stock_to_buy):
                      context.order_target_percent(context.symbol(instrument), weight[i])
              
              # 回测引擎:准备数据,只执行一次
              def m23_prepare_bigquant_run(context):
                  pass
              
              
              m1 = M.instruments.v2(
                  start_date='2010-01-01',
                  end_date='2016-12-31',
                  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/develop/datasource/deprecated/history_data.html
              #   添加benchmark_前缀,可使用对应的benchmark数据
              # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
              
              # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
              shift(close, -22) / shift(open, -1)
              
              # 极值处理:用1%和99%分位的值做clip
              clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
              
              # 将分数映射到分类,这里使用20个分类
              all_wbins(label, 20)
              
              # 过滤掉一字涨停的情况 (设置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
              )
              
              m3 = M.input_features.v1(
                  features="""# #号开始的表示注释
              # 多个特征,每行一个,可以包含基础特征和衍生特征
              #每日换手率作为权重对每日收益率求算术平均值
              log(market_cap_0)"""
              )
              
              m6 = M.input_features.v1(
                  features_ds=m3.data,
                  features="""
              # #号开始的表示注释,注释需单独一行
              # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
              shift(close_0,-22)/close_0-1"""
              )
              
              m15 = M.general_feature_extractor.v7(
                  instruments=m1.data,
                  features=m6.data,
                  start_date='',
                  end_date='',
                  before_start_days=120
              )
              
              m16 = M.derived_feature_extractor.v3(
                  input_data=m15.data,
                  features=m6.data,
                  date_col='date',
                  instrument_col='instrument',
                  drop_na=True,
                  remove_extra_columns=False
              )
              
              m7 = M.join.v3(
                  data1=m2.data,
                  data2=m16.data,
                  on='date,instrument',
                  how='inner',
                  sort=False
              )
              
              m13 = M.dropnan.v1(
                  input_data=m7.data
              )
              
              m9 = M.instruments.v2(
                  start_date=T.live_run_param('trading_date', '2017-01-01'),
                  end_date=T.live_run_param('trading_date', '2019-06-01'),
                  market='CN_STOCK_A',
                  instrument_list='',
                  max_count=0
              )
              
              m17 = M.general_feature_extractor.v7(
                  instruments=m9.data,
                  features=m6.data,
                  start_date='',
                  end_date='',
                  before_start_days=200
              )
              
              m18 = M.derived_feature_extractor.v3(
                  input_data=m17.data,
                  features=m6.data,
                  date_col='date',
                  instrument_col='instrument',
                  drop_na=True,
                  remove_extra_columns=False
              )
              
              m14 = M.dropnan.v1(
                  input_data=m18.data
              )
              
              m12 = M.stock_ranker.v2(
                  training_ds=m13.data,
                  features=m3.data,
                  predict_ds=m14.data,
                  learning_algorithm='排序',
                  number_of_leaves=30,
                  minimum_docs_per_leaf=1000,
                  number_of_trees=20,
                  learning_rate=0.1,
                  max_bins=1023,
                  feature_fraction=1,
                  slim_data=True
              )
              
              m23 = M.trade.v4(
                  instruments=m9.data,
                  options_data=m12.predictions,
                  start_date='',
                  end_date='',
                  initialize=m23_initialize_bigquant_run,
                  handle_data=m23_handle_data_bigquant_run,
                  prepare=m23_prepare_bigquant_run,
                  volume_limit=0.025,
                  order_price_field_buy='open',
                  order_price_field_sell='close',
                  capital_base=1000000,
                  auto_cancel_non_tradable_orders=True,
                  data_frequency='daily',
                  price_type='后复权',
                  product_type='股票',
                  plot_charts=True,
                  backtest_only=False,
                  benchmark='000300.SHA'
              )
              
              m4 = M.StockRanker_grouptest.v3(
                  input_1=m9.data,
                  input_2=m12.predictions,
                  input_3=m14.data,
                  ret_column='shift(close_0,-22)/close_0-1',
                  N=22,
                  m_cached=False
              )
              
              设置测试数据集,查看训练迭代过程的NDCG
              bigcharts-data-start/{"__id":"bigchart-b476d878463145b191d7fd407a0ccc31","__type":"tabs"}/bigcharts-data-end
              • 收益率-15.55%
              • 年化收益率-7.01%
              • 基准收益率9.66%
              • 阿尔法-0.11
              • 贝塔0.5
              • 夏普比率-0.65
              • 胜率0.49
              • 盈亏比0.81
              • 收益波动率14.1%
              • 信息比率-0.05
              • 最大回撤33.85%
              bigcharts-data-start/{"__id":"bigchart-17cce4aa330c475faa647fa1d0eeb9de","__type":"tabs"}/bigcharts-data-end

              这次 应该行了

              (iQuant) #12

              目前看来,这个还不错~


              (iQuant) #15

              您好,链接打不开,直接在策略编写页面点击分享后,复制链接贴到评论区即可


              (clearyf) #16
              克隆策略

                {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-143:input_1","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-143:data_1"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nsum((close_0/shift(close_0,1)-1) * turn_0,22)/22\npe_ttm_0/market_cap_0\nfs_gross_profit_margin_0\nfs_cash_ratio_0\nclose_0/close_(77+1)\nreturn_30\nreturn_5\nfs_roa_0\nfs_gross_profit_margin_ttm_0\nfs_net_profit_margin_ttm_0\nfs_current_assets_0\nfs_current_liabilities_0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, N):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read_df().set_index('date')\n def cal(x):\n weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])\n result = np.dot(x,weights)\n return result\n df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})\n df1 = df1.merge(df.reset_index(),on=['date','instrument'])\n data_1 = DataSource.write_df(df1)\n return Outputs(data_1=data_1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'N':1\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-143","OutputType":null},{"Name":"data_2","NodeId":"-143","OutputType":null},{"Name":"data_3","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='724,-25,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1012,246,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='291,660,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='438,245,200,200'/><NodePosition Node='-222' Position='450,341,200,200'/><NodePosition Node='-231' Position='1019,373,200,200'/><NodePosition Node='-238' Position='1019,482,200,200'/><NodePosition Node='-143' Position='1013,604,200,200'/><NodePosition Node='-1228' Position='949,979,200,200'/><NodePosition Node='-7106' Position='524,843,200,200'/><NodePosition Node='-7117' Position='555,95,200,200'/><NodePosition Node='-2618' Position='505,993,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":true}
                In [2]:
                # 本代码由可视化策略环境自动生成 2019年7月13日 09:20
                # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
                
                
                # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
                def m5_run_bigquant_run(input_1, N):
                    # 示例代码如下。在这里编写您的代码
                    df=input_1.read_df().set_index('date')
                    def cal(x):
                        weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])
                        result = np.dot(x,weights)
                        return result
                    df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})
                    df1 = df1.merge(df.reset_index(),on=['date','instrument'])
                    data_1 = DataSource.write_df(df1)
                    return Outputs(data_1=data_1)
                
                
                # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
                def m5_post_run_bigquant_run(outputs):
                    return outputs
                
                # 回测引擎:初始化函数,只执行一次
                def m23_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))
                
                    context.options['hold_days'] = 22
                
                # 回测引擎:每日数据处理函数,每天执行一次
                def m23_handle_data_bigquant_run(context, data):
                
                    if context.trading_day_index%context.options['hold_days'] !=0:
                        return
                    
                    # 按日期过滤得到今日的预测数据
                    ranker_prediction = context.ranker_prediction[
                          context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
                    layer = len(ranker_prediction)
                    if layer==0:
                        return
                    ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
                    ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
                    stock_to_buy = list(ranker_prediction.instrument)
                    
                    # 定期轮仓卖出
                    positions = {e.symbol: p.amount * p.last_sale_price
                                 for e, p in context.portfolio.positions.items()}
                   
                    stock_to_sell = [k for k in positions if k not in stock_to_buy]
                
                    for instrument in stock_to_sell:
                        context.order_target(context.symbol(instrument), 0)
                
                    # 定期买入
                    weight = [1/len(stock_to_buy) for k in stock_to_buy]
                    #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
                    for i,instrument in enumerate(stock_to_buy):
                        context.order_target_percent(context.symbol(instrument), weight[i])
                
                # 回测引擎:准备数据,只执行一次
                def m23_prepare_bigquant_run(context):
                    pass
                
                
                m1 = M.instruments.v2(
                    start_date='2010-01-01',
                    end_date='2016-12-31',
                    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/develop/datasource/deprecated/history_data.html
                #   添加benchmark_前缀,可使用对应的benchmark数据
                # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
                
                # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
                shift(close, -22) / shift(open, -1)
                
                # 极值处理:用1%和99%分位的值做clip
                clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
                
                # 将分数映射到分类,这里使用20个分类
                all_wbins(label, 20)
                
                # 过滤掉一字涨停的情况 (设置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
                )
                
                m3 = M.input_features.v1(
                    features="""# #号开始的表示注释
                # 多个特征,每行一个,可以包含基础特征和衍生特征
                #每日换手率作为权重对每日收益率求算术平均值
                sum((close_0/shift(close_0,1)-1) * turn_0,22)/22
                pe_ttm_0/market_cap_0
                fs_gross_profit_margin_0
                fs_cash_ratio_0
                close_0/close_(77+1)
                return_30
                return_5
                fs_roa_0
                fs_gross_profit_margin_ttm_0
                fs_net_profit_margin_ttm_0
                fs_current_assets_0
                fs_current_liabilities_0"""
                )
                
                m6 = M.input_features.v1(
                    features_ds=m3.data,
                    features="""
                # #号开始的表示注释,注释需单独一行
                # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
                shift(close_0,-22)/close_0-1"""
                )
                
                m15 = M.general_feature_extractor.v7(
                    instruments=m1.data,
                    features=m6.data,
                    start_date='',
                    end_date='',
                    before_start_days=120
                )
                
                m16 = M.derived_feature_extractor.v3(
                    input_data=m15.data,
                    features=m6.data,
                    date_col='date',
                    instrument_col='instrument',
                    drop_na=True,
                    remove_extra_columns=False
                )
                
                m7 = M.join.v3(
                    data1=m2.data,
                    data2=m16.data,
                    on='date,instrument',
                    how='inner',
                    sort=False
                )
                
                m13 = M.dropnan.v1(
                    input_data=m7.data
                )
                
                m9 = M.instruments.v2(
                    start_date=T.live_run_param('trading_date', '2017-01-01'),
                    end_date=T.live_run_param('trading_date', '2019-06-01'),
                    market='CN_STOCK_A',
                    instrument_list='',
                    max_count=0
                )
                
                m17 = M.general_feature_extractor.v7(
                    instruments=m9.data,
                    features=m6.data,
                    start_date='',
                    end_date='',
                    before_start_days=200
                )
                
                m18 = M.derived_feature_extractor.v3(
                    input_data=m17.data,
                    features=m6.data,
                    date_col='date',
                    instrument_col='instrument',
                    drop_na=True,
                    remove_extra_columns=False
                )
                
                m5 = M.cached.v3(
                    input_1=m18.data,
                    run=m5_run_bigquant_run,
                    post_run=m5_post_run_bigquant_run,
                    input_ports='',
                    params="""{
                    'N':1
                }""",
                    output_ports=''
                )
                
                m14 = M.dropnan.v1(
                    input_data=m5.data_1
                )
                
                m12 = M.stock_ranker.v2(
                    training_ds=m13.data,
                    features=m3.data,
                    predict_ds=m14.data,
                    learning_algorithm='排序',
                    number_of_leaves=30,
                    minimum_docs_per_leaf=1000,
                    number_of_trees=20,
                    learning_rate=0.1,
                    max_bins=1023,
                    feature_fraction=1,
                    slim_data=True
                )
                
                m23 = M.trade.v4(
                    instruments=m9.data,
                    options_data=m12.predictions,
                    start_date='',
                    end_date='',
                    initialize=m23_initialize_bigquant_run,
                    handle_data=m23_handle_data_bigquant_run,
                    prepare=m23_prepare_bigquant_run,
                    volume_limit=0.025,
                    order_price_field_buy='open',
                    order_price_field_sell='close',
                    capital_base=1000000,
                    auto_cancel_non_tradable_orders=True,
                    data_frequency='daily',
                    price_type='后复权',
                    product_type='股票',
                    plot_charts=True,
                    backtest_only=False,
                    benchmark='000300.SHA'
                )
                
                m4 = M.StockRanker_grouptest.v3(
                    input_1=m9.data,
                    input_2=m12.predictions,
                    input_3=m14.data,
                    ret_column='shift(close_0,-22)/close_0-1',
                    N=22,
                    m_cached=False
                )
                
                设置测试数据集,查看训练迭代过程的NDCG
                bigcharts-data-start/{"__id":"bigchart-6f3adb579888437fa356ed02f107b6f5","__type":"tabs"}/bigcharts-data-end
                设置测试数据集,查看训练迭代过程的NDCG
                bigcharts-data-start/{"__id":"bigchart-184c5390334246d1997edda740b7278b","__type":"tabs"}/bigcharts-data-end
                • 收益率-18.69%
                • 年化收益率-8.51%
                • 基准收益率9.66%
                • 阿尔法-0.12
                • 贝塔0.46
                • 夏普比率-0.86
                • 胜率0.46
                • 盈亏比0.79
                • 收益波动率12.86%
                • 信息比率-0.06
                • 最大回撤34.14%
                bigcharts-data-start/{"__id":"bigchart-4b7b5fc80fc94cef8ec5c3cffee2f1f6","__type":"tabs"}/bigcharts-data-end

                (mlzhang) #17
                克隆策略

                  {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-143:input_1","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-143:data_1"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nsum((close_0/shift(close_0,1)-1) * turn_0,22)/22\nreturn_5\nreturn_10\nreturn_20\n# avg_amount_0/avg_amount_5\n# avg_amount_5/avg_amount_20\n# rank_avg_amount_0/rank_avg_amount_5\n# rank_avg_amount_5/rank_avg_amount_10\n# rank_return_0\n# rank_return_5\nrank_return_10\n# rank_return_0/rank_return_5\n# rank_return_5/rank_return_10\n# pe_ttm_0\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"120","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"200","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, N):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read_df().set_index('date')\n def cal(x):\n weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])\n result = np.dot(x,weights)\n return result\n df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})\n df1 = df1.merge(df.reset_index(),on=['date','instrument'])\n data_1 = DataSource.write_df(df1)\n return Outputs(data_1=data_1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'N':1\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-143","OutputType":null},{"Name":"data_2","NodeId":"-143","OutputType":null},{"Name":"data_3","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1\n\n#估值因子\nfs_net_profit_ttm_0/market_cap_0 # EP\n# fs_deducted_profit_ttm_0/market_cap_0 # EPCUT\n# fs_net_cash_flow_ttm_0/market_cap_0 # NCFP\n# fs_net_cash_flow_0/market_cap_0 # OCFP\n# fs_free_cash_flow_0/market_cap_0 # FCFP","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='723,-25,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1012,246,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='291,660,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='438,245,200,200'/><NodePosition Node='-222' Position='450,341,200,200'/><NodePosition Node='-231' Position='1019,373,200,200'/><NodePosition Node='-238' Position='1019,482,200,200'/><NodePosition Node='-143' Position='1013,604,200,200'/><NodePosition Node='-1228' Position='949,979,200,200'/><NodePosition Node='-7106' Position='524,843,200,200'/><NodePosition Node='-7117' Position='555,95,200,200'/><NodePosition Node='-2618' Position='505,993,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":true}
                  In [4]:
                  # 本代码由可视化策略环境自动生成 2019年7月13日 09:53
                  # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
                  
                  
                  # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
                  def m5_run_bigquant_run(input_1, N):
                      # 示例代码如下。在这里编写您的代码
                      df=input_1.read_df().set_index('date')
                      def cal(x):
                          weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])
                          result = np.dot(x,weights)
                          return result
                      df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})
                      df1 = df1.merge(df.reset_index(),on=['date','instrument'])
                      data_1 = DataSource.write_df(df1)
                      return Outputs(data_1=data_1)
                  
                  
                  # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
                  def m5_post_run_bigquant_run(outputs):
                      return outputs
                  
                  # 回测引擎:初始化函数,只执行一次
                  def m23_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))
                  
                      context.options['hold_days'] = 22
                  
                  # 回测引擎:每日数据处理函数,每天执行一次
                  def m23_handle_data_bigquant_run(context, data):
                  
                      if context.trading_day_index%context.options['hold_days'] !=0:
                          return
                      
                      # 按日期过滤得到今日的预测数据
                      ranker_prediction = context.ranker_prediction[
                            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
                      layer = len(ranker_prediction)
                      if layer==0:
                          return
                      ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
                      ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
                      stock_to_buy = list(ranker_prediction.instrument)
                      
                      # 定期轮仓卖出
                      positions = {e.symbol: p.amount * p.last_sale_price
                                   for e, p in context.portfolio.positions.items()}
                     
                      stock_to_sell = [k for k in positions if k not in stock_to_buy]
                  
                      for instrument in stock_to_sell:
                          context.order_target(context.symbol(instrument), 0)
                  
                      # 定期买入
                      weight = [1/len(stock_to_buy) for k in stock_to_buy]
                      #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
                      for i,instrument in enumerate(stock_to_buy):
                          context.order_target_percent(context.symbol(instrument), weight[i])
                  
                  # 回测引擎:准备数据,只执行一次
                  def m23_prepare_bigquant_run(context):
                      pass
                  
                  
                  m1 = M.instruments.v2(
                      start_date='2010-01-01',
                      end_date='2016-12-31',
                      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/develop/datasource/deprecated/history_data.html
                  #   添加benchmark_前缀,可使用对应的benchmark数据
                  # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
                  
                  # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
                  shift(close, -22) / shift(open, -1)
                  
                  # 极值处理:用1%和99%分位的值做clip
                  clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
                  
                  # 将分数映射到分类,这里使用20个分类
                  all_wbins(label, 20)
                  
                  # 过滤掉一字涨停的情况 (设置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
                  )
                  
                  m3 = M.input_features.v1(
                      features="""# #号开始的表示注释
                  # 多个特征,每行一个,可以包含基础特征和衍生特征
                  #每日换手率作为权重对每日收益率求算术平均值
                  sum((close_0/shift(close_0,1)-1) * turn_0,22)/22
                  return_5
                  return_10
                  return_20
                  # avg_amount_0/avg_amount_5
                  # avg_amount_5/avg_amount_20
                  # 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
                  # pe_ttm_0
                  """
                  )
                  
                  m6 = M.input_features.v1(
                      features_ds=m3.data,
                      features="""
                  # #号开始的表示注释,注释需单独一行
                  # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
                  shift(close_0,-22)/close_0-1
                  
                  #估值因子
                  fs_net_profit_ttm_0/market_cap_0  # EP
                  # fs_deducted_profit_ttm_0/market_cap_0  # EPCUT
                  # fs_net_cash_flow_ttm_0/market_cap_0  # NCFP
                  # fs_net_cash_flow_0/market_cap_0  # OCFP
                  # fs_free_cash_flow_0/market_cap_0  # FCFP"""
                  )
                  
                  m15 = M.general_feature_extractor.v7(
                      instruments=m1.data,
                      features=m6.data,
                      start_date='',
                      end_date='',
                      before_start_days=120
                  )
                  
                  m16 = M.derived_feature_extractor.v3(
                      input_data=m15.data,
                      features=m6.data,
                      date_col='date',
                      instrument_col='instrument',
                      drop_na=True,
                      remove_extra_columns=False
                  )
                  
                  m7 = M.join.v3(
                      data1=m2.data,
                      data2=m16.data,
                      on='date,instrument',
                      how='inner',
                      sort=False
                  )
                  
                  m13 = M.dropnan.v1(
                      input_data=m7.data
                  )
                  
                  m9 = M.instruments.v2(
                      start_date=T.live_run_param('trading_date', '2017-01-01'),
                      end_date=T.live_run_param('trading_date', '2019-06-01'),
                      market='CN_STOCK_A',
                      instrument_list='',
                      max_count=0
                  )
                  
                  m17 = M.general_feature_extractor.v7(
                      instruments=m9.data,
                      features=m6.data,
                      start_date='',
                      end_date='',
                      before_start_days=200
                  )
                  
                  m18 = M.derived_feature_extractor.v3(
                      input_data=m17.data,
                      features=m6.data,
                      date_col='date',
                      instrument_col='instrument',
                      drop_na=True,
                      remove_extra_columns=False
                  )
                  
                  m5 = M.cached.v3(
                      input_1=m18.data,
                      run=m5_run_bigquant_run,
                      post_run=m5_post_run_bigquant_run,
                      input_ports='',
                      params="""{
                      'N':1
                  }""",
                      output_ports=''
                  )
                  
                  m14 = M.dropnan.v1(
                      input_data=m5.data_1
                  )
                  
                  m12 = M.stock_ranker.v2(
                      training_ds=m13.data,
                      features=m3.data,
                      predict_ds=m14.data,
                      learning_algorithm='排序',
                      number_of_leaves=30,
                      minimum_docs_per_leaf=1000,
                      number_of_trees=20,
                      learning_rate=0.1,
                      max_bins=1023,
                      feature_fraction=1,
                      slim_data=True
                  )
                  
                  m23 = M.trade.v4(
                      instruments=m9.data,
                      options_data=m12.predictions,
                      start_date='',
                      end_date='',
                      initialize=m23_initialize_bigquant_run,
                      handle_data=m23_handle_data_bigquant_run,
                      prepare=m23_prepare_bigquant_run,
                      volume_limit=0.025,
                      order_price_field_buy='open',
                      order_price_field_sell='close',
                      capital_base=1000000,
                      auto_cancel_non_tradable_orders=True,
                      data_frequency='daily',
                      price_type='后复权',
                      product_type='股票',
                      plot_charts=True,
                      backtest_only=False,
                      benchmark='000300.SHA'
                  )
                  
                  m4 = M.StockRanker_grouptest.v3(
                      input_1=m9.data,
                      input_2=m12.predictions,
                      input_3=m14.data,
                      ret_column='shift(close_0,-22)/close_0-1',
                      N=22,
                      m_cached=False
                  )
                  
                  设置测试数据集,查看训练迭代过程的NDCG
                  bigcharts-data-start/{"__id":"bigchart-3e580eed09994abeb0df726e68d37ab3","__type":"tabs"}/bigcharts-data-end
                  设置测试数据集,查看训练迭代过程的NDCG
                  bigcharts-data-start/{"__id":"bigchart-f05034cf481b4115bff9b5d3b8d4cd10","__type":"tabs"}/bigcharts-data-end
                  • 收益率-17.13%
                  • 年化收益率-7.76%
                  • 基准收益率9.66%
                  • 阿尔法-0.11
                  • 贝塔0.64
                  • 夏普比率-0.58
                  • 胜率0.45
                  • 盈亏比1.14
                  • 收益波动率16.73%
                  • 信息比率-0.06
                  • 最大回撤33.64%
                  bigcharts-data-start/{"__id":"bigchart-4a698c1aa6f4434bbbfe252a930aef5f","__type":"tabs"}/bigcharts-data-end

                  (muhai123) #18
                  克隆策略

                    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-7117:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-7106:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-231:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-1228:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-2618:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-7106:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-7106:predict_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-2618:input_3","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-222:data"},{"DestinationInputPortId":"-238:input_data","SourceOutputPortId":"-231:data"},{"DestinationInputPortId":"-143:input_1","SourceOutputPortId":"-238:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-143:data_1"},{"DestinationInputPortId":"-1228:options_data","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-2618:input_2","SourceOutputPortId":"-7106:predictions"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-231:features","SourceOutputPortId":"-7117:data"},{"DestinationInputPortId":"-238:features","SourceOutputPortId":"-7117:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-12-31","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -22) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\n#每日换手率作为权重对每日收益率求算术平均值\nsum((close_0/shift(close_0,1)-1) * turn_0,22)/22\npe_ttm_0/market_cap_0\nfs_gross_profit_margin_0\nfs_cash_ratio_0\nclose_0/close_(77+1)\nreturn_27\nreturn_30\nreturn_5\nfs_roa_0\nfs_gross_profit_margin_ttm_0\nfs_net_profit_margin_ttm_0\nfs_current_assets_0\nfs_current_liabilities_0\nfs_net_profit_margin_ttm_0\nfs_operating_revenue_0/market_cap_0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"360","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-231","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"360","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-231"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-231"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-231","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-238","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-238"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-238"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-238","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-143","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, N):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read_df().set_index('date')\n def cal(x):\n weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])\n result = np.dot(x,weights)\n return result\n df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})\n df1 = df1.merge(df.reset_index(),on=['date','instrument'])\n data_1 = DataSource.write_df(df1)\n return Outputs(data_1=data_1)\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'N':1\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-143","OutputType":null},{"Name":"data_2","NodeId":"-143","OutputType":null},{"Name":"data_3","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1228","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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\n context.options['hold_days'] = 22\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n if context.trading_day_index%context.options['hold_days'] !=0:\n return\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n layer = len(ranker_prediction)\n if layer==0:\n return\n ranker_prediction[\"组合\"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])\n ranker_prediction = ranker_prediction[ranker_prediction[\"组合\"]==1]\n stock_to_buy = list(ranker_prediction.instrument)\n \n # 定期轮仓卖出\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n stock_to_sell = [k for k in positions if k not in stock_to_buy]\n\n for instrument in stock_to_sell:\n context.order_target(context.symbol(instrument), 0)\n\n # 定期买入\n weight = [1/len(stock_to_buy) for k in stock_to_buy]\n #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])\n for i,instrument in enumerate(stock_to_buy):\n context.order_target_percent(context.symbol(instrument), weight[i])\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","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":"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":"product_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":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1228"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1228","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"第一组股票轮仓回测结果","CommentCollapsed":false},{"Id":"-7106","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"30","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-7106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-7106"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-7106","OutputType":null},{"Name":"predictions","NodeId":"-7106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-7117","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nshift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-7117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-7117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2618","ModuleId":"BigQuantSpace.StockRanker_grouptest.StockRanker_grouptest-v3","ModuleParameters":[{"Name":"ret_column","Value":"shift(close_0,-22)/close_0-1","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"N","Value":"22","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-2618"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-2618"}],"OutputPortsInternal":[],"UsePreviousResults":false,"moduleIdForCode":4,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='246,85,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='48,342,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='725,-26,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='317,487,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1012,246,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='291,660,200,200'/><NodePosition Node='-86' Position='1023,748,200,200'/><NodePosition Node='-215' Position='439.0029296875,243.9970703125,200,200'/><NodePosition Node='-222' Position='451.0029296875,341,200,200'/><NodePosition Node='-231' Position='1019,373,200,200'/><NodePosition Node='-238' Position='1019,482,200,200'/><NodePosition Node='-143' Position='1013,604,200,200'/><NodePosition Node='-1228' Position='949,979,200,200'/><NodePosition Node='-7106' Position='524,843,200,200'/><NodePosition Node='-7117' Position='555,95,200,200'/><NodePosition Node='-2618' Position='505,993,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":true}
                    In [5]:
                    # 本代码由可视化策略环境自动生成 2019年7月13日 11:10
                    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
                    
                    
                    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
                    def m5_run_bigquant_run(input_1, N):
                        # 示例代码如下。在这里编写您的代码
                        df=input_1.read_df().set_index('date')
                        def cal(x):
                            weights = np.array([ np.exp(-1*j/N/4) for j in range(N*22)])
                            result = np.dot(x,weights)
                            return result
                        df1 = df.groupby('instrument').rolling(N*22)['turn_0'].apply(cal).reset_index().rename(columns={'turn_0':'exp_wgt_return_'+str(N)+'m'})
                        df1 = df1.merge(df.reset_index(),on=['date','instrument'])
                        data_1 = DataSource.write_df(df1)
                        return Outputs(data_1=data_1)
                    
                    
                    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
                    def m5_post_run_bigquant_run(outputs):
                        return outputs
                    
                    # 回测引擎:初始化函数,只执行一次
                    def m23_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))
                    
                        context.options['hold_days'] = 22
                    
                    # 回测引擎:每日数据处理函数,每天执行一次
                    def m23_handle_data_bigquant_run(context, data):
                    
                        if context.trading_day_index%context.options['hold_days'] !=0:
                            return
                        
                        # 按日期过滤得到今日的预测数据
                        ranker_prediction = context.ranker_prediction[
                              context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
                        layer = len(ranker_prediction)
                        if layer==0:
                            return
                        ranker_prediction["组合"] = pd.cut(ranker_prediction['position'],bins=[0,layer/5,2*layer/5,3*layer/5,4*layer/5,layer],labels=[1,2,3,4,5])
                        ranker_prediction = ranker_prediction[ranker_prediction["组合"]==1]
                        stock_to_buy = list(ranker_prediction.instrument)
                        
                        # 定期轮仓卖出
                        positions = {e.symbol: p.amount * p.last_sale_price
                                     for e, p in context.portfolio.positions.items()}
                       
                        stock_to_sell = [k for k in positions if k not in stock_to_buy]
                    
                        for instrument in stock_to_sell:
                            context.order_target(context.symbol(instrument), 0)
                    
                        # 定期买入
                        weight = [1/len(stock_to_buy) for k in stock_to_buy]
                        #非等仓位权重可以设置 weight = T.norm([1 / math.log(i + 2) for i in range(len(stock_to_buy))])
                        for i,instrument in enumerate(stock_to_buy):
                            context.order_target_percent(context.symbol(instrument), weight[i])
                    
                    # 回测引擎:准备数据,只执行一次
                    def m23_prepare_bigquant_run(context):
                        pass
                    
                    
                    m1 = M.instruments.v2(
                        start_date='2010-01-01',
                        end_date='2016-12-31',
                        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/develop/datasource/deprecated/history_data.html
                    #   添加benchmark_前缀,可使用对应的benchmark数据
                    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
                    
                    # 计算收益:22日前收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
                    shift(close, -22) / shift(open, -1)
                    
                    # 极值处理:用1%和99%分位的值做clip
                    clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
                    
                    # 将分数映射到分类,这里使用20个分类
                    all_wbins(label, 20)
                    
                    # 过滤掉一字涨停的情况 (设置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
                    )
                    
                    m3 = M.input_features.v1(
                        features="""# #号开始的表示注释
                    # 多个特征,每行一个,可以包含基础特征和衍生特征
                    #每日换手率作为权重对每日收益率求算术平均值
                    sum((close_0/shift(close_0,1)-1) * turn_0,22)/22
                    pe_ttm_0/market_cap_0
                    fs_gross_profit_margin_0
                    fs_cash_ratio_0
                    close_0/close_(77+1)
                    return_27
                    return_30
                    return_5
                    fs_roa_0
                    fs_gross_profit_margin_ttm_0
                    fs_net_profit_margin_ttm_0
                    fs_current_assets_0
                    fs_current_liabilities_0
                    fs_net_profit_margin_ttm_0
                    fs_operating_revenue_0/market_cap_0"""
                    )
                    
                    m6 = M.input_features.v1(
                        features_ds=m3.data,
                        features="""
                    # #号开始的表示注释,注释需单独一行
                    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
                    shift(close_0,-22)/close_0-1"""
                    )
                    
                    m15 = M.general_feature_extractor.v7(
                        instruments=m1.data,
                        features=m6.data,
                        start_date='',
                        end_date='',
                        before_start_days=360
                    )
                    
                    m16 = M.derived_feature_extractor.v3(
                        input_data=m15.data,
                        features=m6.data,
                        date_col='date',
                        instrument_col='instrument',
                        drop_na=True,
                        remove_extra_columns=False
                    )
                    
                    m7 = M.join.v3(
                        data1=m2.data,
                        data2=m16.data,
                        on='date,instrument',
                        how='inner',
                        sort=False
                    )
                    
                    m13 = M.dropnan.v1(
                        input_data=m7.data
                    )
                    
                    m9 = M.instruments.v2(
                        start_date=T.live_run_param('trading_date', '2017-01-01'),
                        end_date=T.live_run_param('trading_date', '2019-06-01'),
                        market='CN_STOCK_A',
                        instrument_list='',
                        max_count=0
                    )
                    
                    m17 = M.general_feature_extractor.v7(
                        instruments=m9.data,
                        features=m6.data,
                        start_date='',
                        end_date='',
                        before_start_days=360
                    )
                    
                    m18 = M.derived_feature_extractor.v3(
                        input_data=m17.data,
                        features=m6.data,
                        date_col='date',
                        instrument_col='instrument',
                        drop_na=True,
                        remove_extra_columns=False
                    )
                    
                    m5 = M.cached.v3(
                        input_1=m18.data,
                        run=m5_run_bigquant_run,
                        post_run=m5_post_run_bigquant_run,
                        input_ports='',
                        params="""{
                        'N':1
                    }""",
                        output_ports=''
                    )
                    
                    m14 = M.dropnan.v1(
                        input_data=m5.data_1
                    )
                    
                    m12 = M.stock_ranker.v2(
                        training_ds=m13.data,
                        features=m3.data,
                        predict_ds=m14.data,
                        learning_algorithm='排序',
                        number_of_leaves=30,
                        minimum_docs_per_leaf=1000,
                        number_of_trees=20,
                        learning_rate=0.1,
                        max_bins=1023,
                        feature_fraction=1,
                        slim_data=True
                    )
                    
                    m23 = M.trade.v4(
                        instruments=m9.data,
                        options_data=m12.predictions,
                        start_date='',
                        end_date='',
                        initialize=m23_initialize_bigquant_run,
                        handle_data=m23_handle_data_bigquant_run,
                        prepare=m23_prepare_bigquant_run,
                        volume_limit=0.025,
                        order_price_field_buy='open',
                        order_price_field_sell='close',
                        capital_base=1000000,
                        auto_cancel_non_tradable_orders=True,
                        data_frequency='daily',
                        price_type='后复权',
                        product_type='股票',
                        plot_charts=True,
                        backtest_only=False,
                        benchmark='000300.SHA'
                    )
                    
                    m4 = M.StockRanker_grouptest.v3(
                        input_1=m9.data,
                        input_2=m12.predictions,
                        input_3=m14.data,
                        ret_column='shift(close_0,-22)/close_0-1',
                        N=22,
                        m_cached=False
                    )
                    
                    设置测试数据集,查看训练迭代过程的NDCG
                    bigcharts-data-start/{"__id":"bigchart-4c65a7d8394d4cf0b155d5944991f1f0","__type":"tabs"}/bigcharts-data-end
                    • 收益率-18.91%
                    • 年化收益率-8.62%
                    • 基准收益率9.66%
                    • 阿尔法-0.12
                    • 贝塔0.45
                    • 夏普比率-0.87
                    • 胜率0.47
                    • 盈亏比0.7
                    • 收益波动率12.87%
                    • 信息比率-0.06
                    • 最大回撤34.66%
                    bigcharts-data-start/{"__id":"bigchart-ef290fdbc55a47179e07bf4977877185","__type":"tabs"}/bigcharts-data-end

                    (Fengshu) #20

                    发错了 帮我删一下 我重新发 谢谢


                    (Fengshu) #21

                    https://i.bigquant.com/user/fengshu/lab/share/策略模板_上传.ipynb


                    #22

                    还可以多试试其他类因子组合,比如财务因子和估值因子等


                    #23

                    还可以多试试其他类因子组合,比如财务因子和估值因子等


                    #24

                    选手请尽量选择给定研报里面的因子哦


                    #26

                    这篇策略中前八个月都没有持仓记录,可以找一下原因。