策略运行错误AttributeError: module 'tensorflow' has no attribute 'placeholder'?


(ahxdct) #1

策略运行错误AttributeError: module ‘tensorflow’ has no attribute ‘placeholder’?什么情况!


(达达) #2

能分享一下策略么?


(ahxdct) #3
克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-8531: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":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-8531:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-8538:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-8547:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-8554:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:model"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"-8566:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"-8547:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-8566:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-8587:input_data","SourceOutputPortId":"-8531:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-8538:data"},{"DestinationInputPortId":"-8596:input_data","SourceOutputPortId":"-8547:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-8554:data"},{"DestinationInputPortId":"-8538:input_data","SourceOutputPortId":"-8587:data"},{"DestinationInputPortId":"-8554:input_data","SourceOutputPortId":"-8596: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":"2018-06-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. 可用数据字段见 {{web_host_url}}docs/data_history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <{{web_host_url}}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# 将分数映射到分类,这里使用1000个分类\nall_wbins(label, 1000)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na_label","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"cast_label_int","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nta_mfi_14_0\nta_adx_14_0\nwhere(ta_cci_14_0>100,delta(ta_cci_14_0,1),where(ta_cci_14_0<-100,delta(ta_cci_14_0,1),0))\narctan(avg_turn_5*return_5)\nta_willr_14_0\narctan(where(ta_macd_macd_12_26_9_0>0,swing_volatility_5_0,swing_volatility_5_0*-1))\narctan(avg_mf_net_amount_5/avg_amount_5)\nwhere(delta(ta_macd_macd_12_26_9_0,1)>0,ta_aroon_up_14_0*ta_aroon_down_14_0,ta_aroon_up_14_0*ta_aroon_down_14_0*-1)\narcsin(where(delta(ta_macd_macd_12_26_9_0,1)>0,(1-turn_5*0.01)*(1-turn_0*0.01)*(1-turn_1*0.01)*(1-turn_2*0.01)*(1-turn_3*0.01)*(1-turn_4*0.01),(1-turn_5*0.01)*(1-turn_0*0.01)*(1-turn_1*0.01)*(1-turn_2*0.01)*(1-turn_3*0.01)*(1-turn_4*0.01)*-1))\narctan2((close_0-close_1),(close_1-close_2))","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-43","ModuleId":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v5","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":"50","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":"500","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":"30","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":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"}],"OutputPortsInternal":[{"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null},{"Name":"feature_gains","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"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":"2018-06-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2018-07-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-8531","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":"150","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-8531"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-8531"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8531","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-8538","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":"-8538"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-8538"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8538","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-8547","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":"150","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-8547"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-8547"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8547","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-8554","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":"-8554"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-8554"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8554","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-8566","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 # 设置买入的股票数量,这里买入预测股票列表排名靠前的4只\n stock_count = 4\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.05\n context.options['hold_days'] = 5\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n from sklearn.preprocessing import maxabs_scale\n from keras.models import load_model\n \n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n\n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.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 cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)\n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n \n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰\n ss=[]\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n \n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n ss.append(instrument)\n if cash_for_sell <= 0:\n break\n\n #---------------------START--------------------------\n \n today_date = data.current_dt.strftime('%Y-%m-%d')\n buy_cash_weights = context.stock_weights\n test_input = []\n start_date= (pd.to_datetime(today_date) - datetime.timedelta(days=20)).strftime('%Y-%m-%d')\n fields = ['open','close', 'high', 'low','amount','volume'] \n buy_instruments=list(ranker_prediction.instrument[:len(buy_cash_weights)])\n data2 = DataSource('bar1d_CN_STOCK_A').read(buy_instruments, start_date, today_date, fields)\n for instrument in buy_instruments:\n tdata2 = data2[data2.instrument==instrument][fields]\n b = maxabs_scale(tdata2[len(tdata2)-5:])\n test_input.append(b)\n \n test_x = np.array(test_input)\n ds = DataSource(context.modid)\n model_new = load_model(ds.open_temp_path())\n ds.close_temp_path()\n ds11 = DataSource(context.modid11)\n model_new11 = load_model(ds11.open_temp_path())\n ds11.close_temp_path()\n predictions = model_new.predict(test_x)\n predictions11 = model_new11.predict(test_x)\n cc=predictions+predictions11\n dd=np.concatenate((predictions,predictions11),axis=0).reshape(8,1)\n jishu=1\n for i in range(len(dd)):\n if dd[i]<0:\n jishu=jishu-0.1\n jishu=np.round(jishu,2)\n fieldsu=['pe_ttm','pe_lyr','pb_lf','ps_ttm']\n pp=DataSource('market_value_CN_STOCK_A').read(buy_instruments, today_date, today_date, fieldsu)\n ppd=[]\n for instrument in pp.instrument:\n ppd.append(data.current(context.symbol(instrument), 'price'))\n pp['price']=ppd\n pp=pp.set_index('instrument')\n print(today_date,jishu)\n print(dd.reshape(2,4))\n print(buy_instruments)\n print(pp.drop('date',axis=1))\n if len(ss)>0:\n print(ss)\n \n \n \n #------------------------END---------------------------\n \n \n \n # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票\n #buy_cash_weights = context.stock_weights\n max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument\n for i, instrument in enumerate(buy_instruments):\n cash = cash_for_buy * buy_cash_weights[i]\n if cash > max_cash_per_instrument - positions.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n cash = max_cash_per_instrument - positions.get(instrument, 0)\n if cash > 0 :\n if cc[i]>0:\n context.order_value(context.symbol(instrument), jishu*cash)\n else:\n context.order_value(context.symbol(instrument), 0.5*jishu*cash)\n \n \n ","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n #---------------------START--------------------------\n seq_len=5 #每个input的长度\n # 导入包\n from keras.layers.core import Activation, Dropout\n from keras import optimizers\n from sklearn.preprocessing import maxabs_scale\n from keras.layers import Input, Dense, LSTM\n from keras.models import Model\n # 基础参数配置\n instrument=['000001.HIX','399001.ZIX']\n #设置用于训练和回测的开始/结束日期\n train_length=seq_len*10\n jc=train_length-2*seq_len\n start_date= (pd.to_datetime(context.start_date) - datetime.timedelta(days=2*train_length)).strftime('%Y-%m-%d') # 多取几天的数据,这里取5倍\n fields = ['open','close', 'high', 'low','amount','volume'] # features因子\n batch = 10#整数,指定进行梯度下降时每个batch包含的样本数,训练时一个batch的样本会被计算一次梯度下降,使目标函数优化一步\n \n # 数据导入以及初步处理\n data = DataSource('bar1d_index_CN_STOCK_A').read(instrument, start_date, context.start_date, fields)\n data1=data[data.instrument==instrument[0]]\n data11=data[data.instrument==instrument[1]]\n data1=data1[len(data1)-train_length:]\n data11=data11[len(data11)-train_length:]\n data1['return'] = data1['close'].shift(-5) / data1['open'].shift(-1) - 1 #计算未来5日收益率(未来第五日的收盘价/明日的开盘价)\n data11['return'] = data11['close'].shift(-5) / data11['open'].shift(-1) - 1\n data1.fillna(value=0)\n data11.fillna(value=0)\n data1['return'] = data1['return']*10 # 适当增大return范围,利于LSTM模型训练\n data11['return'] = data11['return']*10\n data1.reset_index(drop=True, inplace=True)\n data11.reset_index(drop=True, inplace=True)\n scaledata = data1[fields]\n scaledata11 = data11[fields]\n traindata = data1['return']\n traindata11 = data11['return']\n # 数据处理:设定每个input(series×6features)以及数据标准化\n train_input = []\n train_input11 = []\n train_output = []\n train_output11 = []\n \n for i in range(seq_len-1, len(traindata)):\n a = maxabs_scale(scaledata[i+1-seq_len:i+1])\n train_input.append(a)\n c = traindata[i]\n train_output.append(c)\n \n\n for i in range(seq_len-1, len(traindata11)):\n a = maxabs_scale(scaledata11[i+1-seq_len:i+1])\n train_input11.append(a)\n c = traindata11[i]\n train_output11.append(c)\n # LSTM接受数组类型的输入\n train_x = np.array(train_input)[:jc]\n train_x11 = np.array(train_input11)[:jc]\n train_y = np.array(train_output)[:jc]\n train_y11 = np.array(train_output11)[:jc]\n \n \n # 自定义激活函数\n # 构建神经网络层 1层LSTM层+3层Dense层\n # 用于1个输入情况\n lstm_input = Input(shape=(seq_len,len(fields)), name='lstm_input')\n lstm_output = LSTM(32, activation='tanh', dropout_W=0.2, dropout_U=0.1)(lstm_input)\n Dense_output_1 = Dense(16, activation='linear')(lstm_output)\n Dense_output_2 = Dense(4, activation='linear')(Dense_output_1)\n predictions = Dense(1, activation='tanh')(Dense_output_2)\n model = Model(input=lstm_input, output=predictions)\n model.compile(optimizer='adam', loss='mse', metrics=['mse'])\n model.fit(train_x, train_y, batch_size=batch, nb_epoch=15, verbose=0)\n model_ds = DataSource()\n model.save(model_ds.open_temp_path())\n model_ds.close_temp_path()\n context.modid=model_ds.id\n \n lstm_input11 = Input(shape=(seq_len,len(fields)), name='lstm_input11')\n lstm_output11 = LSTM(32, activation='tanh', dropout_W=0.2, dropout_U=0.1)(lstm_input11)\n Dense_output_111 = Dense(16, activation='linear')(lstm_output11)\n Dense_output_211 = Dense(4, activation='linear')(Dense_output_111)\n predictions11 = Dense(1, activation='tanh')(Dense_output_211)\n model11 = Model(input=lstm_input11, output=predictions11)\n model11.compile(optimizer='adam', loss='mse', metrics=['mse'])\n model11.fit(train_x11, train_y11, batch_size=batch, nb_epoch=15, verbose=0)\n model_ds11 = DataSource()\n model11.save(model_ds11.open_temp_path())\n model_ds11.close_temp_path()\n context.modid11=model_ds11.id\n #------------------------END---------------------------\n ","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"后复权","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"product_type","Value":"股票","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.HIX","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-8566"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-8566"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-8566"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-8566"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-8566"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-8566","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-8587","ModuleId":"BigQuantSpace.chinaa_stock_filter.chinaa_stock_filter-v1","ModuleParameters":[{"Name":"index_constituent_cond","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%8150%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%8150%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B2%AA%E6%B7%B1300%22%2C%22displayValue%22%3A%22%E6%B2%AA%E6%B7%B1300%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81500%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81500%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81800%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81800%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%81180%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%81180%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81100%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81100%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B7%B1%E8%AF%81100%22%2C%22displayValue%22%3A%22%E6%B7%B1%E8%AF%81100%22%2C%22selected%22%3Afalse%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"board_cond","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B7%B1%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22displayValue%22%3A%22%E6%B7%B1%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%88%9B%E4%B8%9A%E6%9D%BF%22%2C%22displayValue%22%3A%22%E5%88%9B%E4%B8%9A%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"industry_cond","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%BA%A4%E9%80%9A%E8%BF%90%E8%BE%93%22%2C%22displayValue%22%3A%22%E4%BA%A4%E9%80%9A%E8%BF%90%E8%BE%93%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%BC%91%E9%97%B2%E6%9C%8D%E5%8A%A1%22%2C%22displayValue%22%3A%22%E4%BC%91%E9%97%B2%E6%9C%8D%E5%8A%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%BC%A0%E5%AA%92%2F%E4%BF%A1%E6%81%AF%E6%9C%8D%E5%8A%A1%22%2C%22displayValue%22%3A%22%E4%BC%A0%E5%AA%92%2F%E4%BF%A1%E6%81%AF%E6%9C%8D%E5%8A%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%85%AC%E7%94%A8%E4%BA%8B%E4%B8%9A%22%2C%22displayValue%22%3A%22%E5%85%AC%E7%94%A8%E4%BA%8B%E4%B8%9A%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%86%9C%E6%9E%97%E7%89%A7%E6%B8%94%22%2C%22displayValue%22%3A%22%E5%86%9C%E6%9E%97%E7%89%A7%E6%B8%94%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%8C%96%E5%B7%A5%22%2C%22displayValue%22%3A%22%E5%8C%96%E5%B7%A5%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%8C%BB%E8%8D%AF%E7%94%9F%E7%89%A9%22%2C%22displayValue%22%3A%22%E5%8C%BB%E8%8D%AF%E7%94%9F%E7%89%A9%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%95%86%E4%B8%9A%E8%B4%B8%E6%98%93%22%2C%22displayValue%22%3A%22%E5%95%86%E4%B8%9A%E8%B4%B8%E6%98%93%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%9B%BD%E9%98%B2%E5%86%9B%E5%B7%A5%22%2C%22displayValue%22%3A%22%E5%9B%BD%E9%98%B2%E5%86%9B%E5%B7%A5%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%22%2C%22displayValue%22%3A%22%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%BB%BA%E7%AD%91%E6%9D%90%E6%96%99%2F%E5%BB%BA%E7%AD%91%E5%BB%BA%E6%9D%90%22%2C%22displayValue%22%3A%22%E5%BB%BA%E7%AD%91%E6%9D%90%E6%96%99%2F%E5%BB%BA%E7%AD%91%E5%BB%BA%E6%9D%90%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%BB%BA%E7%AD%91%E8%A3%85%E9%A5%B0%22%2C%22displayValue%22%3A%22%E5%BB%BA%E7%AD%91%E8%A3%85%E9%A5%B0%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%88%BF%E5%9C%B0%E4%BA%A7%22%2C%22displayValue%22%3A%22%E6%88%BF%E5%9C%B0%E4%BA%A7%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9C%89%E8%89%B2%E9%87%91%E5%B1%9E%22%2C%22displayValue%22%3A%22%E6%9C%89%E8%89%B2%E9%87%91%E5%B1%9E%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9C%BA%E6%A2%B0%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E6%9C%BA%E6%A2%B0%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B1%BD%E8%BD%A6%2F%E4%BA%A4%E8%BF%90%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E6%B1%BD%E8%BD%A6%2F%E4%BA%A4%E8%BF%90%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%94%B5%E5%AD%90%22%2C%22displayValue%22%3A%22%E7%94%B5%E5%AD%90%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%94%B5%E6%B0%94%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E7%94%B5%E6%B0%94%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%BA%BA%E7%BB%87%E6%9C%8D%E8%A3%85%22%2C%22displayValue%22%3A%22%E7%BA%BA%E7%BB%87%E6%9C%8D%E8%A3%85%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%BB%BC%E5%90%88%22%2C%22displayValue%22%3A%22%E7%BB%BC%E5%90%88%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E8%AE%A1%E7%AE%97%E6%9C%BA%22%2C%22displayValue%22%3A%22%E8%AE%A1%E7%AE%97%E6%9C%BA%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E8%BD%BB%E5%B7%A5%E5%88%B6%E9%80%A0%22%2C%22displayValue%22%3A%22%E8%BD%BB%E5%B7%A5%E5%88%B6%E9%80%A0%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%80%9A%E4%BF%A1%22%2C%22displayValue%22%3A%22%E9%80%9A%E4%BF%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%87%87%E6%8E%98%22%2C%22displayValue%22%3A%22%E9%87%87%E6%8E%98%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%92%A2%E9%93%81%22%2C%22displayValue%22%3A%22%E9%92%A2%E9%93%81%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%93%B6%E8%A1%8C%22%2C%22displayValue%22%3A%22%E9%93%B6%E8%A1%8C%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%9D%9E%E9%93%B6%E9%87%91%E8%9E%8D%22%2C%22displayValue%22%3A%22%E9%9D%9E%E9%93%B6%E9%87%91%E8%9E%8D%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%A3%9F%E5%93%81%E9%A5%AE%E6%96%99%22%2C%22displayValue%22%3A%22%E9%A3%9F%E5%93%81%E9%A5%AE%E6%96%99%22%2C%22selected%22%3Afalse%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"st_cond","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%AD%A3%E5%B8%B8%22%2C%22displayValue%22%3A%22%E6%AD%A3%E5%B8%B8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22ST%22%2C%22displayValue%22%3A%22ST%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22*ST%22%2C%22displayValue%22%3A%22*ST%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9A%82%E5%81%9C%E4%B8%8A%E5%B8%82%22%2C%22displayValue%22%3A%22%E6%9A%82%E5%81%9C%E4%B8%8A%E5%B8%82%22%2C%22selected%22%3Afalse%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_left_data","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-8587"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8587","OutputType":null},{"Name":"left_data","NodeId":"-8587","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":20,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-8596","ModuleId":"BigQuantSpace.chinaa_stock_filter.chinaa_stock_filter-v1","ModuleParameters":[{"Name":"index_constituent_cond","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%8150%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%8150%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B2%AA%E6%B7%B1300%22%2C%22displayValue%22%3A%22%E6%B2%AA%E6%B7%B1300%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81500%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81500%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81800%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81800%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%81180%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%81180%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81100%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81100%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B7%B1%E8%AF%81100%22%2C%22displayValue%22%3A%22%E6%B7%B1%E8%AF%81100%22%2C%22selected%22%3Afalse%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"board_cond","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B7%B1%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22displayValue%22%3A%22%E6%B7%B1%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%88%9B%E4%B8%9A%E6%9D%BF%22%2C%22displayValue%22%3A%22%E5%88%9B%E4%B8%9A%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"industry_cond","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%BA%A4%E9%80%9A%E8%BF%90%E8%BE%93%22%2C%22displayValue%22%3A%22%E4%BA%A4%E9%80%9A%E8%BF%90%E8%BE%93%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%BC%91%E9%97%B2%E6%9C%8D%E5%8A%A1%22%2C%22displayValue%22%3A%22%E4%BC%91%E9%97%B2%E6%9C%8D%E5%8A%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%BC%A0%E5%AA%92%2F%E4%BF%A1%E6%81%AF%E6%9C%8D%E5%8A%A1%22%2C%22displayValue%22%3A%22%E4%BC%A0%E5%AA%92%2F%E4%BF%A1%E6%81%AF%E6%9C%8D%E5%8A%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%85%AC%E7%94%A8%E4%BA%8B%E4%B8%9A%22%2C%22displayValue%22%3A%22%E5%85%AC%E7%94%A8%E4%BA%8B%E4%B8%9A%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%86%9C%E6%9E%97%E7%89%A7%E6%B8%94%22%2C%22displayValue%22%3A%22%E5%86%9C%E6%9E%97%E7%89%A7%E6%B8%94%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%8C%96%E5%B7%A5%22%2C%22displayValue%22%3A%22%E5%8C%96%E5%B7%A5%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%8C%BB%E8%8D%AF%E7%94%9F%E7%89%A9%22%2C%22displayValue%22%3A%22%E5%8C%BB%E8%8D%AF%E7%94%9F%E7%89%A9%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%95%86%E4%B8%9A%E8%B4%B8%E6%98%93%22%2C%22displayValue%22%3A%22%E5%95%86%E4%B8%9A%E8%B4%B8%E6%98%93%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%9B%BD%E9%98%B2%E5%86%9B%E5%B7%A5%22%2C%22displayValue%22%3A%22%E5%9B%BD%E9%98%B2%E5%86%9B%E5%B7%A5%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%22%2C%22displayValue%22%3A%22%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%BB%BA%E7%AD%91%E6%9D%90%E6%96%99%2F%E5%BB%BA%E7%AD%91%E5%BB%BA%E6%9D%90%22%2C%22displayValue%22%3A%22%E5%BB%BA%E7%AD%91%E6%9D%90%E6%96%99%2F%E5%BB%BA%E7%AD%91%E5%BB%BA%E6%9D%90%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%BB%BA%E7%AD%91%E8%A3%85%E9%A5%B0%22%2C%22displayValue%22%3A%22%E5%BB%BA%E7%AD%91%E8%A3%85%E9%A5%B0%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%88%BF%E5%9C%B0%E4%BA%A7%22%2C%22displayValue%22%3A%22%E6%88%BF%E5%9C%B0%E4%BA%A7%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9C%89%E8%89%B2%E9%87%91%E5%B1%9E%22%2C%22displayValue%22%3A%22%E6%9C%89%E8%89%B2%E9%87%91%E5%B1%9E%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9C%BA%E6%A2%B0%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E6%9C%BA%E6%A2%B0%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B1%BD%E8%BD%A6%2F%E4%BA%A4%E8%BF%90%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E6%B1%BD%E8%BD%A6%2F%E4%BA%A4%E8%BF%90%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%94%B5%E5%AD%90%22%2C%22displayValue%22%3A%22%E7%94%B5%E5%AD%90%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%94%B5%E6%B0%94%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E7%94%B5%E6%B0%94%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%BA%BA%E7%BB%87%E6%9C%8D%E8%A3%85%22%2C%22displayValue%22%3A%22%E7%BA%BA%E7%BB%87%E6%9C%8D%E8%A3%85%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%BB%BC%E5%90%88%22%2C%22displayValue%22%3A%22%E7%BB%BC%E5%90%88%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E8%AE%A1%E7%AE%97%E6%9C%BA%22%2C%22displayValue%22%3A%22%E8%AE%A1%E7%AE%97%E6%9C%BA%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E8%BD%BB%E5%B7%A5%E5%88%B6%E9%80%A0%22%2C%22displayValue%22%3A%22%E8%BD%BB%E5%B7%A5%E5%88%B6%E9%80%A0%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%80%9A%E4%BF%A1%22%2C%22displayValue%22%3A%22%E9%80%9A%E4%BF%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%87%87%E6%8E%98%22%2C%22displayValue%22%3A%22%E9%87%87%E6%8E%98%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%92%A2%E9%93%81%22%2C%22displayValue%22%3A%22%E9%92%A2%E9%93%81%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%93%B6%E8%A1%8C%22%2C%22displayValue%22%3A%22%E9%93%B6%E8%A1%8C%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%9D%9E%E9%93%B6%E9%87%91%E8%9E%8D%22%2C%22displayValue%22%3A%22%E9%9D%9E%E9%93%B6%E9%87%91%E8%9E%8D%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%A3%9F%E5%93%81%E9%A5%AE%E6%96%99%22%2C%22displayValue%22%3A%22%E9%A3%9F%E5%93%81%E9%A5%AE%E6%96%99%22%2C%22selected%22%3Afalse%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"st_cond","Value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%AD%A3%E5%B8%B8%22%2C%22displayValue%22%3A%22%E6%AD%A3%E5%B8%B8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22ST%22%2C%22displayValue%22%3A%22ST%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22*ST%22%2C%22displayValue%22%3A%22*ST%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9A%82%E5%81%9C%E4%B8%8A%E5%B8%82%22%2C%22displayValue%22%3A%22%E6%9A%82%E5%81%9C%E4%B8%8A%E5%B8%82%22%2C%22selected%22%3Afalse%7D%5D%7D","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_left_data","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-8596"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8596","OutputType":null},{"Name":"left_data","NodeId":"-8596","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":21,"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='189,-197,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='11,-3,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='668,-392,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-43' Position='610,619,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='786,722,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1047,-203,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='376,467,200,200'/><NodePosition Node='-86' Position='1078,418,200,200'/><NodePosition Node='-8531' Position='357,-1,200,200'/><NodePosition Node='-8538' Position='385,280,200,200'/><NodePosition Node='-8547' Position='1208,16,200,200'/><NodePosition Node='-8554' Position='1081,327,200,200'/><NodePosition Node='-8566' Position='913,864,200,200'/><NodePosition Node='-8587' Position='353,120,200,200'/><NodePosition Node='-8596' Position='1235,182,200,200'/></NodePositions><NodeGroups /></DataV1>"},"IsDraft":true,"ParentExperimentId":null,"WebService":{"IsWebServiceExperiment":false,"Inputs":[],"Outputs":[],"Parameters":[{"Name":"交易日期","Value":"","ParameterDefinition":{"Name":"交易日期","FriendlyName":"交易日期","DefaultValue":"","ParameterType":"String","HasDefaultValue":true,"IsOptional":true,"ParameterRules":[],"HasRules":false,"MarkupType":0,"CredentialDescriptor":null}}],"WebServiceGroupId":null,"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions></NodePositions><NodeGroups /></DataV1>"},"DisableNodesUpdate":false,"Category":"user","Tags":[],"IsPartialRun":true}
    In [1]:
    # 本代码由可视化策略环境自动生成 2019年12月30日 16:33
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    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)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的4只
        stock_count = 4
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 0.05
        context.options['hold_days'] = 5
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_handle_data_bigquant_run(context, data):
        
        from sklearn.preprocessing import maxabs_scale
        from keras.models import load_model
        
        # 按日期过滤得到今日的预测数据
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
    
        # 1. 资金分配
        # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金
        # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)
        is_staging = context.trading_day_index < context.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)
        cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
        positions = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
    
        
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
        ss=[]
        if not is_staging and cash_for_sell > 0:
            equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
            instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                    lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
            # print('rank order for sell %s' % instruments)
            
            for instrument in instruments:
                context.order_target(context.symbol(instrument), 0)
                cash_for_sell -= positions[instrument]
                ss.append(instrument)
                if cash_for_sell <= 0:
                    break
    
        #---------------------START--------------------------
        
        today_date = data.current_dt.strftime('%Y-%m-%d')
        buy_cash_weights = context.stock_weights
        test_input = []
        start_date= (pd.to_datetime(today_date) - datetime.timedelta(days=20)).strftime('%Y-%m-%d')
        fields = ['open','close',  'high', 'low','amount','volume'] 
        buy_instruments=list(ranker_prediction.instrument[:len(buy_cash_weights)])
        data2 = DataSource('bar1d_CN_STOCK_A').read(buy_instruments, start_date, today_date, fields)
        for instrument in buy_instruments:
            tdata2 = data2[data2.instrument==instrument][fields]
            b = maxabs_scale(tdata2[len(tdata2)-5:])
            test_input.append(b)
            
        test_x = np.array(test_input)
        ds = DataSource(context.modid)
        model_new = load_model(ds.open_temp_path())
        ds.close_temp_path()
        ds11 = DataSource(context.modid11)
        model_new11 = load_model(ds11.open_temp_path())
        ds11.close_temp_path()
        predictions = model_new.predict(test_x)
        predictions11 = model_new11.predict(test_x)
        cc=predictions+predictions11
        dd=np.concatenate((predictions,predictions11),axis=0).reshape(8,1)
        jishu=1
        for i in range(len(dd)):
            if dd[i]<0:
                jishu=jishu-0.1
        jishu=np.round(jishu,2)
        fieldsu=['pe_ttm','pe_lyr','pb_lf','ps_ttm']
        pp=DataSource('market_value_CN_STOCK_A').read(buy_instruments, today_date, today_date, fieldsu)
        ppd=[]
        for instrument in pp.instrument:
            ppd.append(data.current(context.symbol(instrument), 'price'))
        pp['price']=ppd
        pp=pp.set_index('instrument')
        print(today_date,jishu)
        print(dd.reshape(2,4))
        print(buy_instruments)
        print(pp.drop('date',axis=1))
        if len(ss)>0:
            print(ss)
        
        
        
        #------------------------END---------------------------
       
        
        
        # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
        #buy_cash_weights = context.stock_weights
        max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
        for i, instrument in enumerate(buy_instruments):
            cash = cash_for_buy * buy_cash_weights[i]
            if cash > max_cash_per_instrument - positions.get(instrument, 0):
                # 确保股票持仓量不会超过每次股票最大的占用资金量
                cash = max_cash_per_instrument - positions.get(instrument, 0)
            if cash > 0 :
                if cc[i]>0:
                    context.order_value(context.symbol(instrument), jishu*cash)
                else:
                    context.order_value(context.symbol(instrument), 0.5*jishu*cash)
            
            
               
    # 回测引擎:准备数据,只执行一次
    def m19_prepare_bigquant_run(context):
       #---------------------START--------------------------
        seq_len=5    #每个input的长度
        # 导入包
        from keras.layers.core import  Activation, Dropout
        from keras import optimizers
        from sklearn.preprocessing import maxabs_scale
        from keras.layers import Input, Dense, LSTM
        from keras.models import Model
        # 基础参数配置
        instrument=['000001.HIX','399001.ZIX']
        #设置用于训练和回测的开始/结束日期
        train_length=seq_len*10
        jc=train_length-2*seq_len
        start_date= (pd.to_datetime(context.start_date) - datetime.timedelta(days=2*train_length)).strftime('%Y-%m-%d') # 多取几天的数据,这里取5倍
        fields = ['open','close',  'high', 'low','amount','volume']  # features因子
        batch = 10#整数,指定进行梯度下降时每个batch包含的样本数,训练时一个batch的样本会被计算一次梯度下降,使目标函数优化一步
        
        # 数据导入以及初步处理
        data = DataSource('bar1d_index_CN_STOCK_A').read(instrument, start_date, context.start_date, fields)
        data1=data[data.instrument==instrument[0]]
        data11=data[data.instrument==instrument[1]]
        data1=data1[len(data1)-train_length:]
        data11=data11[len(data11)-train_length:]
        data1['return'] = data1['close'].shift(-5) / data1['open'].shift(-1) - 1 #计算未来5日收益率(未来第五日的收盘价/明日的开盘价)
        data11['return'] = data11['close'].shift(-5) / data11['open'].shift(-1) - 1
        data1.fillna(value=0)
        data11.fillna(value=0)
        data1['return'] = data1['return']*10  # 适当增大return范围,利于LSTM模型训练
        data11['return'] = data11['return']*10
        data1.reset_index(drop=True, inplace=True)
        data11.reset_index(drop=True, inplace=True)
        scaledata = data1[fields]
        scaledata11 = data11[fields]
        traindata = data1['return']
        traindata11 = data11['return']
        # 数据处理:设定每个input(series×6features)以及数据标准化
        train_input = []
        train_input11 = []
        train_output = []
        train_output11 = []
        
        for i in range(seq_len-1, len(traindata)):
            a = maxabs_scale(scaledata[i+1-seq_len:i+1])
            train_input.append(a)
            c = traindata[i]
            train_output.append(c)
        
    
        for i in range(seq_len-1, len(traindata11)):
            a = maxabs_scale(scaledata11[i+1-seq_len:i+1])
            train_input11.append(a)
            c = traindata11[i]
            train_output11.append(c)
        # LSTM接受数组类型的输入
        train_x = np.array(train_input)[:jc]
        train_x11 = np.array(train_input11)[:jc]
        train_y = np.array(train_output)[:jc]
        train_y11 = np.array(train_output11)[:jc]
        
       
        # 自定义激活函数
        # 构建神经网络层 1层LSTM层+3层Dense层
        # 用于1个输入情况
        lstm_input = Input(shape=(seq_len,len(fields)), name='lstm_input')
        lstm_output = LSTM(32, activation='tanh', dropout_W=0.2, dropout_U=0.1)(lstm_input)
        Dense_output_1 = Dense(16, activation='linear')(lstm_output)
        Dense_output_2 = Dense(4, activation='linear')(Dense_output_1)
        predictions = Dense(1, activation='tanh')(Dense_output_2)
        model = Model(input=lstm_input, output=predictions)
        model.compile(optimizer='adam', loss='mse', metrics=['mse'])
        model.fit(train_x, train_y, batch_size=batch, nb_epoch=15, verbose=0)
        model_ds = DataSource()
        model.save(model_ds.open_temp_path())
        model_ds.close_temp_path()
        context.modid=model_ds.id
        
        lstm_input11 = Input(shape=(seq_len,len(fields)), name='lstm_input11')
        lstm_output11 = LSTM(32, activation='tanh', dropout_W=0.2, dropout_U=0.1)(lstm_input11)
        Dense_output_111 = Dense(16, activation='linear')(lstm_output11)
        Dense_output_211 = Dense(4, activation='linear')(Dense_output_111)
        predictions11 = Dense(1, activation='tanh')(Dense_output_211)
        model11 = Model(input=lstm_input11, output=predictions11)
        model11.compile(optimizer='adam', loss='mse', metrics=['mse'])
        model11.fit(train_x11, train_y11, batch_size=batch, nb_epoch=15, verbose=0)
        model_ds11 = DataSource()
        model11.save(model_ds11.open_temp_path())
        model_ds11.close_temp_path()
        context.modid11=model_ds11.id
        #------------------------END---------------------------
       
    
    m1 = M.instruments.v2(
        start_date='2014-01-01',
        end_date='2018-06-01',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m2 = M.advanced_auto_labeler.v2(
        instruments=m1.data,
        label_expr="""# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 {{web_host_url}}docs/data_history_data.html
    #   添加benchmark_前缀,可使用对应的benchmark数据
    # 2. 可用操作符和函数见 `表达式引擎 <{{web_host_url}}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))
    
    # 将分数映射到分类,这里使用1000个分类
    all_wbins(label, 1000)
    
    # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
    where(shift(high, -1) == shift(low, -1), NaN, label)
    """,
        start_date='',
        end_date='',
        benchmark='000300.SHA',
        drop_na_label=True,
        cast_label_int=True
    )
    
    m3 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    ta_mfi_14_0
    ta_adx_14_0
    where(ta_cci_14_0>100,delta(ta_cci_14_0,1),where(ta_cci_14_0<-100,delta(ta_cci_14_0,1),0))
    arctan(avg_turn_5*return_5)
    ta_willr_14_0
    arctan(where(ta_macd_macd_12_26_9_0>0,swing_volatility_5_0,swing_volatility_5_0*-1))
    arctan(avg_mf_net_amount_5/avg_amount_5)
    where(delta(ta_macd_macd_12_26_9_0,1)>0,ta_aroon_up_14_0*ta_aroon_down_14_0,ta_aroon_up_14_0*ta_aroon_down_14_0*-1)
    arcsin(where(delta(ta_macd_macd_12_26_9_0,1)>0,(1-turn_5*0.01)*(1-turn_0*0.01)*(1-turn_1*0.01)*(1-turn_2*0.01)*(1-turn_3*0.01)*(1-turn_4*0.01),(1-turn_5*0.01)*(1-turn_0*0.01)*(1-turn_1*0.01)*(1-turn_2*0.01)*(1-turn_3*0.01)*(1-turn_4*0.01)*-1))
    arctan2((close_0-close_1),(close_1-close_2))"""
    )
    
    m15 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=150
    )
    
    m20 = M.chinaa_stock_filter.v1(
        input_data=m15.data,
        index_constituent_cond=['全部'],
        board_cond=['全部'],
        industry_cond=['全部'],
        st_cond=['正常'],
        output_left_data=False
    )
    
    m16 = M.derived_feature_extractor.v3(
        input_data=m20.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False
    )
    
    m7 = M.join.v3(
        data1=m2.data,
        data2=m16.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m13 = M.dropnan.v1(
        input_data=m7.data
    )
    
    m6 = M.stock_ranker_train.v5(
        training_ds=m13.data,
        features=m3.data,
        learning_algorithm='排序',
        number_of_leaves=50,
        minimum_docs_per_leaf=500,
        number_of_trees=30,
        learning_rate=0.1,
        max_bins=1023,
        feature_fraction=1,
        m_lazy_run=False
    )
    
    m9 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2018-06-01'),
        end_date=T.live_run_param('trading_date', '2018-07-01'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m17 = M.general_feature_extractor.v7(
        instruments=m9.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=150
    )
    
    m21 = M.chinaa_stock_filter.v1(
        input_data=m17.data,
        index_constituent_cond=['全部'],
        board_cond=['全部'],
        industry_cond=['全部'],
        st_cond=['正常'],
        output_left_data=False
    )
    
    m18 = M.derived_feature_extractor.v3(
        input_data=m21.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False
    )
    
    m14 = M.dropnan.v1(
        input_data=m18.data
    )
    
    m8 = M.stock_ranker_predict.v5(
        model=m6.model,
        data=m14.data,
        m_lazy_run=False
    )
    
    m19 = M.trade.v4(
        instruments=m9.data,
        options_data=m8.predictions,
        start_date='',
        end_date='',
        initialize=m19_initialize_bigquant_run,
        handle_data=m19_handle_data_bigquant_run,
        prepare=m19_prepare_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='close',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark='000300.HIX'
    )
    
    Using TensorFlow backend.
    
    2018-06-01 0.3
    [[-0.03551475 -0.00195318  0.01487001 -0.00277396]
     [-0.06279154 -0.05547398 -0.06769198 -0.04985318]]
    ['300312.SZA', '002509.SZA', '002592.SZA', '600666.SHA']
                    pe_lyr     pb_lf      pe_ttm    ps_ttm      price
    instrument                                                       
    002509.SZA   14.104595  1.679078   14.101110  2.419423  49.660625
    002592.SZA   34.366741  2.166334   45.417782  6.517274  41.416321
    300312.SZA  -16.835560  3.699415  -18.840071  8.175104  22.617758
    600666.SHA  115.030754  2.356386  104.681473  4.914660  58.448696
    2018-06-04 0.3
    [[-0.01150201 -0.01464651 -0.03604876  0.01447868]
     [-0.05216324 -0.05433258 -0.06503359 -0.07301509]]
    ['002377.SZA', '601002.SHA', '300312.SZA', '603595.SHA']
                    pe_lyr     pb_lf     pe_ttm    ps_ttm      price
    instrument                                                      
    300312.SZA  -16.181095  3.555604 -18.107681  7.857306  21.738516
    601002.SHA   43.825703  2.596572  44.236534  2.045448   8.729633
    603595.SHA   44.768818  9.639879  31.834017  8.377281  76.210861
    002377.SZA  182.690506  1.621743  61.623230  2.264781  35.942574
    2018-06-05 0.3
    [[ 0.0148481  -0.05406129 -0.04098991 -0.04311452]
     [-0.07706798 -0.06773745 -0.06187478 -0.06147069]]
    ['300316.SZA', '300325.SZA', '002697.SZA', '002694.SZA']
                    pe_lyr     pb_lf      pe_ttm    ps_ttm       price
    instrument                                                        
    300325.SZA  155.137039  2.613300  121.113220  1.940522   39.444115
    002697.SZA   47.826370  3.364256   43.820442  1.119644   41.068878
    002694.SZA   32.015907  3.375411   32.205318  1.727941   24.990253
    300316.SZA   44.044235  4.721909   36.916138  7.937764  120.617317
    2018-06-06 0.3
    [[-0.04715245 -0.00985971  0.00740894 -0.03751333]
     [-0.05453086 -0.06919239 -0.06650097 -0.06094884]]
    ['600007.SHA', '000610.SZA', '002499.SZA', '002293.SZA']
                   pe_lyr     pb_lf     pe_ttm    ps_ttm      price
    instrument                                                     
    002499.SZA  55.189579  2.992224  37.086121  2.897202  31.233763
    002293.SZA  29.745514  3.845000  27.222876  2.665098  98.987038
    000610.SZA -91.830444  2.214084 -89.583511  2.370593  21.658983
    600007.SHA  25.340473  2.534528  23.732548  5.468160  27.389956
    2018-06-07 0.2
    [[-0.03820531 -0.0227287  -0.02713558 -0.03442345]
     [-0.05192012 -0.04894819 -0.05415495 -0.05453958]]
    ['000927.SZA', '000869.SZA', '601588.SHA', '603589.SHA']
                   pe_lyr      pb_lf     pe_ttm     ps_ttm       price
    instrument                                                        
    603589.SHA  34.863331   7.016648  31.430040  10.164567   66.115631
    000869.SZA  29.599270   3.255506  30.706158   6.309363  196.672119
    000927.SZA  -4.006081 -39.841125  -4.113469   4.450670    6.543318
    601588.SHA  13.197509   1.137019  14.722776   1.063788    4.989034
    2018-06-08 0.3
    [[-0.0380542  -0.03110021 -0.02339117  0.00732719]
     [-0.06557018 -0.05458695 -0.0617073  -0.06110158]]
    ['002684.SZA', '002250.SZA', '002499.SZA', '002524.SZA']
                    pe_lyr     pb_lf      pe_ttm    ps_ttm      price
    instrument                                                       
    002499.SZA   54.508228  2.955282   36.628265  2.861434  30.848160
    002684.SZA  -33.751869  1.668774  -38.861351  1.115264  53.030045
    002250.SZA   44.101265  1.560763   49.067810  2.084517  56.828949
    002524.SZA  508.314758  3.462000  392.846161  4.735024  25.085524
    2018-06-11 0.2
    [[-0.01685448 -0.07263261 -0.04862946 -0.0390939 ]
     [-0.06407281 -0.07060619 -0.06655323 -0.0632828 ]]
    ['600438.SHA', '000610.SZA', '601012.SHA', '300425.SZA']
                   pe_lyr     pb_lf     pe_ttm    ps_ttm       price
    instrument                                                      
    601012.SHA  13.086985  3.241892  12.717344  2.720816  130.070312
    300425.SZA  31.285057  2.053757  27.721552  3.380500   34.554295
    000610.SZA -87.366463  2.106455 -85.228760  2.255356   20.606115
    600438.SHA  13.738509  2.121798  13.374868  1.019968   75.859802
    2018-06-12 0.2
    [[-0.06000231 -0.01969507 -0.01020973 -0.01034403]
     [-0.06652657 -0.05878654 -0.05443319 -0.05777626]]
    ['000812.SZA', '603301.SHA', '300071.SZA', '002413.SZA']
                    pe_lyr     pb_lf     pe_ttm    ps_ttm      price
    instrument                                                      
    002413.SZA   52.986145  1.803758  52.572388  8.355890  27.897308
    300071.SZA   -9.720105  2.937353 -10.046245  0.781546  44.186203
    000812.SZA  103.260834  2.077394  85.430634  3.582611  26.876461
    603301.SHA   43.681026  5.249544  44.529724  4.111374  53.189999
    2018-06-13 0.4
    [[ 0.00472329 -0.04349094  0.01890346 -0.00307379]
     [-0.05963608 -0.06125784 -0.05419057 -0.05167379]]
    ['002499.SZA', '000812.SZA', '002684.SZA', '300071.SZA']
                   pe_lyr     pb_lf     pe_ttm    ps_ttm      price
    instrument                                                     
    300071.SZA  -9.230427  2.789376  -9.540136  0.742174  41.960197
    002684.SZA -28.338036  1.401101 -32.627953  0.936374  44.523972
    002499.SZA  50.874348  2.758264  34.186382  2.670672  28.791616
    000812.SZA  99.300148  1.997713  82.153839  3.445196  25.845583
    2018-06-14 0.5
    [[ 0.00774729 -0.01128624  0.02250063  0.00432208]
     [-0.06459481 -0.05832153 -0.06959446 -0.05305226]]
    ['002451.SZA', '002499.SZA', '002045.SZA', '002086.SZA']
                   pe_lyr     pb_lf     pe_ttm     ps_ttm      price
    instrument                                                      
    002086.SZA  40.727547  1.428731  40.617115   6.386154  27.568989
    002499.SZA  50.692654  2.748413  34.064289   2.661134  28.688789
    002451.SZA  88.913536  7.928653  79.560692  10.361463  36.710178
    002045.SZA  23.908888  2.209880  25.274418   0.734641  42.328117
    2018-06-15 0.3
    [[-0.00296406  0.00011041 -0.04196117 -0.0184069 ]
     [-0.05695069 -0.05790649 -0.06364432 -0.06008143]]
    ['002499.SZA', '002694.SZA', '300411.SZA', '600311.SHA']
                    pe_lyr     pb_lf      pe_ttm     ps_ttm      price
    instrument                                                        
    600311.SHA  786.541199  2.438160  281.918549  12.324224  13.677401
    002694.SZA   27.292248  2.877399   27.453714   1.472999  21.303167
    002499.SZA   47.422157  2.571096   31.866592   2.489448  26.837898
    300411.SZA   54.077854  1.125765   47.798775   7.815929  29.313251
    2018-06-19 0.5
    [[ 0.02057813  0.0202272   0.02157215 -0.0147317 ]
     [-0.04684034 -0.05947249 -0.06067055 -0.06767514]]
    ['600385.SHA', '300676.SZA', '002428.SZA', '000757.SZA']
                    pe_lyr      pb_lf      pe_ttm     ps_ttm       price
    instrument                                                          
    002428.SZA  580.251099   3.307675  562.473938  10.121836   39.769798
    600385.SHA -183.802155  21.011171 -190.542450  46.160973   19.118372
    300676.SZA  104.946831  10.193018  103.303314  18.785112  104.657555
    000757.SZA   53.605541   3.985727   53.043655   3.958270   22.496513
    2018-06-20 0.3
    [[-0.02125069  0.02001327 -0.01156555 -0.00128364]
     [-0.06731786 -0.0720757  -0.05427275 -0.05952602]]
    ['000757.SZA', '300225.SZA', '000709.SZA', '603081.SHA']
                   pe_lyr     pb_lf     pe_ttm    ps_ttm      price
    instrument                                                     
    000757.SZA  52.742481  3.921556  52.189644  3.894541  22.134315
    000709.SZA  17.823689  0.701114  21.021564  0.306412  28.903790
    603081.SHA  24.780550  3.729437  24.534731  3.259124  14.233078
    300225.SZA  52.044857  2.744158  55.665253  3.101141  40.972591
    2018-06-21 0.4
    [[ 0.01080635 -0.0031498  -0.01607881  0.02119812]
     [-0.05523635 -0.05520219 -0.05660189 -0.05388697]]
    ['000925.SZA', '603703.SHA', '600715.SHA', '300167.SZA']
                    pe_lyr     pb_lf      pe_ttm    ps_ttm      price
    instrument                                                       
    000925.SZA   54.086388  1.413995   42.357544  1.462709  17.801115
    600715.SHA   25.945681  1.549246   38.053825  5.665083  23.308775
    300167.SZA -230.958923  1.912041 -266.668274  2.527238  31.380880
    603703.SHA   77.871727  3.619645  343.658447  2.226242  20.719568
    2018-06-22 0.5
    [[ 0.00120231  0.03087315 -0.0159636   0.01820102]
     [-0.06222457 -0.07114026 -0.0553214  -0.07350993]]
    ['300225.SZA', '300392.SZA', '300192.SZA', '600130.SHA']
                    pe_lyr     pb_lf      pe_ttm    ps_ttm      price
    instrument                                                       
    600130.SHA  -16.395327  2.946371  -18.252911  1.860188  19.659576
    300392.SZA  -23.250881  6.713892  -27.234158  1.857501  50.085842
    300225.SZA   50.753670  2.676078   54.284245  3.024204  39.956097
    300192.SZA  367.726654  2.950843  243.435928  3.489212  29.889874
    2018-06-25 0.5
    [[ 0.01547527  0.04022189 -0.06608266  0.01067127]
     [-0.06759865 -0.06259662 -0.06202731 -0.06920761]]
    ['300128.SZA', '002692.SZA', '300057.SZA', '300310.SZA']
                   pe_lyr     pb_lf     pe_ttm    ps_ttm      price
    instrument                                                     
    002692.SZA  34.625778  1.716120  35.376747  0.977226  14.964515
    300057.SZA  32.304073  1.080431  32.096542  0.732579  12.435719
    300310.SZA  20.791441  1.352921  20.592415  1.731577  41.431675
    300128.SZA  63.419468  1.821811  61.986095  1.210218  33.767891
    2018-06-26 0.4
    [[-0.01889863 -0.00942096  0.00542018  0.03740305]
     [-0.06479767 -0.06488802 -0.05309216 -0.07264291]]
    ['300128.SZA', '600130.SHA', '600621.SHA', '603555.SHA']
                   pe_lyr     pb_lf     pe_ttm    ps_ttm        price
    instrument                                                       
    300128.SZA  69.780121  2.004530  68.202988  1.331597    37.154640
    603555.SHA  46.113895  3.217887  45.581306  2.186775    12.682899
    600130.SHA -15.188308  2.729460 -16.909140  1.723242    18.212246
    600621.SHA  13.285329  1.575195  13.103971  4.908861  2734.818115
    2018-06-27 0.3
    [[-0.01577886 -0.03922733 -0.04723353  0.01558333]
     [-0.06306383 -0.06244818 -0.06491377 -0.0516483 ]]
    ['000063.SZA', '000976.SZA', '600130.SHA', '002114.SZA']
                   pe_lyr     pb_lf     pe_ttm    ps_ttm       price
    instrument                                                      
    600130.SHA -15.138016  2.720422 -16.853148  1.717536   18.151941
    000063.SZA  11.793740  1.361179  10.686289  0.481247  202.869049
    002114.SZA  54.221245  1.657991  52.297215  1.776977   16.867599
    000976.SZA  16.893873  2.030885  16.748484  5.242513   19.211287
    ['002684.SZA']
    2018-06-28 0.4
    [[ 0.02444555 -0.05094046  0.01649902 -0.03154628]
     [-0.0607321  -0.06005595 -0.04949732 -0.05749599]]
    ['300676.SZA', '603801.SHA', '600365.SHA', '300199.SZA']
                    pe_lyr     pb_lf      pe_ttm     ps_ttm       price
    instrument                                                         
    300676.SZA   92.765678  9.009917   91.312927  16.604731   92.509979
    603801.SHA   30.514538  4.374947   29.287788   3.154296   45.113529
    300199.SZA   38.609909  3.373722   36.423782   9.726467  113.451591
    600365.SHA  287.614410  2.520692  265.802185   1.788073   11.489533
    ['300225.SZA']
    2018-06-29 0.4
    [[ 0.02882163 -0.06114986  0.04345901 -0.04745825]
     [-0.06978126 -0.07213829 -0.06483734 -0.06144017]]
    ['002584.SZA', '002470.SZA', '000511.SZA', '600806.SHA']
                   pe_lyr     pb_lf     pe_ttm    ps_ttm      price
    instrument                                                     
    600806.SHA  -1.943944 -7.103905  -1.960665  1.194015   4.008263
    002470.SZA  30.364704  2.242708  26.167088  1.034855  29.372227
    000511.SZA  11.825308  0.908138   6.610736  0.270216  12.828396
    002584.SZA  48.460979  2.565907  47.030476  1.299392  19.935785
    ['300312.SZA', '300411.SZA']
    
    • 收益率2.48%
    • 年化收益率36.16%
    • 基准收益率-7.66%
    • 阿尔法0.72
    • 贝塔0.43
    • 夏普比率2.16
    • 胜率1.0
    • 盈亏比0.0
    • 收益波动率13.29%
    • 信息比率0.53
    • 最大回撤3.3%

    (fsm) #4

    怎么解决的,完全没看明白.出现这种错误不是keras版本不对吗?没看到哪里修改了


    (ahxdct) #5

    这是策略代码,问题没有解决。


    (fsm) #6

    平台使用的是tensorflow 2.0,但是keras是2.2.4.需要安装更高版本的keras才行
    import tensorflow as tf print(tf.__version__) import keras as k print(k.__version__)


    (达达) #7

    能分享一下报错的问题策略么?方便调试一下


    (ahxdct) #8

    策略在上面


    (达达) #9

    可以试试tensorflow.keras


    (Fengshu) #10

    希望把服务器的tensorflow调回2.0以下的版本,2.0版本用着太不舒服了 跟1有很大差别