自定义运行功能模块的疑问

机器学习
标签: #<Tag:0x00007f49213c0318>

(youmin) #1

各位大佬好,咨询个问题,我跟着视频学习自定义模块的时候,自己做了个学习用例,如m5。思路很简单,把m9代码列表的开始时间和结束时间依次用2015年~2020年,每年跑一次策略。
核心代码如下

for i in range(len(start_dates)):
        parameters = {}
        parameters['m9.start_date'] = start_dates[i]
        parameters['m9.end_date'] = end_dates[i]
        parameters_list.append({'parameters': parameters})
        print(parameters)

但是报错了,报错提示很诡异,就说“m9”【请见日志】。

[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
{'m9.start_date': '2015-01-01', 'm9.end_date': '2015-12-31'}
ERROR -------- 'm9'

麻烦有经验的大佬给看看,是不是哪里写错了,感谢

克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-339: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":"-339:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-346:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-355:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-362:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-1494:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-240:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-374:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"-355:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-374:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-346:input_data","SourceOutputPortId":"-339:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-346:data"},{"DestinationInputPortId":"-362:input_data","SourceOutputPortId":"-355:data"},{"DestinationInputPortId":"-244:input_data","SourceOutputPortId":"-362:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"-1494:model"},{"DestinationInputPortId":"-1494:training_ds","SourceOutputPortId":"-240:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-244: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":"2014-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/data_history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_\n\n# 计算收益:后天收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -2) / 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":"close_0/mean(close_0,5)","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-60","ModuleId":"BigQuantSpace.stock_ranker_predict.stock_ranker_predict-v5","ModuleParameters":[{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2020-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2020-07-15","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":"-339","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":"50","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-339"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-339"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-339","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-346","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":"False","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":"-346"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-346"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-346","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-355","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":"50","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-355"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-355"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-355","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-362","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":"False","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":"-362"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-362"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-362","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-374","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 # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n context.stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, context.stock_count)])\n context.stock_weights = [0.5,0.5] #半仓买入,每只股票等资金分配\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.5\n context.options['hold_days'] = 2\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n \n # 当日可用资金\n cash_for_buy = context.portfolio.cash\n \n # 获取当日买入列表,每天选取context.stock_count只\n buy_list = list(ranker_prediction.instrument[:context.stock_count])\n \n # 获取当前持仓\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()} \n\n # 需要卖出的股票:已有持仓中不在买入列表的股票\n stock_to_sell = [ i for i in stock_hold_now if i not in buy_list ]\n stock_to_buy = [ i for i in buy_list if i not in stock_hold_now ]\n \n # 卖出列表进行卖出操作\n if len(stock_to_sell)>0:\n for instrument in stock_to_sell:\n sid = context.symbol(instrument) # 将标的转化为equity格式\n cur_position = context.portfolio.positions[sid].amount # 持仓\n if cur_position > 0 and data.can_trade(sid):\n context.order_target_percent(sid, 0) # 全部卖出\n # 如果是早盘买早盘卖,卖出的资金可以用于买股票,此时应将下面的注释打开,卖出股票时更新可用现金;\n # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用\n #cash_for_buy += stock_hold_now[instrument]\n \n # 买入列表执行买操作\n if len(stock_to_buy)>0:\n for instrument,weight in zip(stock_to_buy,context.stock_weights):\n sid = context.symbol(instrument) # 将标的转化为equity格式\n if data.can_trade(sid):\n context.order_target_value(sid, min(cash_for_buy,context.portfolio.portfolio_value*0.5)) # 买入","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":"100000","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":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-374"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-374"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-374"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-374"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-374"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-374","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1494","ModuleId":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v6","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":"data_row_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ndcg_discount_base","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-1494"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1494"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-1494"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-1494"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-1494","OutputType":null},{"Name":"feature_gains","NodeId":"-1494","OutputType":null},{"Name":"m_lazy_run","NodeId":"-1494","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-240","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-240"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-240"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-240","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-244","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-244"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-244"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-244","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-4932","ModuleId":"BigQuantSpace.hyper_run.hyper_run-v1","ModuleParameters":[{"Name":"run","Value":"def bigquant_run(bq_graph, inputs):\n g = bq_graph\n\n start_dates =['2015-01-01','2016-01-01','2017-01-01','2018-01-01', '2019-01-01', '2020-01-01']\n# end_dates =[T.live_run_param('trading_date', '2015-12-31'),T.live_run_param('trading_date', '2016-12-31'),T.live_run_param('trading_date', '2017-12-31'),T.live_run_param('trading_date', '2018-12-31'),T.live_run_param('trading_date', '2019-12-31'),T.live_run_param('trading_date', '2020-07-31')]\n end_dates =['2015-12-31','2016-12-31','2017-12-31','2018-12-31', '2019-12-31', '2020-07-31']\n\n parameters_list = []\n \n for i in range(len(start_dates)):\n parameters = {}\n parameters['m9.start_date'] = start_dates[i]\n parameters['m9.end_date'] = end_dates[i]\n parameters_list.append({'parameters': parameters})\n print(parameters)\n \n def run(parameters):\n try:\n print(parameters)\n return g.run(parameters)\n except Exception as e:\n print('ERROR --------', e)\n return None\n \n results = T.parallel_map(run, parameters_list, max_workers=1, remote_run=False)\n\n return results\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"run_now","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"bq_graph","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"bq_graph_port","NodeId":"-4932"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-4932"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-4932"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-4932"}],"OutputPortsInternal":[{"Name":"result","NodeId":"-4932","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":5,"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='211,64,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='70,183,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='765,16,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='906,666,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1078,136,200,200'/><NodePosition Node='-339' Position='381,188,200,200'/><NodePosition Node='-346' Position='385,280,200,200'/><NodePosition Node='-355' Position='1078,236,200,200'/><NodePosition Node='-362' Position='1081,327,200,200'/><NodePosition Node='-374' Position='757,749,200,200'/><NodePosition Node='-1494' Position='608,597,200,200'/><NodePosition Node='-240' Position='324,456,200,200'/><NodePosition Node='-244' Position='1078,418,200,200'/><NodePosition Node='-4932' Position='87,-46,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 [8]:
    # 本代码由可视化策略环境自动生成 2020年8月26日 15:21
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m19_initialize_bigquant_run(context):
        # 加载预测数据
        context.ranker_prediction = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
        # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        context.stock_count = 5
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, context.stock_count)])
        context.stock_weights = [0.5,0.5]  #半仓买入,每只股票等资金分配
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 0.5
        context.options['hold_days'] = 2
    
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_handle_data_bigquant_run(context, data):
        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
        
        # 当日可用资金
        cash_for_buy = context.portfolio.cash
        
        # 获取当日买入列表,每天选取context.stock_count只
        buy_list = list(ranker_prediction.instrument[:context.stock_count])
        
        # 获取当前持仓
        stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                          for e, p in context.perf_tracker.position_tracker.positions.items()} 
    
        # 需要卖出的股票:已有持仓中不在买入列表的股票
        stock_to_sell = [ i for i in stock_hold_now if i not in buy_list ]
        stock_to_buy =  [ i for i in buy_list if i not in stock_hold_now ]
        
        # 卖出列表进行卖出操作
        if len(stock_to_sell)>0:
            for instrument in stock_to_sell:
                sid = context.symbol(instrument) # 将标的转化为equity格式
                cur_position = context.portfolio.positions[sid].amount # 持仓
                if cur_position > 0 and data.can_trade(sid):
                    context.order_target_percent(sid, 0) # 全部卖出
                    # 如果是早盘买早盘卖,卖出的资金可以用于买股票,此时应将下面的注释打开,卖出股票时更新可用现金;
                    # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用
                    #cash_for_buy += stock_hold_now[instrument]
        
        # 买入列表执行买操作
        if len(stock_to_buy)>0:
            for instrument,weight in zip(stock_to_buy,context.stock_weights):
                sid = context.symbol(instrument) # 将标的转化为equity格式
                if data.can_trade(sid):
                    context.order_target_value(sid, min(cash_for_buy,context.portfolio.portfolio_value*0.5)) # 买入
    # 回测引擎:准备数据,只执行一次
    def m19_prepare_bigquant_run(context):
        pass
    
    
    g = T.Graph({
    
        'm1': 'M.instruments.v2',
        'm1.start_date': '2010-01-01',
        'm1.end_date': '2014-12-31',
        'm1.market': 'CN_STOCK_A',
        'm1.instrument_list': '',
        'm1.max_count': 0,
    
        'm2': 'M.advanced_auto_labeler.v2',
        'm2.instruments': T.Graph.OutputPort('m1.data'),
        'm2.label_expr': """# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html
    #   添加benchmark_前缀,可使用对应的benchmark数据
    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_
    
    # 计算收益:后天收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    shift(close, -2) / 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)
    """,
        'm2.start_date': '',
        'm2.end_date': '',
        'm2.benchmark': '000300.SHA',
        'm2.drop_na_label': True,
        'm2.cast_label_int': True,
    
        'm3': 'M.input_features.v1',
        'm3.features': 'close_0/mean(close_0,5)',
    
        'm15': 'M.general_feature_extractor.v7',
        'm15.instruments': T.Graph.OutputPort('m1.data'),
        'm15.features': T.Graph.OutputPort('m3.data'),
        'm15.start_date': '',
        'm15.end_date': '',
        'm15.before_start_days': 50,
    
        'm16': 'M.derived_feature_extractor.v3',
        'm16.input_data': T.Graph.OutputPort('m15.data'),
        'm16.features': T.Graph.OutputPort('m3.data'),
        'm16.date_col': 'date',
        'm16.instrument_col': 'instrument',
        'm16.drop_na': False,
        'm16.remove_extra_columns': False,
    
        'm7': 'M.join.v3',
        'm7.data1': T.Graph.OutputPort('m2.data'),
        'm7.data2': T.Graph.OutputPort('m16.data'),
        'm7.on': 'date,instrument',
        'm7.how': 'inner',
        'm7.sort': False,
    
        'm6': 'M.dropnan.v2',
        'm6.input_data': T.Graph.OutputPort('m7.data'),
    
        'm4': 'M.stock_ranker_train.v6',
        'm4.training_ds': T.Graph.OutputPort('m6.data'),
        'm4.features': T.Graph.OutputPort('m3.data'),
        'm4.learning_algorithm': '排序',
        'm4.number_of_leaves': 30,
        'm4.minimum_docs_per_leaf': 1000,
        'm4.number_of_trees': 20,
        'm4.learning_rate': 0.1,
        'm4.max_bins': 1023,
        'm4.feature_fraction': 1,
        'm4.data_row_fraction': 1,
        'm4.ndcg_discount_base': 1,
        'm4.m_lazy_run': False,
    
        'm9': 'M.instruments.v2',
        'm9.start_date': T.live_run_param('trading_date', '2020-01-01'),
        'm9.end_date': T.live_run_param('trading_date', '2020-07-15'),
        'm9.market': 'CN_STOCK_A',
        'm9.instrument_list': '',
        'm9.max_count': 0,
    
        'm17': 'M.general_feature_extractor.v7',
        'm17.instruments': T.Graph.OutputPort('m9.data'),
        'm17.features': T.Graph.OutputPort('m3.data'),
        'm17.start_date': '',
        'm17.end_date': '',
        'm17.before_start_days': 50,
    
        'm18': 'M.derived_feature_extractor.v3',
        'm18.input_data': T.Graph.OutputPort('m17.data'),
        'm18.features': T.Graph.OutputPort('m3.data'),
        'm18.date_col': 'date',
        'm18.instrument_col': 'instrument',
        'm18.drop_na': False,
        'm18.remove_extra_columns': False,
    
        'm10': 'M.dropnan.v2',
        'm10.input_data': T.Graph.OutputPort('m18.data'),
    
        'm8': 'M.stock_ranker_predict.v5',
        'm8.model': T.Graph.OutputPort('m4.model'),
        'm8.data': T.Graph.OutputPort('m10.data'),
        'm8.m_lazy_run': False,
    
        'm19': 'M.trade.v4',
        'm19.instruments': T.Graph.OutputPort('m9.data'),
        'm19.options_data': T.Graph.OutputPort('m8.predictions'),
        'm19.start_date': '',
        'm19.end_date': '',
        'm19.initialize': m19_initialize_bigquant_run,
        'm19.handle_data': m19_handle_data_bigquant_run,
        'm19.prepare': m19_prepare_bigquant_run,
        'm19.volume_limit': 0.025,
        'm19.order_price_field_buy': 'open',
        'm19.order_price_field_sell': 'close',
        'm19.capital_base': 100000,
        'm19.auto_cancel_non_tradable_orders': True,
        'm19.data_frequency': 'daily',
        'm19.price_type': '后复权',
        'm19.product_type': '股票',
        'm19.plot_charts': True,
        'm19.backtest_only': False,
        'm19.benchmark': '',
    })
    
    # g.run({})
    
    
    def m5_run_bigquant_run(bq_graph, inputs):
        g = bq_graph
    
        start_dates =['2015-01-01','2016-01-01','2017-01-01','2018-01-01', '2019-01-01', '2020-01-01']
    #    end_dates =[T.live_run_param('trading_date', '2015-12-31'),T.live_run_param('trading_date', '2016-12-31'),T.live_run_param('trading_date', '2017-12-31'),T.live_run_param('trading_date', '2018-12-31'),T.live_run_param('trading_date', '2019-12-31'),T.live_run_param('trading_date', '2020-07-31')]
        end_dates =['2015-12-31','2016-12-31','2017-12-31','2018-12-31', '2019-12-31', '2020-07-31']
    
        parameters_list = []
         
        for i in range(len(start_dates)):
            parameters = {}
            parameters['m9.start_date'] = start_dates[i]
            parameters['m9.end_date'] = end_dates[i]
            parameters_list.append({'parameters': parameters})
            print(parameters)
        
        def run(parameters):
            try:
                print(parameters)
                return g.run(parameters)
            except Exception as e:
                print('ERROR --------', e)
                return None
     
        results = T.parallel_map(run, parameters_list, max_workers=1, remote_run=False)
    
        return results
    
    
    m5 = M.hyper_run.v1(
        run=m5_run_bigquant_run,
        run_now=True,
        bq_graph=g
    )
    
    {'m9.start_date': '2015-01-01', 'm9.end_date': '2015-12-31'}
    {'m9.start_date': '2016-01-01', 'm9.end_date': '2016-12-31'}
    {'m9.start_date': '2017-01-01', 'm9.end_date': '2017-12-31'}
    {'m9.start_date': '2018-01-01', 'm9.end_date': '2018-12-31'}
    {'m9.start_date': '2019-01-01', 'm9.end_date': '2019-12-31'}
    {'m9.start_date': '2020-01-01', 'm9.end_date': '2020-07-31'}
    
    [Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
    {'m9.start_date': '2015-01-01', 'm9.end_date': '2015-12-31'}
    ERROR -------- 'm9'
    [Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    0.0s remaining:    0.0s
    {'m9.start_date': '2016-01-01', 'm9.end_date': '2016-12-31'}
    ERROR -------- 'm9'
    [Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    0.0s remaining:    0.0s
    {'m9.start_date': '2017-01-01', 'm9.end_date': '2017-12-31'}
    ERROR -------- 'm9'
    [Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.0s remaining:    0.0s
    {'m9.start_date': '2018-01-01', 'm9.end_date': '2018-12-31'}
    ERROR -------- 'm9'
    [Parallel(n_jobs=1)]: Done   4 out of   4 | elapsed:    0.0s remaining:    0.0s
    {'m9.start_date': '2019-01-01', 'm9.end_date': '2019-12-31'}
    ERROR -------- 'm9'
    [Parallel(n_jobs=1)]: Done   5 out of   5 | elapsed:    0.0s remaining:    0.0s
    {'m9.start_date': '2020-01-01', 'm9.end_date': '2020-07-31'}
    ERROR -------- 'm9'
    [Parallel(n_jobs=1)]: Done   6 out of   6 | elapsed:    0.0s remaining:    0.0s
    [Parallel(n_jobs=1)]: Done   6 out of   6 | elapsed:    0.0s finished
    

    (adhaha111) #2

    您好,我这边是可以运行的,您可以尝试下重启内核

    克隆策略

      {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-339: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":"-339:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-346:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-355:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-362:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-1494:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-240:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-374:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"-355:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-374:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-346:input_data","SourceOutputPortId":"-339:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-346:data"},{"DestinationInputPortId":"-362:input_data","SourceOutputPortId":"-355:data"},{"DestinationInputPortId":"-244:input_data","SourceOutputPortId":"-362:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"-1494:model"},{"DestinationInputPortId":"-1494:training_ds","SourceOutputPortId":"-240:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-244: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":"2014-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/data_history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_\n\n# 计算收益:后天收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -2) / 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":"close_0/mean(close_0,5)","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-60","ModuleId":"BigQuantSpace.stock_ranker_predict.stock_ranker_predict-v5","ModuleParameters":[{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2020-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2020-07-15","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":"-339","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":"50","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-339"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-339"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-339","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-346","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":"False","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":"-346"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-346"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-346","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-355","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":"50","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-355"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-355"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-355","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-362","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":"False","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":"-362"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-362"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-362","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-374","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 # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n context.stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, context.stock_count)])\n context.stock_weights = [0.5,0.5] #半仓买入,每只股票等资金分配\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.5\n context.options['hold_days'] = 2\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n \n # 当日可用资金\n cash_for_buy = context.portfolio.cash\n \n # 获取当日买入列表,每天选取context.stock_count只\n buy_list = list(ranker_prediction.instrument[:context.stock_count])\n \n # 获取当前持仓\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()} \n\n # 需要卖出的股票:已有持仓中不在买入列表的股票\n stock_to_sell = [ i for i in stock_hold_now if i not in buy_list ]\n stock_to_buy = [ i for i in buy_list if i not in stock_hold_now ]\n \n # 卖出列表进行卖出操作\n if len(stock_to_sell)>0:\n for instrument in stock_to_sell:\n sid = context.symbol(instrument) # 将标的转化为equity格式\n cur_position = context.portfolio.positions[sid].amount # 持仓\n if cur_position > 0 and data.can_trade(sid):\n context.order_target_percent(sid, 0) # 全部卖出\n # 如果是早盘买早盘卖,卖出的资金可以用于买股票,此时应将下面的注释打开,卖出股票时更新可用现金;\n # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用\n #cash_for_buy += stock_hold_now[instrument]\n \n # 买入列表执行买操作\n if len(stock_to_buy)>0:\n for instrument,weight in zip(stock_to_buy,context.stock_weights):\n sid = context.symbol(instrument) # 将标的转化为equity格式\n if data.can_trade(sid):\n context.order_target_value(sid, min(cash_for_buy,context.portfolio.portfolio_value*0.5)) # 买入","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":"100000","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":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-374"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-374"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-374"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-374"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-374"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-374","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1494","ModuleId":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v6","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":"data_row_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ndcg_discount_base","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-1494"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1494"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-1494"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-1494"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-1494","OutputType":null},{"Name":"feature_gains","NodeId":"-1494","OutputType":null},{"Name":"m_lazy_run","NodeId":"-1494","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-240","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-240"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-240"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-240","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-244","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-244"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-244"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-244","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-4932","ModuleId":"BigQuantSpace.hyper_run.hyper_run-v1","ModuleParameters":[{"Name":"run","Value":"def bigquant_run(bq_graph, inputs):\n g = bq_graph\n\n start_dates =['2015-01-01','2016-01-01','2017-01-01','2018-01-01', '2019-01-01', '2020-01-01']\n# end_dates =[T.live_run_param('trading_date', '2015-12-31'),T.live_run_param('trading_date', '2016-12-31'),T.live_run_param('trading_date', '2017-12-31'),T.live_run_param('trading_date', '2018-12-31'),T.live_run_param('trading_date', '2019-12-31'),T.live_run_param('trading_date', '2020-07-31')]\n end_dates =['2015-12-31','2016-12-31','2017-12-31','2018-12-31', '2019-12-31', '2020-07-31']\n\n parameters_list = []\n \n for i in range(len(start_dates)):\n parameters = {}\n parameters['m9.start_date'] = start_dates[i]\n parameters['m9.end_date'] = end_dates[i]\n parameters_list.append({'parameters': parameters})\n print(parameters)\n \n def run(parameters):\n try:\n print(parameters)\n return g.run(parameters)\n except Exception as e:\n print('ERROR --------', e)\n return None\n \n results = T.parallel_map(run, parameters_list, max_workers=1, remote_run=False)\n\n return results\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"run_now","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"bq_graph","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"bq_graph_port","NodeId":"-4932"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-4932"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-4932"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-4932"}],"OutputPortsInternal":[{"Name":"result","NodeId":"-4932","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":5,"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='211,64,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='70,183,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='765,16,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='906,666,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1078,136,200,200'/><NodePosition Node='-339' Position='381,188,200,200'/><NodePosition Node='-346' Position='385,280,200,200'/><NodePosition Node='-355' Position='1078,236,200,200'/><NodePosition Node='-362' Position='1081,327,200,200'/><NodePosition Node='-374' Position='757,749,200,200'/><NodePosition Node='-1494' Position='608,597,200,200'/><NodePosition Node='-240' Position='324,456,200,200'/><NodePosition Node='-244' Position='1078,418,200,200'/><NodePosition Node='-4932' Position='87,-46,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]:
      # 本代码由可视化策略环境自动生成 2020年8月26日 17:53
      # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
      
      
      # 回测引擎:初始化函数,只执行一次
      def m19_initialize_bigquant_run(context):
          # 加载预测数据
          context.ranker_prediction = context.options['data'].read_df()
      
          # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
          context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
          # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
          # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
          context.stock_count = 5
          # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
          #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, context.stock_count)])
          context.stock_weights = [0.5,0.5]  #半仓买入,每只股票等资金分配
          # 设置每只股票占用的最大资金比例
          context.max_cash_per_instrument = 0.5
          context.options['hold_days'] = 2
      
      
      # 回测引擎:每日数据处理函数,每天执行一次
      def m19_handle_data_bigquant_run(context, data):
          # 按日期过滤得到今日的预测数据
          ranker_prediction = context.ranker_prediction[
              context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
          
          # 当日可用资金
          cash_for_buy = context.portfolio.cash
          
          # 获取当日买入列表,每天选取context.stock_count只
          buy_list = list(ranker_prediction.instrument[:context.stock_count])
          
          # 获取当前持仓
          stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                            for e, p in context.perf_tracker.position_tracker.positions.items()} 
      
          # 需要卖出的股票:已有持仓中不在买入列表的股票
          stock_to_sell = [ i for i in stock_hold_now if i not in buy_list ]
          stock_to_buy =  [ i for i in buy_list if i not in stock_hold_now ]
          
          # 卖出列表进行卖出操作
          if len(stock_to_sell)>0:
              for instrument in stock_to_sell:
                  sid = context.symbol(instrument) # 将标的转化为equity格式
                  cur_position = context.portfolio.positions[sid].amount # 持仓
                  if cur_position > 0 and data.can_trade(sid):
                      context.order_target_percent(sid, 0) # 全部卖出
                      # 如果是早盘买早盘卖,卖出的资金可以用于买股票,此时应将下面的注释打开,卖出股票时更新可用现金;
                      # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用
                      #cash_for_buy += stock_hold_now[instrument]
          
          # 买入列表执行买操作
          if len(stock_to_buy)>0:
              for instrument,weight in zip(stock_to_buy,context.stock_weights):
                  sid = context.symbol(instrument) # 将标的转化为equity格式
                  if data.can_trade(sid):
                      context.order_target_value(sid, min(cash_for_buy,context.portfolio.portfolio_value*0.5)) # 买入
      # 回测引擎:准备数据,只执行一次
      def m19_prepare_bigquant_run(context):
          pass
      
      
      g = T.Graph({
      
          'm1': 'M.instruments.v2',
          'm1.start_date': '2010-01-01',
          'm1.end_date': '2014-12-31',
          'm1.market': 'CN_STOCK_A',
          'm1.instrument_list': '',
          'm1.max_count': 0,
      
          'm2': 'M.advanced_auto_labeler.v2',
          'm2.instruments': T.Graph.OutputPort('m1.data'),
          'm2.label_expr': """# #号开始的表示注释
      # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
      # 1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html
      #   添加benchmark_前缀,可使用对应的benchmark数据
      # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_
      
      # 计算收益:后天收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
      shift(close, -2) / 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)
      """,
          'm2.start_date': '',
          'm2.end_date': '',
          'm2.benchmark': '000300.SHA',
          'm2.drop_na_label': True,
          'm2.cast_label_int': True,
      
          'm3': 'M.input_features.v1',
          'm3.features': 'close_0/mean(close_0,5)',
      
          'm15': 'M.general_feature_extractor.v7',
          'm15.instruments': T.Graph.OutputPort('m1.data'),
          'm15.features': T.Graph.OutputPort('m3.data'),
          'm15.start_date': '',
          'm15.end_date': '',
          'm15.before_start_days': 50,
      
          'm16': 'M.derived_feature_extractor.v3',
          'm16.input_data': T.Graph.OutputPort('m15.data'),
          'm16.features': T.Graph.OutputPort('m3.data'),
          'm16.date_col': 'date',
          'm16.instrument_col': 'instrument',
          'm16.drop_na': False,
          'm16.remove_extra_columns': False,
      
          'm7': 'M.join.v3',
          'm7.data1': T.Graph.OutputPort('m2.data'),
          'm7.data2': T.Graph.OutputPort('m16.data'),
          'm7.on': 'date,instrument',
          'm7.how': 'inner',
          'm7.sort': False,
      
          'm6': 'M.dropnan.v2',
          'm6.input_data': T.Graph.OutputPort('m7.data'),
      
          'm4': 'M.stock_ranker_train.v6',
          'm4.training_ds': T.Graph.OutputPort('m6.data'),
          'm4.features': T.Graph.OutputPort('m3.data'),
          'm4.learning_algorithm': '排序',
          'm4.number_of_leaves': 30,
          'm4.minimum_docs_per_leaf': 1000,
          'm4.number_of_trees': 20,
          'm4.learning_rate': 0.1,
          'm4.max_bins': 1023,
          'm4.feature_fraction': 1,
          'm4.data_row_fraction': 1,
          'm4.ndcg_discount_base': 1,
          'm4.m_lazy_run': False,
      
          'm9': 'M.instruments.v2',
          'm9.start_date': T.live_run_param('trading_date', '2020-01-01'),
          'm9.end_date': T.live_run_param('trading_date', '2020-07-15'),
          'm9.market': 'CN_STOCK_A',
          'm9.instrument_list': '',
          'm9.max_count': 0,
      
          'm17': 'M.general_feature_extractor.v7',
          'm17.instruments': T.Graph.OutputPort('m9.data'),
          'm17.features': T.Graph.OutputPort('m3.data'),
          'm17.start_date': '',
          'm17.end_date': '',
          'm17.before_start_days': 50,
      
          'm18': 'M.derived_feature_extractor.v3',
          'm18.input_data': T.Graph.OutputPort('m17.data'),
          'm18.features': T.Graph.OutputPort('m3.data'),
          'm18.date_col': 'date',
          'm18.instrument_col': 'instrument',
          'm18.drop_na': False,
          'm18.remove_extra_columns': False,
      
          'm10': 'M.dropnan.v2',
          'm10.input_data': T.Graph.OutputPort('m18.data'),
      
          'm8': 'M.stock_ranker_predict.v5',
          'm8.model': T.Graph.OutputPort('m4.model'),
          'm8.data': T.Graph.OutputPort('m10.data'),
          'm8.m_lazy_run': False,
      
          'm19': 'M.trade.v4',
          'm19.instruments': T.Graph.OutputPort('m9.data'),
          'm19.options_data': T.Graph.OutputPort('m8.predictions'),
          'm19.start_date': '',
          'm19.end_date': '',
          'm19.initialize': m19_initialize_bigquant_run,
          'm19.handle_data': m19_handle_data_bigquant_run,
          'm19.prepare': m19_prepare_bigquant_run,
          'm19.volume_limit': 0.025,
          'm19.order_price_field_buy': 'open',
          'm19.order_price_field_sell': 'close',
          'm19.capital_base': 100000,
          'm19.auto_cancel_non_tradable_orders': True,
          'm19.data_frequency': 'daily',
          'm19.price_type': '后复权',
          'm19.product_type': '股票',
          'm19.plot_charts': True,
          'm19.backtest_only': False,
          'm19.benchmark': '',
      })
      
      # g.run({})
      
      
      def m5_run_bigquant_run(bq_graph, inputs):
          g = bq_graph
      
          start_dates =['2015-01-01','2016-01-01','2017-01-01','2018-01-01', '2019-01-01', '2020-01-01']
      #    end_dates =[T.live_run_param('trading_date', '2015-12-31'),T.live_run_param('trading_date', '2016-12-31'),T.live_run_param('trading_date', '2017-12-31'),T.live_run_param('trading_date', '2018-12-31'),T.live_run_param('trading_date', '2019-12-31'),T.live_run_param('trading_date', '2020-07-31')]
          end_dates =['2015-12-31','2016-12-31','2017-12-31','2018-12-31', '2019-12-31', '2020-07-31']
      
          parameters_list = []
           
          for i in range(len(start_dates)):
              parameters = {}
              parameters['m9.start_date'] = start_dates[i]
              parameters['m9.end_date'] = end_dates[i]
              parameters_list.append({'parameters': parameters})
              print(parameters)
          
          def run(parameters):
              try:
                  print(parameters)
                  return g.run(parameters)
              except Exception as e:
                  print('ERROR --------', e)
                  return None
       
          results = T.parallel_map(run, parameters_list, max_workers=1, remote_run=False)
      
          return results
      
      
      m5 = M.hyper_run.v1(
          run=m5_run_bigquant_run,
          run_now=True,
          bq_graph=g
      )
      
      {'m9.start_date': '2015-01-01', 'm9.end_date': '2015-12-31'}
      {'m9.start_date': '2016-01-01', 'm9.end_date': '2016-12-31'}
      {'m9.start_date': '2017-01-01', 'm9.end_date': '2017-12-31'}
      {'m9.start_date': '2018-01-01', 'm9.end_date': '2018-12-31'}
      {'m9.start_date': '2019-01-01', 'm9.end_date': '2019-12-31'}
      {'m9.start_date': '2020-01-01', 'm9.end_date': '2020-07-31'}
      
      [Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
      {'m9.start_date': '2015-01-01', 'm9.end_date': '2015-12-31'}
      
      设置评估测试数据集,查看训练曲线
      [视频教程]StockRanker训练曲线
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-534b57d300464dd09a3e04356ffafe5e"}/bigcharts-data-end
      • 收益率-29.9%
      • 年化收益率-30.72%
      • 基准收益率5.58%
      • 阿尔法-0.33
      • 贝塔0.66
      • 夏普比率-0.49
      • 胜率0.51
      • 盈亏比0.88
      • 收益波动率52.78%
      • 信息比率-0.05
      • 最大回撤57.46%
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-0781e501760f4deea626120fa9e855ba"}/bigcharts-data-end
      [Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    2.0s remaining:    0.0s
      {'m9.start_date': '2016-01-01', 'm9.end_date': '2016-12-31'}
      
      设置评估测试数据集,查看训练曲线
      [视频教程]StockRanker训练曲线
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-6d45837f69ae49cab1964fb15581c2b0"}/bigcharts-data-end
      • 收益率-52.92%
      • 年化收益率-54.07%
      • 基准收益率-11.28%
      • 阿尔法-0.57
      • 贝塔1.03
      • 夏普比率-1.49
      • 胜率0.46
      • 盈亏比0.92
      • 收益波动率46.79%
      • 信息比率-0.09
      • 最大回撤59.71%
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-f903a45a8d3c4271b43502e16135a835"}/bigcharts-data-end
      [Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    3.0s remaining:    0.0s
      {'m9.start_date': '2017-01-01', 'm9.end_date': '2017-12-31'}
      
      设置评估测试数据集,查看训练曲线
      [视频教程]StockRanker训练曲线
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-7d7adbe7341c40c2b0af766014ca7711"}/bigcharts-data-end
      • 收益率-73.37%
      • 年化收益率-74.5%
      • 基准收益率21.78%
      • 阿尔法-1.38
      • 贝塔0.37
      • 夏普比率-3.42
      • 胜率0.45
      • 盈亏比0.69
      • 收益波动率38.54%
      • 信息比率-0.24
      • 最大回撤74.94%
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-a7982c975dda4b47ab7d6b0250e3c0ee"}/bigcharts-data-end
      [Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    4.6s remaining:    0.0s
      {'m9.start_date': '2018-01-01', 'm9.end_date': '2018-12-31'}
      
      设置评估测试数据集,查看训练曲线
      [视频教程]StockRanker训练曲线
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-d739d55584b84a42aac56d588be62c13"}/bigcharts-data-end
      • 收益率-89.65%
      • 年化收益率-90.48%
      • 基准收益率-25.31%
      • 阿尔法-2.04
      • 贝塔0.78
      • 夏普比率-5.33
      • 胜率0.42
      • 盈亏比0.55
      • 收益波动率42.71%
      • 信息比率-0.31
      • 最大回撤89.87%
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-aa4039707c5f41559b99f94b6757e992"}/bigcharts-data-end
      [Parallel(n_jobs=1)]: Done   4 out of   4 | elapsed:    6.0s remaining:    0.0s
      {'m9.start_date': '2019-01-01', 'm9.end_date': '2019-12-31'}
      
      设置评估测试数据集,查看训练曲线
      [视频教程]StockRanker训练曲线
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-beedae7b0d464a309820ff24c3273725"}/bigcharts-data-end
      • 收益率-73.26%
      • 年化收益率-74.39%
      • 基准收益率36.07%
      • 阿尔法-1.5
      • 贝塔0.76
      • 夏普比率-2.59
      • 胜率0.49
      • 盈亏比0.77
      • 收益波动率48.91%
      • 信息比率-0.21
      • 最大回撤79.63%
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-303e004e34f1412da8265ebb62b77b28"}/bigcharts-data-end
      [Parallel(n_jobs=1)]: Done   5 out of   5 | elapsed:    7.6s remaining:    0.0s
      {'m9.start_date': '2020-01-01', 'm9.end_date': '2020-07-31'}
      
      设置评估测试数据集,查看训练曲线
      [视频教程]StockRanker训练曲线
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-3a5cf19921884edba92ac879db0dda40"}/bigcharts-data-end
      • 收益率-75.43%
      • 年化收益率-92.01%
      • 基准收益率14.61%
      • 阿尔法-2.57
      • 贝塔0.59
      • 夏普比率-4.97
      • 胜率0.45
      • 盈亏比0.61
      • 收益波动率48.74%
      • 信息比率-0.36
      • 最大回撤76.53%
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-fe3fa2d43028401583cc22058fe90094"}/bigcharts-data-end
      [Parallel(n_jobs=1)]: Done   6 out of   6 | elapsed:    8.5s remaining:    0.0s
      [Parallel(n_jobs=1)]: Done   6 out of   6 | elapsed:    8.5s finished
      

      (youmin) #3

      谢谢,重启搞定