克隆策略
In [ ]:
 

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-169: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":"-169:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-176:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-183:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-190:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-2363:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-403:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-200:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"-183:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-200:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-176:input_data","SourceOutputPortId":"-169:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-176:data"},{"DestinationInputPortId":"-617:input_1","SourceOutputPortId":"-176:data"},{"DestinationInputPortId":"-190:input_data","SourceOutputPortId":"-183:data"},{"DestinationInputPortId":"-407:input_data","SourceOutputPortId":"-190:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"-2363:model"},{"DestinationInputPortId":"-2363:training_ds","SourceOutputPortId":"-403:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-407:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2014-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"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# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / 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":"sum(max(0,high_0-((high_1+low_1+close_1)/3)),26)/sum(max(0,((high_1+low_1+close_1)/3)-low_0),26)*100\nclose_0\nopen_0\n\n\n\nscale","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":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2015-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":"-169","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":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-169"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-169"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-169","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-176","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":"-176"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-176"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-176","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-183","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":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-183"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-183"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-183","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-190","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":"-190"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-190"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-190","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-200","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 context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n context.stock_count = 30\n context.hold_days = 5\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n if context.trading_day_index % context.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 \n stock_to_buy = list(ranker_prediction.instrument)[:context.stock_count]\n # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表\n stock_hold_now = [equity.symbol for equity in context.portfolio.positions]\n # 继续持有的股票:调仓时,如果买入的股票已经存在于目前的持仓里,那么应继续持有\n no_need_to_sell = [i for i in stock_hold_now if i in stock_to_buy]\n # 需要卖出的股票\n stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]\n \n assert type(stock_to_buy) == list, '格式类型不对!'\n \n \n # 卖出\n for stock in stock_to_sell:\n if data.can_trade(context.symbol(stock)):\n # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,\n # 即卖出全部股票,可参考回测文档\n context.order_target_percent(context.symbol(stock), 0)\n \n # 如果当天没有买入的股票,就返回\n if len(stock_to_buy) == 0:\n return\n\n \n context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, len(stock_to_buy))])\n\n # 买入\n c = 0\n for stock in stock_to_buy:\n \n if data.can_trade(context.symbol(stock)):\n # 下单使得某只股票的持仓权重达到weight,因为\n # weight大于0,因此是等权重买入\n context.order_target_percent(context.symbol(stock), context.stock_weights[c])\n c += 1","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":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":"3000000","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":"-200"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-200"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-200"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-200"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-200"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-200","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2363","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":"-2363"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-2363"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-2363"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-2363"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-2363","OutputType":null},{"Name":"feature_gains","NodeId":"-2363","OutputType":null},{"Name":"m_lazy_run","NodeId":"-2363","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-3355","ModuleId":"BigQuantSpace.hyper_run.hyper_run-v1","ModuleParameters":[{"Name":"run","Value":"def bigquant_run(bq_graph, inputs):\n factor_pool =['rank(std(amount_0,15))','rank_avg_amount_0/rank_avg_amount_8',\n 'ts_argmin(low_0,20)','rank_return_30','(low_1-close_0)/close_0','ta_bbands_lowerband_14_0',\n 'mean(mf_net_pct_s_0,4)','amount_0/avg_amount_3','return_0/return_5','return_1/return_5',\n 'rank_avg_amount_7/rank_avg_amount_10','ta_sma_10_0/close_0','sqrt(high_0*low_0)-amount_0/volume_0*adjust_factor_0',\n 'avg_turn_15/turn_0','return_10','mf_net_pct_s_0','(close_0-open_0)/close_1',\n 'return_5','return_10','return_20','avg_amount_0/avg_amount_5','avg_amount_5/avg_amount_20',\n 'rank_avg_amount_0/rank_avg_amount_5','rank_avg_amount_5/rank_avg_amount_10','rank_return_0',\n 'rank_return_5','rank_return_10','rank_return_0/rank_return_5','rank_return_5/rank_return_10','pe_ttm_0','close_0/open_0','close_0/mean(close_0,3)',\n 'close_0/mean(close_0,5)','close_0/mean(close_0,15)','close_0/mean(close_0,30)','close_0/mean(close_0,60)',\n 'amount_0/mean(amount_0,3)','amount_0/mean(amount_0,5)','amount_0/mean(amount_0,10)','amount_0/mean(amount_0,15)',\n 'amount_0/mean(amount_0,30)','amount_0/mean(amount_0,60)','turn_0/mean(turn_0,3)','turn_0/mean(turn_0,5)',\n 'turn_0/mean(turn_0,10)','turn_0/mean(turn_0,15)','turn_0/mean(turn_0,30)','turn_0/mean(turn_0,60)','open_0/mean(close_0,3)',\n 'open_0/mean(close_0,5)','open_0/mean(close_0,10)','open_0/mean(close_0,15)','open_0/mean(close_0,30)','open_0/mean(close_0,60)']\n\n batch_num = 1 # 多少组,需要跑多少组策略\n batch_factor = list()\n for i in range(batch_num):\n random.seed(i)\n factor_num = 10 # 每组多少个因子\n batch_factor.append(random.sample(factor_pool, factor_num))\n\n parameters_list = []\n \n for feature in batch_factor:\n parameters = {'m3.features': '\\n'.join(feature)}\n parameters_list.append({'parameters': parameters})\n \n \n def run(parameters):\n try:\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=10, remote_run=True, silent=True) # 任务数 # 是否远程 # \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":"-3355"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-3355"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-3355"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-3355"}],"OutputPortsInternal":[{"Name":"result","NodeId":"-3355","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-403","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-403"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-403"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-403","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-407","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-407"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-407"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-407","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-617","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3):\n # 示例代码如下。在这里编写您的代码\n from sklearn.preprocessing import MinMaxScaler\n df = input_1.read()\n \n \n \n \n data_1 = DataSource.write_df(df)\n data_2 = DataSource.write_pickle(df)\n return Outputs(data_1=data_1, data_2=data_2, data_3=None)\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":"{}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-617"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-617"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-617"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-617","OutputType":null},{"Name":"data_2","NodeId":"-617","OutputType":null},{"Name":"data_3","NodeId":"-617","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"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='119,59,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='66,181,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='572,-6,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='822,614,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1065,96,200,200'/><NodePosition Node='-169' Position='381,188,200,200'/><NodePosition Node='-176' Position='385,280,200,200'/><NodePosition Node='-183' Position='1078,236,200,200'/><NodePosition Node='-190' Position='1081,327,200,200'/><NodePosition Node='-200' Position='820,742,200,200'/><NodePosition Node='-2363' Position='635,539,200,200'/><NodePosition Node='-3355' Position='253,-176,200,200'/><NodePosition Node='-403' Position='376,467,200,200'/><NodePosition Node='-407' Position='1078,418,200,200'/><NodePosition Node='-617' Position='553,359,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 [17]:
    # 本代码由可视化策略环境自动生成 2021年5月27日17:40
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m12_run_bigquant_run(input_1, input_2, input_3):
        # 示例代码如下。在这里编写您的代码
        from sklearn.preprocessing import MinMaxScaler
        df = input_1.read()
        
        
        
        
        data_1 = DataSource.write_df(df)
        data_2 = DataSource.write_pickle(df)
        return Outputs(data_1=data_1, data_2=data_2, data_3=None)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m12_post_run_bigquant_run(outputs):
        return outputs
    
    # 回测引擎:初始化函数,只执行一次
    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))
        context.stock_count = 30
        context.hold_days = 5
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_handle_data_bigquant_run(context, data):
        
        if context.trading_day_index % context.hold_days != 0:
            return 
        
        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
        
        stock_to_buy = list(ranker_prediction.instrument)[:context.stock_count]
        # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表
        stock_hold_now = [equity.symbol for equity in context.portfolio.positions]
        # 继续持有的股票:调仓时,如果买入的股票已经存在于目前的持仓里,那么应继续持有
        no_need_to_sell = [i for i in stock_hold_now if i in stock_to_buy]
        # 需要卖出的股票
        stock_to_sell = [i for i in stock_hold_now if i not in no_need_to_sell]
        
        assert type(stock_to_buy) == list, '格式类型不对!'
        
        
        # 卖出
        for stock in stock_to_sell:
            if data.can_trade(context.symbol(stock)):
                # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,
                #   即卖出全部股票,可参考回测文档
                context.order_target_percent(context.symbol(stock), 0)
        
        # 如果当天没有买入的股票,就返回
        if len(stock_to_buy) == 0:
            return
    
         
        context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, len(stock_to_buy))])
    
        # 买入
        c = 0
        for stock in stock_to_buy:
            
            if data.can_trade(context.symbol(stock)):
                # 下单使得某只股票的持仓权重达到weight,因为
                # weight大于0,因此是等权重买入
                context.order_target_percent(context.symbol(stock), context.stock_weights[c])
            c += 1
    # 回测引擎:准备数据,只执行一次
    def m19_prepare_bigquant_run(context):
        pass
    
    
    g = T.Graph({
    
        'm1': 'M.instruments.v2',
        'm1.start_date': '2014-01-01',
        'm1.end_date': '2015-01-01',
        '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>`_
    
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    shift(close, -5) / 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': """sum(max(0,high_0-((high_1+low_1+close_1)/3)),26)/sum(max(0,((high_1+low_1+close_1)/3)-low_0),26)*100
    close_0
    open_0
    
    
    
    scale""",
    
        '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': 0,
    
        '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'),
    
        'm12': 'M.cached.v3',
        'm12.input_1': T.Graph.OutputPort('m16.data'),
        'm12.run': m12_run_bigquant_run,
        'm12.post_run': m12_post_run_bigquant_run,
        'm12.input_ports': '',
        'm12.params': '{}',
        'm12.output_ports': '',
    
        'm5': 'M.stock_ranker_train.v6',
        'm5.training_ds': T.Graph.OutputPort('m6.data'),
        'm5.features': T.Graph.OutputPort('m3.data'),
        'm5.learning_algorithm': '排序',
        'm5.number_of_leaves': 30,
        'm5.minimum_docs_per_leaf': 1000,
        'm5.number_of_trees': 20,
        'm5.learning_rate': 0.1,
        'm5.max_bins': 1023,
        'm5.feature_fraction': 1,
        'm5.data_row_fraction': 1,
        'm5.ndcg_discount_base': 1,
        'm5.m_lazy_run': False,
    
        'm9': 'M.instruments.v2',
        'm9.start_date': T.live_run_param('trading_date', '2015-01-01'),
        'm9.end_date': T.live_run_param('trading_date', '2015-06-01'),
        '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': 0,
    
        '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('m5.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': 'open',
        'm19.capital_base': 3000000,
        '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 m4_run_bigquant_run(bq_graph, inputs):
        factor_pool =['rank(std(amount_0,15))','rank_avg_amount_0/rank_avg_amount_8',
                        'ts_argmin(low_0,20)','rank_return_30','(low_1-close_0)/close_0','ta_bbands_lowerband_14_0',
                        'mean(mf_net_pct_s_0,4)','amount_0/avg_amount_3','return_0/return_5','return_1/return_5',
                        'rank_avg_amount_7/rank_avg_amount_10','ta_sma_10_0/close_0','sqrt(high_0*low_0)-amount_0/volume_0*adjust_factor_0',
                        'avg_turn_15/turn_0','return_10','mf_net_pct_s_0','(close_0-open_0)/close_1',
                        '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','close_0/open_0','close_0/mean(close_0,3)',
                        'close_0/mean(close_0,5)','close_0/mean(close_0,15)','close_0/mean(close_0,30)','close_0/mean(close_0,60)',
                        'amount_0/mean(amount_0,3)','amount_0/mean(amount_0,5)','amount_0/mean(amount_0,10)','amount_0/mean(amount_0,15)',
                        'amount_0/mean(amount_0,30)','amount_0/mean(amount_0,60)','turn_0/mean(turn_0,3)','turn_0/mean(turn_0,5)',
                        'turn_0/mean(turn_0,10)','turn_0/mean(turn_0,15)','turn_0/mean(turn_0,30)','turn_0/mean(turn_0,60)','open_0/mean(close_0,3)',
                        'open_0/mean(close_0,5)','open_0/mean(close_0,10)','open_0/mean(close_0,15)','open_0/mean(close_0,30)','open_0/mean(close_0,60)']
    
        batch_num = 1 # 多少组,需要跑多少组策略
        batch_factor = list()
        for i in range(batch_num):
            random.seed(i)
            factor_num = 10 # 每组多少个因子
            batch_factor.append(random.sample(factor_pool, factor_num))
    
        parameters_list = []
         
        for feature in  batch_factor:
            parameters = {'m3.features': '\n'.join(feature)}
            parameters_list.append({'parameters': parameters})
            
        
        def run(parameters):
            try:
                return g.run(parameters)
            except Exception as e:
                print('ERROR --------', e)
                return None
     
        results = T.parallel_map(run, parameters_list, max_workers=10, remote_run=True, silent=True)  # 任务数  # 是否远程  # 
    
        return results
    
    
    m4 = M.hyper_run.v1(
        run=m4_run_bigquant_run,
        run_now=True,
        bq_graph=g
    )
    
    In [ ]:
    m4.result
    
    In [12]:
    len(m4.result)
    
    Out[12]:
    1
    In [13]:
    # 查看第一个任务返回结果中的预测模块m8的预测结果前5条
    m4.result[0]['m8'].predictions.read_df().head()  # 每一个任务  每一个模块 的输入
    
    Out[13]:
    date instrument score position
    0 2015-01-30 603088.SHA 2.133042 1
    1 2015-01-30 300002.SZA 2.088365 2
    2 2015-01-30 002438.SZA 1.994470 3
    3 2015-01-30 601299.SHA 1.994470 4
    4 2015-01-30 603169.SHA 1.994470 5
    In [14]:
    # 绘制第一个任务返回结果中回测模块的绩效曲线
    m4.result[0]['m19'].display()
    
    • 收益率95.83%
    • 年化收益率453.28%
    • 基准收益率43.65%
    • 阿尔法1.26
    • 贝塔0.49
    • 夏普比率5.95
    • 胜率0.7
    • 盈亏比1.83
    • 收益波动率29.05%
    • 信息比率0.17
    • 最大回撤8.29%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-3451a21850b142c4b6b112d680c8876c"}/bigcharts-data-end