复制链接
克隆策略

    {"description":"实验创建于2022/4/8","graph":{"edges":[{"to_node_id":"-1290:features","from_node_id":"-1278:data"},{"to_node_id":"-2427:features","from_node_id":"-1278:data"},{"to_node_id":"-1290:input_data","from_node_id":"-1283:data"},{"to_node_id":"-1079:input_data","from_node_id":"-1283:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","from_node_id":"-1290:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","from_node_id":"-1079:data"},{"to_node_id":"-186:input_data","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:model"},{"to_node_id":"-3135:options_data","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"to_node_id":"-2427:input_data","from_node_id":"-2411:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","from_node_id":"-2427:data"},{"to_node_id":"-760:input","from_node_id":"-512:data"},{"to_node_id":"-2411:instruments","from_node_id":"-760:instrument_list"},{"to_node_id":"-3135:instruments","from_node_id":"-760:instrument_list"},{"to_node_id":"-1283:instruments","from_node_id":"-123:data"},{"to_node_id":"-512:instruments","from_node_id":"-177:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:training_ds","from_node_id":"-186:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:features","from_node_id":"-189:data"},{"to_node_id":"-186:features","from_node_id":"-189:data"}],"nodes":[{"node_id":"-1278","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"return_1 = close/shift(close, 1)\nreturn_3 = close/shift(close, 3)\nreturn_5 = close/shift(close, 5)\namount/mean(amount,3)\nmean(amount,3)/mean(amount,5)\nrank(amount)/rank(mean(amount,5))\nrank(amount)/rank(mean(amount,3))\nrank(close/shift(close, 1))\nrank(close/shift(close, 3))\nrank(close/shift(close, 5)) \nrank(close/shift(close, 1))/rank(close/shift(close, 5)) \nrank(close/shift(close, 3))/rank(close/shift(close, 5))","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-1278"}],"output_ports":[{"name":"data","node_id":"-1278"}],"cacheable":true,"seq_num":11,"comment":"","comment_collapsed":true},{"node_id":"-1283","module_id":"BigQuantSpace.use_datasource.use_datasource-v1","parameters":[{"name":"datasource_id","value":"bar1d_CN_CONBOND","type":"Literal","bound_global_parameter":null},{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-1283"},{"name":"features","node_id":"-1283"}],"output_ports":[{"name":"data","node_id":"-1283"}],"cacheable":false,"seq_num":12,"comment":"","comment_collapsed":true},{"node_id":"-1290","module_id":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","parameters":[{"name":"date_col","value":"date","type":"Literal","bound_global_parameter":null},{"name":"instrument_col","value":"instrument","type":"Literal","bound_global_parameter":null},{"name":"drop_na","value":"False","type":"Literal","bound_global_parameter":null},{"name":"remove_extra_columns","value":"False","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-1290"},{"name":"features","node_id":"-1290"}],"output_ports":[{"name":"data","node_id":"-1290"}],"cacheable":true,"seq_num":13,"comment":"","comment_collapsed":true},{"node_id":"-1079","module_id":"BigQuantSpace.auto_labeler_on_datasource.auto_labeler_on_datasource-v1","parameters":[{"name":"label_expr","value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","type":"Literal","bound_global_parameter":null},{"name":"drop_na_label","value":"True","type":"Literal","bound_global_parameter":null},{"name":"cast_label_int","value":"True","type":"Literal","bound_global_parameter":null},{"name":"date_col","value":"date","type":"Literal","bound_global_parameter":null},{"name":"instrument_col","value":"instrument","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-1079"}],"output_ports":[{"name":"data","node_id":"-1079"}],"cacheable":true,"seq_num":14,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","module_id":"BigQuantSpace.join.join-v3","parameters":[{"name":"on","value":"date,instrument","type":"Literal","bound_global_parameter":null},{"name":"how","value":"inner","type":"Literal","bound_global_parameter":null},{"name":"sort","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"data1","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"name":"data2","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"output_ports":[{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"cacheable":true,"seq_num":15,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","module_id":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v6","parameters":[{"name":"learning_algorithm","value":"排序","type":"Literal","bound_global_parameter":null},{"name":"number_of_leaves","value":"30","type":"Literal","bound_global_parameter":null},{"name":"minimum_docs_per_leaf","value":"1000","type":"Literal","bound_global_parameter":null},{"name":"number_of_trees","value":"20","type":"Literal","bound_global_parameter":null},{"name":"learning_rate","value":"0.1","type":"Literal","bound_global_parameter":null},{"name":"max_bins","value":1023,"type":"Literal","bound_global_parameter":null},{"name":"feature_fraction","value":1,"type":"Literal","bound_global_parameter":null},{"name":"data_row_fraction","value":1,"type":"Literal","bound_global_parameter":null},{"name":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"ndcg_discount_base","value":1,"type":"Literal","bound_global_parameter":null},{"name":"m_lazy_run","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"training_ds","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"name":"features","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"name":"test_ds","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"name":"base_model","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"}],"output_ports":[{"name":"model","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"name":"feature_gains","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"name":"m_lazy_run","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"}],"cacheable":true,"seq_num":16,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","module_id":"BigQuantSpace.stock_ranker_predict.stock_ranker_predict-v5","parameters":[{"name":"m_lazy_run","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"model","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"output_ports":[{"name":"predictions","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"name":"m_lazy_run","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"cacheable":true,"seq_num":17,"comment":"","comment_collapsed":true},{"node_id":"-2411","module_id":"BigQuantSpace.use_datasource.use_datasource-v1","parameters":[{"name":"datasource_id","value":"bar1d_CN_CONBOND","type":"Literal","bound_global_parameter":null},{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-2411"},{"name":"features","node_id":"-2411"}],"output_ports":[{"name":"data","node_id":"-2411"}],"cacheable":true,"seq_num":28,"comment":"","comment_collapsed":true},{"node_id":"-2427","module_id":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","parameters":[{"name":"date_col","value":"date","type":"Literal","bound_global_parameter":null},{"name":"instrument_col","value":"instrument","type":"Literal","bound_global_parameter":null},{"name":"drop_na","value":"False","type":"Literal","bound_global_parameter":null},{"name":"remove_extra_columns","value":"False","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-2427"},{"name":"features","node_id":"-2427"}],"output_ports":[{"name":"data","node_id":"-2427"}],"cacheable":true,"seq_num":30,"comment":"","comment_collapsed":true},{"node_id":"-3135","module_id":"BigQuantSpace.hftrade.hftrade-v2","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"initialize","value":"# 交易引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载股票指标数据,数据继承自m6模块\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.00016, sell_cost=0.00116, 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 = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])\n context.stock_weights = [1/stock_count for i in range(stock_count)]\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.5\n context.options['hold_days'] = 10\n #大盘数据获取\n bm_df = DataSource('bar1d_index_CN_STOCK_A').read(instruments=['000001.HIX'])\n bm_df[\"bm_ret\"] = bm_df[\"close\"]/bm_df[\"close\"].shift(4)-1\n #bm_df[\"bm_ret\"] = bm_df[\"bm_ret\"].shift(1) #取昨日的收益情况\n context.bm_df = bm_df[['date','bm_ret']]\n ","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"# 交易引擎:每个单位时间开盘前调用一次。\ndef bigquant_run(context, data):\n pass","type":"Literal","bound_global_parameter":null},{"name":"handle_tick","value":"# 交易引擎:tick数据处理函数,每个tick执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n today=data.current_dt.strftime('%Y-%m-%d')\n positions = {e: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n positions_cost={e: p.cost_basis for e,p in context.portfolio.positions.items()} \n now_bm = context.bm_df[context.bm_df.date==today]\n current_stoploss_stock = []\n current_stopwin_stock = []\n if len(positions) > 0:\n for i in positions.keys():\n stock_cost=positions_cost[i] \n stock_market_price=data.current(context.symbol(i),'price') \n # 亏5%就止损\n #if (stock_market_price - stock_cost) / stock_cost <= -0.1: \n #context.order_target_percent(context.symbol(i),0) \n #current_stoploss_stock.append(i)\n #print('日期:',date,i,'出现止损状况')\n #df = pd.DataFrame(current_stoploss_stock)\n #f=df.to_csv(\"loss.csv\")\n #stop_loss = pd.read_csv(\"loss.csv\")\n #stop_loss_stock = stop_loss.values.tolist()\n #print(stop_loss_stock\n if (stock_market_price - stock_cost ) / stock_cost >= 0.18: \n context.order_target_percent(context.symbol(i),0) \n current_stopwin_stock.append(i)\n #print('日期:',date,'股票:',i,'出现止盈状况')\n \n #context.bm_risk = 0\n if(now_bm.bm_ret.iloc[0]< -0.03):\n if len(positions)>0:\n for instrument in positions.keys():\n stock_cost=positions_cost[instrument] \n stock_market_price=data.current(context.symbol(instrument),'price') \n #volume_since_buy = data.history(context.symbol(instrument), 'volume', 6, '1d')\n # 赚4%且为可交易状态就止盈\n if stock_market_price/stock_cost-1>= 0.02 and data.can_trade(context.symbol(instrument)):\n context.order_target_percent(context.symbol(instrument),0)\n print(\"触发风控止赢!\")\n print(\"触发大盘风控!\")\n return \n #if(context.bm_risk==1):\n #print(\"触发大盘风控!\")\n #return\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: p.amount * p.last_sale_price\n for e, p in context.portfolio.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e: e for e, p in context.portfolio.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities)])))\n\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票\n buy_cash_weights = context.stock_weights\n buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_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 context.order_value(context.symbol(instrument), cash)\n","type":"Literal","bound_global_parameter":null},{"name":"handle_trade","value":"# 交易引擎:成交回报处理函数,每个成交发生时执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"handle_order","value":"# 交易引擎:委托回报处理函数,每个委托变化时执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"after_trading","value":"# 交易引擎:盘后处理函数,每日盘后执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"capital_base","value":"1000000","type":"Literal","bound_global_parameter":null},{"name":"frequency","value":"daily","type":"Literal","bound_global_parameter":null},{"name":"price_type","value":"后复权","type":"Literal","bound_global_parameter":null},{"name":"product_type","value":"可转债","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":"0","type":"Literal","bound_global_parameter":null},{"name":"volume_limit","value":1,"type":"Literal","bound_global_parameter":null},{"name":"order_price_field_buy","value":"open","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_sell","value":"close","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"000300.HIX","type":"Literal","bound_global_parameter":null},{"name":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"disable_cache","value":"False","type":"Literal","bound_global_parameter":null},{"name":"replay_bdb","value":"False","type":"Literal","bound_global_parameter":null},{"name":"show_debug_info","value":"False","type":"Literal","bound_global_parameter":null},{"name":"backtest_only","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-3135"},{"name":"options_data","node_id":"-3135"},{"name":"history_ds","node_id":"-3135"},{"name":"benchmark_ds","node_id":"-3135"}],"output_ports":[{"name":"raw_perf","node_id":"-3135"}],"cacheable":false,"seq_num":19,"comment":"","comment_collapsed":true},{"node_id":"-512","module_id":"BigQuantSpace.use_datasource.use_datasource-v1","parameters":[{"name":"datasource_id","value":"market_performance_CN_CONBOND","type":"Literal","bound_global_parameter":null},{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-512"},{"name":"features","node_id":"-512"}],"output_ports":[{"name":"data","node_id":"-512"}],"cacheable":false,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-760","module_id":"BigQuantSpace.trade_data_generation.trade_data_generation-v1","parameters":[{"name":"category","value":"CN_STOCK","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input","node_id":"-760"}],"output_ports":[{"name":"history_data","node_id":"-760"},{"name":"instrument_list","node_id":"-760"},{"name":"calendar","node_id":"-760"}],"cacheable":false,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"-123","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2017-01-03","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2018-01-09","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_CONBOND","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-123"}],"output_ports":[{"name":"data","node_id":"-123"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-177","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2018-01-10","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-12-12","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_CONBOND","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-177"}],"output_ports":[{"name":"data","node_id":"-177"}],"cacheable":true,"seq_num":22,"comment":"","comment_collapsed":true},{"node_id":"-186","module_id":"BigQuantSpace.dropnan.dropnan-v2","parameters":[],"input_ports":[{"name":"input_data","node_id":"-186"},{"name":"features","node_id":"-186"}],"output_ports":[{"name":"data","node_id":"-186"}],"cacheable":true,"seq_num":23,"comment":"","comment_collapsed":true},{"node_id":"-189","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"return_1 \nreturn_3 \nreturn_5 \namount/mean(amount,3)\nmean(amount,3)/mean(amount,5)\nrank(amount)/rank(mean(amount,5))\nrank(amount)/rank(mean(amount,3))\nrank(close/shift(close, 1))\nrank(close/shift(close, 3))\nrank(close/shift(close, 5)) \nrank(close/shift(close, 1))/rank(close/shift(close, 5)) \nrank(close/shift(close, 3))/rank(close/shift(close, 5))","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-189"}],"output_ports":[{"name":"data","node_id":"-189"}],"cacheable":true,"seq_num":18,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-1278' Position='1318,-545,200,200'/><node_position Node='-1283' Position='982,-486,200,200'/><node_position Node='-1290' Position='1194,-247,200,200'/><node_position Node='-1079' Position='816,-321,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='1097,-104,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-43' Position='1265,107,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='1471,245,200,200'/><node_position Node='-2411' Position='1729,-192,200,200'/><node_position Node='-2427' Position='1722,6,200,200'/><node_position Node='-3135' Position='1742,400,200,200'/><node_position Node='-512' Position='1734,-522,200,200'/><node_position Node='-760' Position='1764,-401,200,200'/><node_position Node='-123' Position='980,-585,200,200'/><node_position Node='-177' Position='1736,-620,200,200'/><node_position Node='-186' Position='1107,0,200,200'/><node_position Node='-189' Position='1432,-121,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [7]:
    # 本代码由可视化策略环境自动生成 2022年12月14日 14:48
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 交易引擎:初始化函数,只执行一次
    def m19_initialize_bigquant_run(context):
           # 加载股票指标数据,数据继承自m6模块
        context.ranker_prediction = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.00016, sell_cost=0.00116, min_cost=5))
        # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        stock_count = 5
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])
        context.stock_weights = [1/stock_count for i in range(stock_count)]
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 0.5
        context.options['hold_days'] = 10
         #大盘数据获取
        bm_df = DataSource('bar1d_index_CN_STOCK_A').read(instruments=['000001.HIX'])
        bm_df["bm_ret"] = bm_df["close"]/bm_df["close"].shift(4)-1
        #bm_df["bm_ret"] = bm_df["bm_ret"].shift(1) #取昨日的收益情况
        context.bm_df = bm_df[['date','bm_ret']]
     
    # 交易引擎:每个单位时间开盘前调用一次。
    def m19_before_trading_start_bigquant_run(context, data):
        pass
    # 交易引擎:tick数据处理函数,每个tick执行一次
    def m19_handle_tick_bigquant_run(context, data):
        pass
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_handle_data_bigquant_run(context, data):
        
        today=data.current_dt.strftime('%Y-%m-%d')
        positions = {e: p.amount * p.last_sale_price
                     for e, p in context.portfolio.positions.items()}
        positions_cost={e: p.cost_basis for e,p in context.portfolio.positions.items()} 
        now_bm = context.bm_df[context.bm_df.date==today]
        current_stoploss_stock = []
        current_stopwin_stock = []
        if len(positions) > 0:
            for i in positions.keys():
                stock_cost=positions_cost[i]  
                stock_market_price=data.current(context.symbol(i),'price') 
                # 亏5%就止损
                #if (stock_market_price - stock_cost) / stock_cost <= -0.1:   
                    #context.order_target_percent(context.symbol(i),0)     
                    #current_stoploss_stock.append(i)
                    #print('日期:',date,i,'出现止损状况')
                    #df = pd.DataFrame(current_stoploss_stock)
                    #f=df.to_csv("loss.csv")
                    #stop_loss = pd.read_csv("loss.csv")
                    #stop_loss_stock = stop_loss.values.tolist()
                    #print(stop_loss_stock
                if (stock_market_price - stock_cost ) / stock_cost >= 0.18:   
                    context.order_target_percent(context.symbol(i),0)     
                    current_stopwin_stock.append(i)
                    #print('日期:',date,'股票:',i,'出现止盈状况')
        
        #context.bm_risk = 0
        if(now_bm.bm_ret.iloc[0]< -0.03):
                if len(positions)>0:
                    for instrument in positions.keys():
                        stock_cost=positions_cost[instrument]  
                        stock_market_price=data.current(context.symbol(instrument),'price')  
                        #volume_since_buy = data.history(context.symbol(instrument), 'volume', 6, '1d')
                # 赚4%且为可交易状态就止盈
                        if stock_market_price/stock_cost-1>= 0.02 and data.can_trade(context.symbol(instrument)):
                             context.order_target_percent(context.symbol(instrument),0)
                             print("触发风控止赢!")
                print("触发大盘风控!")
                return      
            #if(context.bm_risk==1):
                #print("触发大盘风控!")
                #return
            
        # 按日期过滤得到今日的预测数据
        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: p.amount * p.last_sale_price
                     for e, p in context.portfolio.positions.items()}
    
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
        if not is_staging and cash_for_sell > 0:
            equities = {e: e for e, p in context.portfolio.positions.items()}
            instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                    lambda x: x in equities)])))
    
            for instrument in instruments:
                context.order_target(context.symbol(instrument), 0)
                cash_for_sell -= positions[instrument]
                if cash_for_sell <= 0:
                    break
    
        # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
        buy_cash_weights = context.stock_weights
        buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_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:
                context.order_value(context.symbol(instrument), cash)
    
    # 交易引擎:成交回报处理函数,每个成交发生时执行一次
    def m19_handle_trade_bigquant_run(context, data):
        pass
    
    # 交易引擎:委托回报处理函数,每个委托变化时执行一次
    def m19_handle_order_bigquant_run(context, data):
        pass
    
    # 交易引擎:盘后处理函数,每日盘后执行一次
    def m19_after_trading_bigquant_run(context, data):
        pass
    
    
    m11 = M.input_features.v1(
        features="""return_1 = close/shift(close, 1)
    return_3 = close/shift(close, 3)
    return_5 = close/shift(close, 5)
    amount/mean(amount,3)
    mean(amount,3)/mean(amount,5)
    rank(amount)/rank(mean(amount,5))
    rank(amount)/rank(mean(amount,3))
    rank(close/shift(close, 1))
    rank(close/shift(close, 3))
    rank(close/shift(close, 5))     
    rank(close/shift(close, 1))/rank(close/shift(close, 5))    
    rank(close/shift(close, 3))/rank(close/shift(close, 5))"""
    )
    
    m4 = M.instruments.v2(
        start_date='2017-01-03',
        end_date='2018-01-09',
        market='CN_CONBOND',
        instrument_list='',
        max_count=0
    )
    
    m12 = M.use_datasource.v1(
        instruments=m4.data,
        datasource_id='bar1d_CN_CONBOND',
        start_date='',
        end_date='',
        m_cached=False
    )
    
    m13 = M.derived_feature_extractor.v3(
        input_data=m12.data,
        features=m11.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m14 = M.auto_labeler_on_datasource.v1(
        input_data=m12.data,
        label_expr="""# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
    
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    shift(close, -5) / shift(open, -1)
    
    # 极值处理:用1%和99%分位的值做clip
    clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
    
    # 将分数映射到分类,这里使用20个分类
    all_wbins(label, 20)
    
    # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
    where(shift(high, -1) == shift(low, -1), NaN, label)
    """,
        drop_na_label=True,
        cast_label_int=True,
        date_col='date',
        instrument_col='instrument',
        user_functions={}
    )
    
    m15 = M.join.v3(
        data1=m14.data,
        data2=m13.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m22 = M.instruments.v2(
        start_date='2018-01-10',
        end_date='2022-12-12',
        market='CN_CONBOND',
        instrument_list='',
        max_count=0
    )
    
    m1 = M.use_datasource.v1(
        instruments=m22.data,
        datasource_id='market_performance_CN_CONBOND',
        start_date='',
        end_date='',
        m_cached=False
    )
    
    m2 = M.trade_data_generation.v1(
        input=m1.data,
        category='CN_STOCK',
        m_cached=False
    )
    
    m28 = M.use_datasource.v1(
        instruments=m2.instrument_list,
        datasource_id='bar1d_CN_CONBOND',
        start_date='',
        end_date=''
    )
    
    m30 = M.derived_feature_extractor.v3(
        input_data=m28.data,
        features=m11.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m18 = M.input_features.v1(
        features="""return_1 
    return_3 
    return_5 
    amount/mean(amount,3)
    mean(amount,3)/mean(amount,5)
    rank(amount)/rank(mean(amount,5))
    rank(amount)/rank(mean(amount,3))
    rank(close/shift(close, 1))
    rank(close/shift(close, 3))
    rank(close/shift(close, 5))     
    rank(close/shift(close, 1))/rank(close/shift(close, 5))    
    rank(close/shift(close, 3))/rank(close/shift(close, 5))"""
    )
    
    m23 = M.dropnan.v2(
        input_data=m15.data,
        features=m18.data
    )
    
    m16 = M.stock_ranker_train.v6(
        training_ds=m23.data,
        features=m18.data,
        learning_algorithm='排序',
        number_of_leaves=30,
        minimum_docs_per_leaf=1000,
        number_of_trees=20,
        learning_rate=0.1,
        max_bins=1023,
        feature_fraction=1,
        data_row_fraction=1,
        plot_charts=True,
        ndcg_discount_base=1,
        m_lazy_run=False
    )
    
    m17 = M.stock_ranker_predict.v5(
        model=m16.model,
        data=m30.data,
        m_lazy_run=False
    )
    
    m19 = M.hftrade.v2(
        instruments=m2.instrument_list,
        options_data=m17.predictions,
        start_date='',
        end_date='',
        initialize=m19_initialize_bigquant_run,
        before_trading_start=m19_before_trading_start_bigquant_run,
        handle_tick=m19_handle_tick_bigquant_run,
        handle_data=m19_handle_data_bigquant_run,
        handle_trade=m19_handle_trade_bigquant_run,
        handle_order=m19_handle_order_bigquant_run,
        after_trading=m19_after_trading_bigquant_run,
        capital_base=1000000,
        frequency='daily',
        price_type='后复权',
        product_type='可转债',
        before_start_days='0',
        volume_limit=1,
        order_price_field_buy='open',
        order_price_field_sell='close',
        benchmark='000300.HIX',
        plot_charts=True,
        disable_cache=False,
        replay_bdb=False,
        show_debug_info=False,
        backtest_only=False
    )
    
    设置评估测试数据集,查看训练曲线
    [视频教程]StockRanker训练曲线
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-42160908c3e94e0cbf892f1194e3c5a7"}/bigcharts-data-end
    触发风控止赢!
    触发大盘风控!
    触发风控止赢!
    触发大盘风控!
    触发大盘风控!
    触发大盘风控!
    触发大盘风控!
    触发风控止赢!
    触发大盘风控!
    触发风控止赢!
    触发风控止赢!
    触发大盘风控!
    触发大盘风控!
    触发风控止赢!
    触发大盘风控!
    触发风控止赢!
    触发大盘风控!
    触发风控止赢!
    触发风控止赢!
    触发大盘风控!
    触发风控止赢!
    触发风控止赢!
    触发大盘风控!
    触发风控止赢!
    触发大盘风控!
    触发大盘风控!
    触发风控止赢!
    触发风控止赢!
    触发大盘风控!
    触发风控止赢!
    触发风控止赢!
    触发大盘风控!
    触发风控止赢!
    触发风控止赢!
    触发风控止赢!
    触发风控止赢!
    触发风控止赢!
    触发大盘风控!
    触发大盘风控!
    触发风控止赢!
    触发风控止赢!
    触发大盘风控!
    2022-12-14 14:47:39.935205 strategy strategy exception:Traceback (most recent call last):
      File "bigtrader/strategy/engine.py", line 713, in bigtrader2.bigtrader.strategy.engine.StrategyEngine._call_strategy_func
      File "bigtrader/strategy/strategy_base.py", line 2275, in bigtrader2.bigtrader.strategy.strategy_base.StrategyBase.call_handle_data
      File "<ipython-input-7-309825713890>", line 58, in m19_handle_data_bigquant_run
        if (stock_market_price - stock_cost ) / stock_cost >= 0.18:
    ZeroDivisionError: float division by zero
     
    
    ---------------------------------------------------------------------------
    ZeroDivisionError                         Traceback (most recent call last)
    <ipython-input-7-309825713890> in <module>
        285 )
        286 
    --> 287 m19 = M.hftrade.v2(
        288     instruments=m2.instrument_list,
        289     options_data=m17.predictions,
    
    <ipython-input-7-309825713890> in m19_handle_data_bigquant_run(context, data)
         56                 #stop_loss_stock = stop_loss.values.tolist()
         57                 #print(stop_loss_stock
    ---> 58             if (stock_market_price - stock_cost ) / stock_cost >= 0.18:
         59                 context.order_target_percent(context.symbol(i),0)
         60                 current_stopwin_stock.append(i)
    
    ZeroDivisionError: float division by zero