test-失效

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

(zxc7573316672) #1
克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-107:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-779:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"-1206:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-3661:features_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-1038:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-819:input_data","SourceOutputPortId":"-107:data"},{"DestinationInputPortId":"-1038:training_ds","SourceOutputPortId":"-648:data"},{"DestinationInputPortId":"-161:instruments","SourceOutputPortId":"-152:data"},{"DestinationInputPortId":"-213:instruments","SourceOutputPortId":"-152:data"},{"DestinationInputPortId":"-142:instruments","SourceOutputPortId":"-152:data"},{"DestinationInputPortId":"-837:input_data","SourceOutputPortId":"-161:data"},{"DestinationInputPortId":"-1871:input_ds","SourceOutputPortId":"-187:data"},{"DestinationInputPortId":"-1038:predict_ds","SourceOutputPortId":"-187:data"},{"DestinationInputPortId":"-2908:input_1","SourceOutputPortId":"-779:data"},{"DestinationInputPortId":"-779:data2","SourceOutputPortId":"-819:data"},{"DestinationInputPortId":"-2911:input_1","SourceOutputPortId":"-837:data"},{"DestinationInputPortId":"-207:data2","SourceOutputPortId":"-837:data"},{"DestinationInputPortId":"-181:input_1","SourceOutputPortId":"-207:data"},{"DestinationInputPortId":"-207:data1","SourceOutputPortId":"-213:data"},{"DestinationInputPortId":"-1038:test_ds","SourceOutputPortId":"-224:data"},{"DestinationInputPortId":"-648:input_data","SourceOutputPortId":"-2908:data_1"},{"DestinationInputPortId":"-187:input_data","SourceOutputPortId":"-2911:data_1"},{"DestinationInputPortId":"-161:features","SourceOutputPortId":"-1206:data"},{"DestinationInputPortId":"-837:features","SourceOutputPortId":"-1206:data"},{"DestinationInputPortId":"-1877:data2","SourceOutputPortId":"-1871:data"},{"DestinationInputPortId":"-344:input_ds","SourceOutputPortId":"-1877:data"},{"DestinationInputPortId":"-107:features","SourceOutputPortId":"-3661:data"},{"DestinationInputPortId":"-819:features","SourceOutputPortId":"-3661:data"},{"DestinationInputPortId":"-142:options_data","SourceOutputPortId":"-175:data_1"},{"DestinationInputPortId":"-175:input_1","SourceOutputPortId":"-344:sorted_data"},{"DestinationInputPortId":"-224:input_data","SourceOutputPortId":"-181:data_1"},{"DestinationInputPortId":"-1877:data1","SourceOutputPortId":"-1038:predictions"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-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, -6)/shift(close, -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":"Alpha1 = rank_swing_volatility_60_0#相关性高\nAlpha3 = rank_avg_turn_5\nAlpha4 = rank_swing_volatility_120_0#相关性高\nAlpha6 = rank_swing_volatility_5_0\n\nAlpha8 = swing_volatility_60_0\n\nAlpha11 = avg_amount_5\n\nAlpha23 = std(return_0, 180)\nAlpha25 = std(return_0, 60)#相关性高\nAlpha26 = std(avg_amount_0, 60)#相关性高\n \n#Alpha30 = (-1 * rank(covariance(rank(close_0), rank(volume_0), 5)))#正向#相关性高\n#Alpha31 = (-1 * rank(covariance(rank(high_0), rank(volume_0), 5)))#正向\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"因子","CommentCollapsed":false},{"Id":"-107","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":"300","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-107"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-107"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-107","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-142","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 stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = [0.2]*5\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.04\n context.options['hold_days'] = 5","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n today = data.current_dt.strftime('%Y-%m-%d')\n stock_hold_now = [equity.symbol for equity in context.portfolio.positions ]\n ##大盘风控模块,读取风控数据 \n #benckmark_risk=context.benckmark_risk[today]\n #context.symbol\n ##当risk为1时,市场有风险,全部平仓,不再执行其它操作\n #if benckmark_risk > 0:\n # for instrument in stock_hold_now:\n # context.order_target(symbol(instrument), 0)\n # print(today,'大盘风控止损触发,全仓卖出')\n # return\n\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n \n if len(ranker_prediction.instrument) < 3:\n return\n \n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.options['hold_days']\n cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n \n #----------------------------START:持有固定交易日天数卖出---------------------------\n today = data.current_dt.strftime('%Y-%m-%d')\n # 不是建仓期(在前hold_days属于建仓期)\n if not is_staging:\n equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}\n for instrument in equities:\n sid = equities[instrument].sid # 交易标的\n # 今天和上次交易的时间相隔hold_days就全部卖出\n dt = pd.to_datetime(D.trading_days(end_date = today).iloc[-context.options['hold_days']].values[0])\n if pd.to_datetime(equities[instrument].last_sale_date.strftime('%Y-%m-%d')) <= dt and data.can_trade(context.symbol(instrument)):\n context.order_target_percent(sid, 0)\n cash_for_buy += positions[instrument]\n #--------------------------------END:持有固定天数卖出--------------------------- \n \n\n # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票\n buy_cash_weights = context.stock_weights\n counto = 0\n str_list = [ ]\n \n for i in range(len(buy_cash_weights)):\n while (' '.join(ranker_prediction.instrument[counto:counto+1])) in positions.keys():\n counto += 1\n str_list.append(list(ranker_prediction.instrument[counto:counto+1]))\n \n counto += 1\n \n buy_instruments = [ ]\n buy_instruments.extend([x[0] for x in str_list])\n \n max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument\n for i, instrument in enumerate(buy_instruments):\n cash = cash_for_buy * buy_cash_weights[i]\n if cash > max_cash_per_instrument - positions.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n cash = max_cash_per_instrument - positions.get(instrument, 0)\n if cash > 0:\n context.order_value(context.symbol(instrument), cash)\n #print(context.symbol(instrument), cash)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"def bigquant_run(context):\n #在数据准备函数中一次性计算每日的大盘风控条件相比于在handle中每日计算风控条件可以提高回测速度\n # 多取50天的数据便于计算均值(保证回测的第一天均值不为Nan值),其中context.start_date和context.end_date是回测指定的起始时间和终止时间\n start_date= (pd.to_datetime(context.start_date) - datetime.timedelta(days=50)).strftime('%Y-%m-%d') \n df=DataSource('bar1d_index_CN_STOCK_A').read(start_date=start_date,end_date=context.end_date,fields=['close'])\n benckmark_data=df[df.instrument=='000001.HIX']\n #计算上证指数5日涨幅\n benckmark_data['ret5']=benckmark_data['close']/benckmark_data['close'].shift(1)-1\n #计算大盘风控条件,如果5日涨幅小于-4%则设置风险状态risk为1,否则为0\n benckmark_data['risk'] = np.where(benckmark_data['ret5']<-0.04,1,0)\n #修改日期格式为字符串(便于在handle中使用字符串日期索引来查看每日的风险状态)\n benckmark_data['date']=benckmark_data['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n #设置日期为索引\n benckmark_data.set_index('date',inplace=True)\n #把风控序列输出给全局变量context.benckmark_risk\n context.benckmark_risk=benckmark_data['risk']\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":"1000000","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"False","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":"-142"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-142"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-142"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-142"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-142"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-142","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-648","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-648"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-648"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-648","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-152","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2019-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2020-09-22","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":"-152"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-152","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-161","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":"300","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-161"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-161"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-161","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-187","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-187"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-187"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-187","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":22,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-779","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":"-779"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-779"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-779","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-819","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":"-819"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-819"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-819","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":24,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-837","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":"-837"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-837"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-837","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":26,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-207","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":"-207"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-207"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-207","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-213","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, -6)/shift(close, -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":"-213"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-213","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-224","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-224"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-224"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-224","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":11,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2908","ModuleId":"BigQuantSpace.filtet_st_stock.filtet_st_stock-v7","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2908"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-2908","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2911","ModuleId":"BigQuantSpace.filtet_st_stock.filtet_st_stock-v7","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-2911"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-2911","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1206","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"#每档排序指标,默认从大到小排序,若想从小到大排序,在前面加负号-\nranker = close_0/mean(close_0, 5)\n\n#过滤条件\n#f15 = mean(close_1, 5)\n#f05 = mean(close_0, 5)\n#f110 = mean(close_1, 10)\n#f010 = mean(close_0, 10)\n\n\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-1206"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1206","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"每档排序指标","CommentCollapsed":false},{"Id":"-1871","ModuleId":"BigQuantSpace.select_columns.select_columns-v3","ModuleParameters":[{"Name":"columns","Value":"date,instrument,ranker","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"reverse_select","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-1871"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"columns_ds","NodeId":"-1871"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1871","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1877","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":"-1877"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-1877"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1877","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-3661","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\n#f15 = mean(close_1, 5)\n#f05 = mean(close_0, 5)\n#f110 = mean(close_1, 10)\n#f010 = mean(close_0, 10)\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-3661"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-3661","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":20,"IsPartOfPartialRun":null,"Comment":"过滤条件","CommentCollapsed":false},{"Id":"-175","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1):\n # 示例代码如下。在这里编写您的代码\n df = input_1.read_df()\n df = pd.DataFrame(df)\n df = df.groupby(['date','score'], as_index = True, sort = False).apply(lambda x: x.sort_values('ranker', ascending = False))\n df = df.reset_index(drop=True)\n data_1 = DataSource.write_df(df)\n \n return Outputs(data_1=data_1)\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":"input_1","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":"-175"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-175"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-175"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-175","OutputType":null},{"Name":"data_2","NodeId":"-175","OutputType":null},{"Name":"data_3","NodeId":"-175","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-344","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"position","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-344"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-344"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-344","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":21,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-181","ModuleId":"BigQuantSpace.filtet_st_stock.filtet_st_stock-v7","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-181"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-181","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":27,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1038","ModuleId":"BigQuantSpace.stock_ranker.stock_ranker-v2","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"20","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":"1000","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"5","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":"0.2","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":"slim_data","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"-1038"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1038"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-1038"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-1038"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_model","NodeId":"-1038"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"predict_ds","NodeId":"-1038"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-1038","OutputType":null},{"Name":"predictions","NodeId":"-1038","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":23,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-190","ModuleId":"BigQuantSpace.hyper_parameter_search.hyper_parameter_search-v1","ModuleParameters":[{"Name":"param_grid_builder","Value":"def bigquant_run():\n param_grid = {}\n\n # 在这里设置需要调优的参数备选\n param_grid['m23.minimum_docs_per_leaf'] = [5000]\n param_grid['m23.number_of_leaves'] = [10, 20, 30]\n param_grid['m23.number_of_trees'] = [5, 10, 15, 20, 30]\n param_grid['m23.learning_rate'] = [0.2]\n\n return param_grid\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"scoring","Value":"def bigquant_run(result):\n score = result.get('m19').read_raw_perf()['sharpe'].tail(1)[0]\n\n return score\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"search_algorithm","Value":"网格搜索","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"search_iterations","Value":10,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"random_state","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"workers","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"worker_distributed_run","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"worker_silent","Value":"True","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":"-190"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-190"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-190"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-190"}],"OutputPortsInternal":[{"Name":"result","NodeId":"-190","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='-215,-110,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='-419,37,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='350,-337,200,200'/><NodePosition Node='-107' Position='-11,-2,200,200'/><NodePosition Node='-142' Position='478,937,200,200'/><NodePosition Node='-648' Position='-208,375,200,200'/><NodePosition Node='-152' Position='924,-113,200,200'/><NodePosition Node='-161' Position='1099,8,200,200'/><NodePosition Node='-187' Position='1109,290,200,200'/><NodePosition Node='-779' Position='-209,175,200,200'/><NodePosition Node='-819' Position='-12,83,200,200'/><NodePosition Node='-837' Position='1106,99,200,200'/><NodePosition Node='-207' Position='435,89,200,200'/><NodePosition Node='-213' Position='433,1,200,200'/><NodePosition Node='-224' Position='435,256,200,200'/><NodePosition Node='-2908' Position='-207,273,200,200'/><NodePosition Node='-2911' Position='1109,195,200,200'/><NodePosition Node='-1206' Position='577,-201,200,200'/><NodePosition Node='-1871' Position='1104,473,200,200'/><NodePosition Node='-1877' Position='843,609,200,200'/><NodePosition Node='-3661' Position='101,-200,200,200'/><NodePosition Node='-175' Position='846,800,200,200'/><NodePosition Node='-344' Position='846,707,200,200'/><NodePosition Node='-181' Position='435,175,200,200'/><NodePosition Node='-1038' Position='308,480,200,200'/><NodePosition Node='-190' Position='-262,615,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 [ ]:
    # 本代码由可视化策略环境自动生成 2020年9月29日 13:58
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m17_run_bigquant_run(input_1):
        # 示例代码如下。在这里编写您的代码
        df = input_1.read_df()
        df = pd.DataFrame(df)
        df = df.groupby(['date','score'], as_index = True, sort = False).apply(lambda x: x.sort_values('ranker', ascending = False))
        df = df.reset_index(drop=True)
        data_1 = DataSource.write_df(df)
       
        return Outputs(data_1=data_1)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m17_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))
        # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        stock_count = 5
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        context.stock_weights = [0.2]*5
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 0.04
        context.options['hold_days'] = 5
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_handle_data_bigquant_run(context, data):
        today = data.current_dt.strftime('%Y-%m-%d')
        stock_hold_now = [equity.symbol for equity in context.portfolio.positions ]
        ##大盘风控模块,读取风控数据    
        #benckmark_risk=context.benckmark_risk[today]
        #context.symbol
        ##当risk为1时,市场有风险,全部平仓,不再执行其它操作
        #if benckmark_risk > 0:
        #    for instrument in stock_hold_now:
        #        context.order_target(symbol(instrument), 0)
        #    print(today,'大盘风控止损触发,全仓卖出')
        #    return
    
        
        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
        
        if len(ranker_prediction.instrument) < 3:
            return
        
        # 1. 资金分配
        # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
        # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
        is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
        cash_avg = context.portfolio.portfolio_value / context.options['hold_days']
        cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
        positions = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.portfolio.positions.items()}
       
        #----------------------------START:持有固定交易日天数卖出---------------------------
        today = data.current_dt.strftime('%Y-%m-%d')
        # 不是建仓期(在前hold_days属于建仓期)
        if not is_staging:
            equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
            for instrument in equities:
                sid = equities[instrument].sid  # 交易标的
                # 今天和上次交易的时间相隔hold_days就全部卖出
                dt = pd.to_datetime(D.trading_days(end_date = today).iloc[-context.options['hold_days']].values[0])
                if  pd.to_datetime(equities[instrument].last_sale_date.strftime('%Y-%m-%d')) <= dt and data.can_trade(context.symbol(instrument)):
                    context.order_target_percent(sid, 0)
                    cash_for_buy += positions[instrument]
        #--------------------------------END:持有固定天数卖出--------------------------- 
              
    
        # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票
        buy_cash_weights = context.stock_weights
        counto = 0
        str_list = [ ]
        
        for i in range(len(buy_cash_weights)):
            while (' '.join(ranker_prediction.instrument[counto:counto+1])) in positions.keys():
                counto += 1
            str_list.append(list(ranker_prediction.instrument[counto:counto+1]))
            
            counto += 1
        
        buy_instruments = [ ]
        buy_instruments.extend([x[0] for x in str_list])
        
        max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
        for i, instrument in enumerate(buy_instruments):
            cash = cash_for_buy * buy_cash_weights[i]
            if cash > max_cash_per_instrument - positions.get(instrument, 0):
                # 确保股票持仓量不会超过每次股票最大的占用资金量
                cash = max_cash_per_instrument - positions.get(instrument, 0)
            if cash > 0:
                context.order_value(context.symbol(instrument), cash)
                #print(context.symbol(instrument), cash)
    
    def m19_prepare_bigquant_run(context):
        #在数据准备函数中一次性计算每日的大盘风控条件相比于在handle中每日计算风控条件可以提高回测速度
        # 多取50天的数据便于计算均值(保证回测的第一天均值不为Nan值),其中context.start_date和context.end_date是回测指定的起始时间和终止时间
        start_date= (pd.to_datetime(context.start_date) - datetime.timedelta(days=50)).strftime('%Y-%m-%d') 
        df=DataSource('bar1d_index_CN_STOCK_A').read(start_date=start_date,end_date=context.end_date,fields=['close'])
        benckmark_data=df[df.instrument=='000001.HIX']
        #计算上证指数5日涨幅
        benckmark_data['ret5']=benckmark_data['close']/benckmark_data['close'].shift(1)-1
        #计算大盘风控条件,如果5日涨幅小于-4%则设置风险状态risk为1,否则为0
        benckmark_data['risk'] = np.where(benckmark_data['ret5']<-0.04,1,0)
        #修改日期格式为字符串(便于在handle中使用字符串日期索引来查看每日的风险状态)
        benckmark_data['date']=benckmark_data['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
        #设置日期为索引
        benckmark_data.set_index('date',inplace=True)
        #把风控序列输出给全局变量context.benckmark_risk
        context.benckmark_risk=benckmark_data['risk']
    
    
    g = T.Graph({
    
        'm1': 'M.instruments.v2',
        'm1.start_date': '2016-01-01',
        'm1.end_date': '2019-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, -6)/shift(close, -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': """Alpha1 = rank_swing_volatility_60_0#相关性高
    Alpha3 = rank_avg_turn_5
    Alpha4 = rank_swing_volatility_120_0#相关性高
    Alpha6 = rank_swing_volatility_5_0
    
    Alpha8 = swing_volatility_60_0
    
    Alpha11 = avg_amount_5
    
    Alpha23 = std(return_0, 180)
    Alpha25 = std(return_0, 60)#相关性高
    Alpha26 = std(avg_amount_0, 60)#相关性高
                
    #Alpha30 = (-1 * rank(covariance(rank(close_0), rank(volume_0), 5)))#正向#相关性高
    #Alpha31 = (-1 * rank(covariance(rank(high_0), rank(volume_0), 5)))#正向
    """,
    
        'm12': 'M.input_features.v1',
        'm12.features_ds': T.Graph.OutputPort('m3.data'),
        'm12.features': """#每档排序指标,默认从大到小排序,若想从小到大排序,在前面加负号-
    ranker = close_0/mean(close_0, 5)
    
    #过滤条件
    #f15 = mean(close_1, 5)
    #f05 = mean(close_0, 5)
    #f110 = mean(close_1, 10)
    #f010 = mean(close_0, 10)
    
    
    """,
    
        'm20': 'M.input_features.v1',
        'm20.features_ds': T.Graph.OutputPort('m3.data'),
        'm20.features': """
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    #f15 = mean(close_1, 5)
    #f05 = mean(close_0, 5)
    #f110 = mean(close_1, 10)
    #f010 = mean(close_0, 10)
    """,
    
        'm15': 'M.general_feature_extractor.v7',
        'm15.instruments': T.Graph.OutputPort('m1.data'),
        'm15.features': T.Graph.OutputPort('m20.data'),
        'm15.start_date': '',
        'm15.end_date': '',
        'm15.before_start_days': 300,
    
        'm24': 'M.derived_feature_extractor.v3',
        'm24.input_data': T.Graph.OutputPort('m15.data'),
        'm24.features': T.Graph.OutputPort('m20.data'),
        'm24.date_col': 'date',
        'm24.instrument_col': 'instrument',
        'm24.drop_na': False,
        'm24.remove_extra_columns': False,
        'm24.user_functions': {},
    
        'm10': 'M.join.v3',
        'm10.data1': T.Graph.OutputPort('m2.data'),
        'm10.data2': T.Graph.OutputPort('m24.data'),
        'm10.on': 'date,instrument',
        'm10.how': 'inner',
        'm10.sort': False,
    
        'm6': 'M.filtet_st_stock.v7',
        'm6.input_1': T.Graph.OutputPort('m10.data'),
    
        'm5': 'M.dropnan.v2',
        'm5.input_data': T.Graph.OutputPort('m6.data_1'),
    
        'm16': 'M.instruments.v2',
        'm16.start_date': '2019-01-01',
        'm16.end_date': '2020-09-22',
        'm16.market': 'CN_STOCK_A',
        'm16.instrument_list': '',
        'm16.max_count': 0,
    
        'm18': 'M.general_feature_extractor.v7',
        'm18.instruments': T.Graph.OutputPort('m16.data'),
        'm18.features': T.Graph.OutputPort('m12.data'),
        'm18.start_date': '',
        'm18.end_date': '',
        'm18.before_start_days': 300,
    
        'm26': 'M.derived_feature_extractor.v3',
        'm26.input_data': T.Graph.OutputPort('m18.data'),
        'm26.features': T.Graph.OutputPort('m12.data'),
        'm26.date_col': 'date',
        'm26.instrument_col': 'instrument',
        'm26.drop_na': False,
        'm26.remove_extra_columns': False,
        'm26.user_functions': {},
    
        'm7': 'M.filtet_st_stock.v7',
        'm7.input_1': T.Graph.OutputPort('m26.data'),
    
        'm22': 'M.dropnan.v2',
        'm22.input_data': T.Graph.OutputPort('m7.data_1'),
    
        'm13': 'M.select_columns.v3',
        'm13.input_ds': T.Graph.OutputPort('m22.data'),
        'm13.columns': 'date,instrument,ranker',
        'm13.reverse_select': False,
    
        'm9': 'M.advanced_auto_labeler.v2',
        'm9.instruments': T.Graph.OutputPort('m16.data'),
        'm9.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, -6)/shift(close, -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)
    """,
        'm9.start_date': '',
        'm9.end_date': '',
        'm9.benchmark': '000300.SHA',
        'm9.drop_na_label': True,
        'm9.cast_label_int': True,
    
        'm8': 'M.join.v3',
        'm8.data1': T.Graph.OutputPort('m9.data'),
        'm8.data2': T.Graph.OutputPort('m26.data'),
        'm8.on': 'date,instrument',
        'm8.how': 'inner',
        'm8.sort': False,
    
        'm27': 'M.filtet_st_stock.v7',
        'm27.input_1': T.Graph.OutputPort('m8.data'),
    
        'm11': 'M.dropnan.v2',
        'm11.input_data': T.Graph.OutputPort('m27.data_1'),
    
        'm23': 'M.stock_ranker.v2',
        'm23.training_ds': T.Graph.OutputPort('m5.data'),
        'm23.features': T.Graph.OutputPort('m3.data'),
        'm23.test_ds': T.Graph.OutputPort('m11.data'),
        'm23.predict_ds': T.Graph.OutputPort('m22.data'),
        'm23.learning_algorithm': '排序',
        'm23.number_of_leaves': 20,
        'm23.minimum_docs_per_leaf': 1000,
        'm23.number_of_trees': 5,
        'm23.learning_rate': 0.2,
        'm23.max_bins': 1023,
        'm23.feature_fraction': 1,
        'm23.data_row_fraction': 1,
        'm23.ndcg_discount_base': 1,
        'm23.slim_data': True,
    
        'm14': 'M.join.v3',
        'm14.data1': T.Graph.OutputPort('m23.predictions'),
        'm14.data2': T.Graph.OutputPort('m13.data'),
        'm14.on': 'date,instrument',
        'm14.how': 'inner',
        'm14.sort': False,
    
        'm21': 'M.sort.v4',
        'm21.input_ds': T.Graph.OutputPort('m14.data'),
        'm21.sort_by': 'position',
        'm21.group_by': 'date',
        'm21.keep_columns': '--',
        'm21.ascending': True,
    
        'm17': 'M.cached.v3',
        'm17.input_1': T.Graph.OutputPort('m21.sorted_data'),
        'm17.run': m17_run_bigquant_run,
        'm17.post_run': m17_post_run_bigquant_run,
        'm17.input_ports': 'input_1',
        'm17.params': '{}',
        'm17.output_ports': '',
    
        'm19': 'M.trade.v4',
        'm19.instruments': T.Graph.OutputPort('m16.data'),
        'm19.options_data': T.Graph.OutputPort('m17.data_1'),
        '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,
        'm19.order_price_field_buy': 'close',
        'm19.order_price_field_sell': 'close',
        'm19.capital_base': 1000000,
        'm19.auto_cancel_non_tradable_orders': False,
        'm19.data_frequency': 'daily',
        'm19.price_type': '真实价格',
        'm19.product_type': '股票',
        'm19.plot_charts': True,
        'm19.backtest_only': False,
        'm19.benchmark': '',
    })
    
    # g.run({})
    
    
    def m4_param_grid_builder_bigquant_run():
        param_grid = {}
    
        # 在这里设置需要调优的参数备选
        param_grid['m23.minimum_docs_per_leaf'] = [5000]
        param_grid['m23.number_of_leaves'] = [10, 20, 30]
        param_grid['m23.number_of_trees'] = [5, 10, 15, 20, 30]
        param_grid['m23.learning_rate'] = [0.2]
    
        return param_grid
    
    
    def m4_scoring_bigquant_run(result):
        score = result.get('m19').read_raw_perf()['sharpe'].tail(1)[0]
    
        return score
    
    
    m4 = M.hyper_parameter_search.v1(
        param_grid_builder=m4_param_grid_builder_bigquant_run,
        scoring=m4_scoring_bigquant_run,
        search_algorithm='网格搜索',
        search_iterations=10,
        workers=1,
        worker_distributed_run=True,
        worker_silent=True,
        run_now=True,
        bq_graph=g
    )
    
    Fitting 1 folds for each of 15 candidates, totalling 15 fits
    [Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
    [CV] m23.learning_rate=0.2, m23.minimum_docs_per_leaf=5000, m23.number_of_leaves=10, m23.number_of_trees=5 
    
    [CV]  m23.learning_rate=0.2, m23.minimum_docs_per_leaf=5000, m23.number_of_leaves=10, m23.number_of_trees=5, score=1.1551256427288832, total=11.6min
    [Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed: 11.6min remaining:    0.0s
    [CV] m23.learning_rate=0.2, m23.minimum_docs_per_leaf=5000, m23.number_of_leaves=10, m23.number_of_trees=10 
    
    In [ ]:
     
    
    In [ ]:
    #m21.sorted_data.read_all_df()
    
    In [ ]:
    #m4.predictions.read_df().to_csv('1.csv')
    #dt.to_csv('3.csv')