克隆策略

    {"description":"实验创建于2021/11/10","graph":{"edges":[{"to_node_id":"-233:features","from_node_id":"-216:data"},{"to_node_id":"-2663:features","from_node_id":"-216:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:features","from_node_id":"-216:data"},{"to_node_id":"-132:features_ds","from_node_id":"-216:data"},{"to_node_id":"-648:instruments","from_node_id":"-220:data"},{"to_node_id":"-367:instruments","from_node_id":"-220:data"},{"to_node_id":"-931:data2","from_node_id":"-233:data"},{"to_node_id":"-931:data1","from_node_id":"-367:data"},{"to_node_id":"-233:input_data","from_node_id":"-648:data"},{"to_node_id":"-137:input_data","from_node_id":"-931:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:training_ds","from_node_id":"-1082:data"},{"to_node_id":"-2648:instruments","from_node_id":"-2639:data"},{"to_node_id":"-1696:instruments","from_node_id":"-2639:data"},{"to_node_id":"-172:input_1","from_node_id":"-2639:data"},{"to_node_id":"-2663:input_data","from_node_id":"-2648:data"},{"to_node_id":"-1500:input_data","from_node_id":"-2663:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","from_node_id":"-2669:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:model"},{"to_node_id":"-209:data1","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"to_node_id":"-1082:input_data","from_node_id":"-137:data"},{"to_node_id":"-648:features","from_node_id":"-132:data"},{"to_node_id":"-2648:features","from_node_id":"-132:data"},{"to_node_id":"-2669:input_data","from_node_id":"-1500:data"},{"to_node_id":"-172:input_2","from_node_id":"-170:data"},{"to_node_id":"-209:data2","from_node_id":"-172:data_1"},{"to_node_id":"-10139:input_ds","from_node_id":"-209:data"},{"to_node_id":"-1696:options_data","from_node_id":"-10139:sorted_data"}],"nodes":[{"node_id":"-216","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征 \nhigh_0\nhigh_1\nhigh_2\nhigh_3\nhigh_4\nlow_0\nlow_1\nlow_2\nlow_3\nlow_4\n# 5日平均振幅\n(high_0-low_0+high_1-low_1+high_2-low_2+high_3-low_3+high_4-low_4)/5 \n#'pe_lyr_0', # 市盈率LYR\n# 5日净主动买入额\nmf_net_amount_5 \n# 10日净主动买入额\nmf_net_amount_10 \n# 20日净主动买入额\nmf_net_amount_20 \n# 过去10个交易日的换手率排名/过去30个交易日的换手率排名\nrank_return_10/rank_return_30\n# 过去15个交易日的平均换手率/第前0个交易日的换手率\navg_turn_15/turn_0\n# CCI指标,timeperiod=14\nta_cci_14_0\n# 过去0个交易日的收益(当天收益)\nreturn_0\n# 第前5个交易日的换手率/过去10个交易日的平均换手率\nturn_5/avg_turn_10\n# 振幅波动率,timeperiod=10(60)\nswing_volatility_10_0/swing_volatility_60_0\n# 过去10个交易日的交易额百分比排名/过去30个交易日的交易额百分比排名\nrank_amount_10/rank_amount_30\n# 已经上市的天数\nlist_days_0\n# 超大单净流入净额\nmf_net_amount_xl_0\n# 过去5个交易日的平均换手率\navg_turn_5\n# 第前0个交易日的换手率/过去5个交易日的平均换手率\nturn_0/avg_turn_5\n# 过去20个交易日的换手率排名\nrank_return_20\n# 过去5个交易日的换手率排名/ 过去20个交易日的换手率排名\nrank_return_5/rank_return_20\n# 过去5个交易日的平均交易额\navg_amount_5\n# 过去5个交易日的平均换手率排名\nrank_avg_turn_5\n","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-216"}],"output_ports":[{"name":"data","node_id":"-216"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-220","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2010-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2020-01-01","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_STOCK_A","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":"-220"}],"output_ports":[{"name":"data","node_id":"-220"}],"cacheable":true,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"-233","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":"-233"},{"name":"features","node_id":"-233"}],"output_ports":[{"name":"data","node_id":"-233"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-367","module_id":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","parameters":[{"name":"label_expr","value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\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":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"000300.SHA","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":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-367"}],"output_ports":[{"name":"data","node_id":"-367"}],"cacheable":true,"seq_num":5,"comment":"","comment_collapsed":true},{"node_id":"-648","module_id":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":90,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-648"},{"name":"features","node_id":"-648"}],"output_ports":[{"name":"data","node_id":"-648"}],"cacheable":true,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-931","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":"-931"},{"name":"data2","node_id":"-931"}],"output_ports":[{"name":"data","node_id":"-931"}],"cacheable":true,"seq_num":6,"comment":"","comment_collapsed":true},{"node_id":"-1082","module_id":"BigQuantSpace.dropnan.dropnan-v2","parameters":[],"input_ports":[{"name":"input_data","node_id":"-1082"},{"name":"features","node_id":"-1082"}],"output_ports":[{"name":"data","node_id":"-1082"}],"cacheable":true,"seq_num":7,"comment":"","comment_collapsed":true},{"node_id":"-2639","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2020-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-11-19","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_STOCK_A","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":"-2639"}],"output_ports":[{"name":"data","node_id":"-2639"}],"cacheable":true,"seq_num":8,"comment":"","comment_collapsed":true},{"node_id":"-2648","module_id":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v6","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-2648"},{"name":"features","node_id":"-2648"}],"output_ports":[{"name":"data","node_id":"-2648"}],"cacheable":true,"seq_num":9,"comment":"","comment_collapsed":true},{"node_id":"-2663","module_id":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v2","parameters":[{"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":"-2663"},{"name":"features","node_id":"-2663"}],"output_ports":[{"name":"data","node_id":"-2663"}],"cacheable":false,"seq_num":10,"comment":"在衍生特征里配置自定义函数就可以了,也可以覆盖同名的预定义函数","comment_collapsed":true},{"node_id":"-2669","module_id":"BigQuantSpace.dropnan.dropnan-v1","parameters":[],"input_ports":[{"name":"input_data","node_id":"-2669"}],"output_ports":[{"name":"data","node_id":"-2669"}],"cacheable":true,"seq_num":11,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","module_id":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v5","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":"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":12,"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":13,"comment":"","comment_collapsed":true},{"node_id":"-1696","module_id":"BigQuantSpace.trade.trade-v4","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 # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.2\n context.hold_days = 5","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n\n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.hold_days # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.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_1 = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n # 所拥有的仓位情况\n positions = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}\n\n #大盘风控模块,读取风控数据 \n #----------------大盘风控模块,读取风控数据------------------\n # risk表示是否遇到了下跌的情况,等于0否,等于1是\n risk = 0\n today = data.current_dt.strftime('%Y-%m-%d')\n # 利用上证指数的涨跌来看大盘的涨跌\n bm_ret0=ranker_prediction.bm_ret0.values[0]\n bm_ret1=ranker_prediction.bm_ret1.values[0]\n bm_ret2=ranker_prediction.bm_ret2.values[0]\n bm_ret3=ranker_prediction.bm_ret3.values[0]\n bm_risk_v0=ranker_prediction.bm_risk_v0.values[0]\n bm_risk_v1=ranker_prediction.bm_risk_v1.values[0]\n bm_risk_v2=ranker_prediction.bm_risk_v2.values[0]\n if bm_ret0 < 0.001:\n if bm_risk_v0 > 0:\n print(today,'大盘放量下跌,全仓卖出')\n risk = 1\n elif bm_ret1 < 0.001 and bm_ret2 < 0.002:\n print(today,'大盘连续下跌,全仓卖出')\n risk = 1\n if bm_ret3 < -0.02:\n print(today,'大盘三日下跌超过2%,全仓卖出')\n risk = 1\n if bm_ret0 > 0.01:\n if (bm_risk_v0 + bm_risk_v1) < 0:\n print(today,'大盘缩量上涨,全仓卖出')\n risk = 1\n\n # 此时需要卖出手上所有的股票\n if risk == 1:\n # 手上还有仓位\n if len(positions)>0:\n # 全部卖出后返回\n for instrument in positions:\n last_sale_date = positions[instrument].last_sale_date #上次交易日期\n delta_days = data.current_dt - last_sale_date \n hold_days = delta_days.days #持仓天数\n if data.can_trade(context.symbol(instrument)) and hold_days > 0:\n context.order_target_percent(context.symbol(instrument), 0)\n return \n # 风控卖出后直接使用return结束当日交易,后续轮仓逻辑不再执行\n #---------------------大盘风控结束--------------------------------------\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n if len(positions) > 0:\n for instrument in positions.keys():\n last_sale_date = positions[instrument].last_sale_date #上次交易日期\n delta_days = data.current_dt - last_sale_date \n hold_days = delta_days.days #持仓天数\n # 股票实行t+1制度,必须使持仓天数大于0\n if hold_days > 0:\n equities = {e.symbol: 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 and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n for instrument1 in instruments:\n context.order_target(context.symbol(instrument1), 0)\n cash_for_sell -= positions_1[instrument1]\n if cash_for_sell <= 0:\n break\n\n# 3. 生成买入订单:按StockRanker预测的排序,买入前面的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 \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_1.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n cash = max_cash_per_instrument - positions_1.get(instrument, 0)\n if cash > 0:\n # 获取今天和过去两天的成交量\n volume_since_buy = data.history(context.symbol(instrument), 'volume', 3, '1d')\n close_price = data.current(context.symbol(instrument), 'close') #当收盘价\n high_price = data.current(context.symbol(instrument), 'high') #当天最高价\n # 冲高回落的股票不能买\n if ((volume_since_buy[2]/volume_since_buy[1] < 2.5) or (high_price/close_price<1.05)) and volume_since_buy[2]/volume_since_buy[0] > 1:\n current_price = data.current(context.symbol(instrument), 'price')\n amount = math.floor(cash / current_price - cash / current_price % 100)\n context.order(context.symbol(instrument), amount)\n return","type":"Literal","bound_global_parameter":null},{"name":"prepare","value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"volume_limit","value":0.025,"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":"capital_base","value":1000000,"type":"Literal","bound_global_parameter":null},{"name":"auto_cancel_non_tradable_orders","value":"True","type":"Literal","bound_global_parameter":null},{"name":"data_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":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"backtest_only","value":"False","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-1696"},{"name":"options_data","node_id":"-1696"},{"name":"history_ds","node_id":"-1696"},{"name":"benchmark_ds","node_id":"-1696"},{"name":"trading_calendar","node_id":"-1696"}],"output_ports":[{"name":"raw_perf","node_id":"-1696"}],"cacheable":false,"seq_num":15,"comment":"","comment_collapsed":true},{"node_id":"-137","module_id":"BigQuantSpace.filter.filter-v3","parameters":[{"name":"expr","value":"st_status_0==0 and low_0>high_1 and close_0>open_0","type":"Literal","bound_global_parameter":null},{"name":"output_left_data","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-137"}],"output_ports":[{"name":"data","node_id":"-137"},{"name":"left_data","node_id":"-137"}],"cacheable":true,"seq_num":14,"comment":"","comment_collapsed":true},{"node_id":"-132","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nclose_0\nhigh_1\nopen_0\nlow_0\nst_status_0","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-132"}],"output_ports":[{"name":"data","node_id":"-132"}],"cacheable":true,"seq_num":16,"comment":"","comment_collapsed":true},{"node_id":"-1500","module_id":"BigQuantSpace.filter.filter-v3","parameters":[{"name":"expr","value":"st_status_0==0 and low_0>high_1+0.02 and close_0>open_0","type":"Literal","bound_global_parameter":null},{"name":"output_left_data","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-1500"}],"output_ports":[{"name":"data","node_id":"-1500"},{"name":"left_data","node_id":"-1500"}],"cacheable":true,"seq_num":17,"comment":"","comment_collapsed":true},{"node_id":"-170","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nret_1=close/shift(close,1)\nret_3=close/shift(close,3)\nvolumepct_1=volume/shift(volume,1)\nbm_ret0=ret_1\nbm_ret1=shift(bm_ret0,1)\nbm_ret2=shift(bm_ret0,2)\nbm_ret3=ret_3\nbm_risk_v0=volumepct_1\nbm_risk_v1=shift(bm_risk_v0,1)\nbm_risk_v2=shift(bm_risk_v0,2)","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-170"}],"output_ports":[{"name":"data","node_id":"-170"}],"cacheable":true,"seq_num":18,"comment":"","comment_collapsed":true},{"node_id":"-172","module_id":"BigQuantSpace.index_feature_extract.index_feature_extract-v3","parameters":[{"name":"before_days","value":100,"type":"Literal","bound_global_parameter":null},{"name":"index","value":"000001.HIX","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_1","node_id":"-172"},{"name":"input_2","node_id":"-172"}],"output_ports":[{"name":"data_1","node_id":"-172"},{"name":"data_2","node_id":"-172"}],"cacheable":true,"seq_num":19,"comment":"","comment_collapsed":true},{"node_id":"-209","module_id":"BigQuantSpace.join.join-v3","parameters":[{"name":"on","value":"date","type":"Literal","bound_global_parameter":null},{"name":"how","value":"left","type":"Literal","bound_global_parameter":null},{"name":"sort","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"data1","node_id":"-209"},{"name":"data2","node_id":"-209"}],"output_ports":[{"name":"data","node_id":"-209"}],"cacheable":true,"seq_num":20,"comment":"","comment_collapsed":true},{"node_id":"-10139","module_id":"BigQuantSpace.sort.sort-v4","parameters":[{"name":"sort_by","value":"date,position","type":"Literal","bound_global_parameter":null},{"name":"group_by","value":"--","type":"Literal","bound_global_parameter":null},{"name":"keep_columns","value":"--","type":"Literal","bound_global_parameter":null},{"name":"ascending","value":"True","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_ds","node_id":"-10139"},{"name":"sort_by_ds","node_id":"-10139"}],"output_ports":[{"name":"sorted_data","node_id":"-10139"}],"cacheable":true,"seq_num":21,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-216' Position='237,-137,200,200'/><node_position Node='-220' Position='-211,-32,200,200'/><node_position Node='-233' Position='95,139,200,200'/><node_position Node='-367' Position='-253,120,200,200'/><node_position Node='-648' Position='82,46,200,200'/><node_position Node='-931' Position='-85,231,200,200'/><node_position Node='-1082' Position='-38,385,200,200'/><node_position Node='-2639' Position='762,-66,200,200'/><node_position Node='-2648' Position='765,48,200,200'/><node_position Node='-2663' Position='757,149,200,200'/><node_position Node='-2669' Position='717,449,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-43' Position='60,481,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='305,580,200,200'/><node_position Node='-1696' Position='330,885,200,200'/><node_position Node='-137' Position='-77,310,200,200'/><node_position Node='-132' Position='144,-32,200,200'/><node_position Node='-1500' Position='738,296,200,200'/><node_position Node='-170' Position='868,530,200,200'/><node_position Node='-172' Position='849,601,200,200'/><node_position Node='-209' Position='412,670,200,200'/><node_position Node='-10139' Position='421,781,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [ ]:
    # 本代码由可视化策略环境自动生成 2021年11月22日 14:55
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m15_initialize_bigquant_run(context):
        # 加载预测数据
        context.ranker_prediction = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
        # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        stock_count = 5
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 0.2
        context.hold_days = 5
    # 回测引擎:每日数据处理函数,每天执行一次
    def m15_handle_data_bigquant_run(context, data):
        # 按日期过滤得到今日的预测数据
        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.hold_days # 是否在建仓期间(前 hold_days 天)
        cash_avg = context.portfolio.portfolio_value / context.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_1 = {e.symbol: p.amount * p.last_sale_price
                       for e, p in context.perf_tracker.position_tracker.positions.items()}
        # 所拥有的仓位情况
        positions = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
    
        #大盘风控模块,读取风控数据  
        #----------------大盘风控模块,读取风控数据------------------
        # risk表示是否遇到了下跌的情况,等于0否,等于1是
        risk = 0
        today = data.current_dt.strftime('%Y-%m-%d')
        # 利用上证指数的涨跌来看大盘的涨跌
        bm_ret0=ranker_prediction.bm_ret0.values[0]
        bm_ret1=ranker_prediction.bm_ret1.values[0]
        bm_ret2=ranker_prediction.bm_ret2.values[0]
        bm_ret3=ranker_prediction.bm_ret3.values[0]
        bm_risk_v0=ranker_prediction.bm_risk_v0.values[0]
        bm_risk_v1=ranker_prediction.bm_risk_v1.values[0]
        bm_risk_v2=ranker_prediction.bm_risk_v2.values[0]
        if bm_ret0 < 0.001:
            if bm_risk_v0 > 0:
                print(today,'大盘放量下跌,全仓卖出')
                risk = 1
            elif bm_ret1 < 0.001 and bm_ret2 < 0.002:
                print(today,'大盘连续下跌,全仓卖出')
                risk = 1
            if bm_ret3 < -0.02:
                print(today,'大盘三日下跌超过2%,全仓卖出')
                risk = 1
        if bm_ret0 > 0.01:
            if (bm_risk_v0 + bm_risk_v1) < 0:
                print(today,'大盘缩量上涨,全仓卖出')
                risk = 1
    
        # 此时需要卖出手上所有的股票
        if risk == 1:
        # 手上还有仓位
            if len(positions)>0:
            # 全部卖出后返回
                for instrument in positions:
                    last_sale_date = positions[instrument].last_sale_date   #上次交易日期
                    delta_days = data.current_dt - last_sale_date  
                    hold_days = delta_days.days #持仓天数
                    if data.can_trade(context.symbol(instrument)) and hold_days > 0:
                        context.order_target_percent(context.symbol(instrument), 0)
                        return 
                    # 风控卖出后直接使用return结束当日交易,后续轮仓逻辑不再执行
            #---------------------大盘风控结束--------------------------------------
    
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
        if not is_staging and cash_for_sell > 0:
            if len(positions) > 0:
                for instrument in positions.keys():
                    last_sale_date = positions[instrument].last_sale_date   #上次交易日期
                    delta_days = data.current_dt - last_sale_date  
                    hold_days = delta_days.days #持仓天数
                    # 股票实行t+1制度,必须使持仓天数大于0
                    if hold_days > 0:
                        equities = {e.symbol: 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 and not context.has_unfinished_sell_order(equities[x]))])))
                        # print('rank order for sell %s' % instruments)
                        for instrument1 in instruments:
                            context.order_target(context.symbol(instrument1), 0)
                            cash_for_sell -= positions_1[instrument1]
                            if cash_for_sell <= 0:
                                break
    
    # 3. 生成买入订单:按StockRanker预测的排序,买入前面的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_1.get(instrument, 0):
                # 确保股票持仓量不会超过每次股票最大的占用资金量
                cash = max_cash_per_instrument - positions_1.get(instrument, 0)
            if cash > 0:
                # 获取今天和过去两天的成交量
                volume_since_buy = data.history(context.symbol(instrument), 'volume', 3, '1d')
                close_price = data.current(context.symbol(instrument), 'close')  #当收盘价
                high_price = data.current(context.symbol(instrument), 'high')  #当天最高价
                # 冲高回落的股票不能买
                if ((volume_since_buy[2]/volume_since_buy[1] < 2.5) or (high_price/close_price<1.05)) and volume_since_buy[2]/volume_since_buy[0] > 1:
                    current_price = data.current(context.symbol(instrument), 'price')
                    amount = math.floor(cash / current_price - cash / current_price % 100)
                    context.order(context.symbol(instrument), amount)
                    return
    # 回测引擎:准备数据,只执行一次
    def m15_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m15_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m1 = M.input_features.v1(
        features="""# #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征   
    high_0
    high_1
    high_2
    high_3
    high_4
    low_0
    low_1
    low_2
    low_3
    low_4
    # 5日平均振幅
    (high_0-low_0+high_1-low_1+high_2-low_2+high_3-low_3+high_4-low_4)/5 
    #'pe_lyr_0',  # 市盈率LYR
    # 5日净主动买入额
    mf_net_amount_5 
    # 10日净主动买入额
    mf_net_amount_10 
    # 20日净主动买入额
    mf_net_amount_20  
    # 过去10个交易日的换手率排名/过去30个交易日的换手率排名
    rank_return_10/rank_return_30
    # 过去15个交易日的平均换手率/第前0个交易日的换手率
    avg_turn_15/turn_0
    # CCI指标,timeperiod=14
    ta_cci_14_0
    # 过去0个交易日的收益(当天收益)
    return_0
    # 第前5个交易日的换手率/过去10个交易日的平均换手率
    turn_5/avg_turn_10
    # 振幅波动率,timeperiod=10(60)
    swing_volatility_10_0/swing_volatility_60_0
    # 过去10个交易日的交易额百分比排名/过去30个交易日的交易额百分比排名
    rank_amount_10/rank_amount_30
    # 已经上市的天数
    list_days_0
    # 超大单净流入净额
    mf_net_amount_xl_0
    # 过去5个交易日的平均换手率
    avg_turn_5
    # 第前0个交易日的换手率/过去5个交易日的平均换手率
    turn_0/avg_turn_5
    #  过去20个交易日的换手率排名
    rank_return_20
    #  过去5个交易日的换手率排名/ 过去20个交易日的换手率排名
    rank_return_5/rank_return_20
    # 过去5个交易日的平均交易额
    avg_amount_5
    # 过去5个交易日的平均换手率排名
    rank_avg_turn_5
    """
    )
    
    m16 = M.input_features.v1(
        features_ds=m1.data,
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    close_0
    high_1
    open_0
    low_0
    st_status_0"""
    )
    
    m2 = M.instruments.v2(
        start_date='2010-01-01',
        end_date='2020-01-01',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m3 = M.general_feature_extractor.v7(
        instruments=m2.data,
        features=m16.data,
        start_date='',
        end_date='',
        before_start_days=90
    )
    
    m4 = M.derived_feature_extractor.v3(
        input_data=m3.data,
        features=m1.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False
    )
    
    m5 = M.advanced_auto_labeler.v2(
        instruments=m2.data,
        label_expr="""# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
    #   添加benchmark_前缀,可使用对应的benchmark数据
    # 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)
    """,
        start_date='',
        end_date='',
        benchmark='000300.SHA',
        drop_na_label=True,
        cast_label_int=True,
        user_functions={}
    )
    
    m6 = M.join.v3(
        data1=m5.data,
        data2=m4.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m14 = M.filter.v3(
        input_data=m6.data,
        expr='st_status_0==0 and low_0>high_1 and close_0>open_0',
        output_left_data=False
    )
    
    m7 = M.dropnan.v2(
        input_data=m14.data
    )
    
    m12 = M.stock_ranker_train.v5(
        training_ds=m7.data,
        features=m1.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,
        m_lazy_run=False
    )
    
    m8 = M.instruments.v2(
        start_date='2020-01-01',
        end_date='2021-11-19',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m9 = M.general_feature_extractor.v6(
        instruments=m8.data,
        features=m16.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m10 = M.derived_feature_extractor.v2(
        input_data=m9.data,
        features=m1.data,
        date_col='date',
        instrument_col='instrument',
        m_cached=False
    )
    
    m17 = M.filter.v3(
        input_data=m10.data,
        expr='st_status_0==0 and low_0>high_1+0.02 and close_0>open_0',
        output_left_data=False
    )
    
    m11 = M.dropnan.v1(
        input_data=m17.data
    )
    
    m13 = M.stock_ranker_predict.v5(
        model=m12.model,
        data=m11.data,
        m_lazy_run=False
    )
    
    m18 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    ret_1=close/shift(close,1)
    ret_3=close/shift(close,3)
    volumepct_1=volume/shift(volume,1)
    bm_ret0=ret_1
    bm_ret1=shift(bm_ret0,1)
    bm_ret2=shift(bm_ret0,2)
    bm_ret3=ret_3
    bm_risk_v0=volumepct_1
    bm_risk_v1=shift(bm_risk_v0,1)
    bm_risk_v2=shift(bm_risk_v0,2)"""
    )
    
    m19 = M.index_feature_extract.v3(
        input_1=m8.data,
        input_2=m18.data,
        before_days=100,
        index='000001.HIX'
    )
    
    m20 = M.join.v3(
        data1=m13.predictions,
        data2=m19.data_1,
        on='date',
        how='left',
        sort=False
    )
    
    m21 = M.sort.v4(
        input_ds=m20.data,
        sort_by='date,position',
        group_by='--',
        keep_columns='--',
        ascending=True
    )
    
    m15 = M.trade.v4(
        instruments=m8.data,
        options_data=m21.sorted_data,
        start_date='',
        end_date='',
        initialize=m15_initialize_bigquant_run,
        handle_data=m15_handle_data_bigquant_run,
        prepare=m15_prepare_bigquant_run,
        before_trading_start=m15_before_trading_start_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=''
    )