股票代码过滤-支持股票类别、上市板、行业和ST过滤

股票代码过滤
标签: #<Tag:0x00007fcf69f8c240>

(iQuant) #1

在策略开发过程中,经常需要对股票代码做过滤。A股股票过滤 提供了常用对股票过滤能力。

模块功能

A股股票过滤 支持股票类别、上市板、行业和ST过滤。

模块原理

此模块对输入数据需要date和instrument列。

对于给定对数据,模块会读取对应时间段的股票类别、上市板、行业和ST状态数据(按需读取,只在读取过滤用到的数据,以达到最好的性能),并用过滤条件过滤给定数据集上的股票。

输出为满足条件的股票。如果需要同时输出不满足条件的股票,可以勾选 输出剩余数据,并在第一个输出端获得此数据。

如何使用

  1. 新建策略:通过模版新建一个 可视化AI策略
  2. 平台现在支持非常多的模块,我们可以使用搜索功能。在左侧模块链接搜索关键词 过滤 找到模块 A股股票过滤
    image
  3. 如下图,在训练数据和预测数据的 基础特征抽取 后分布添加 A股股票过滤
  4. 配置 A股股票过滤,如上图,这里我们只过滤到ST股票,在ST配置里,去掉 全部,只选择 正常

示例代码

https://i.bigquant.com/user/jliang/lab/share/AI%E7%AD%96%E7%95%A5-%E8%82%A1%E7%A5%A8%E4%BB%A3%E7%A0%81%E8%BF%87%E6%BB%A4.ipynb


我如何在策略中过滤掉ST股票呢???
我如何在策略中过滤掉ST股票呢???
000511退市股票出现在策略中该如何处理?
(xuan) #2

ST是要ST股票?正常是不要ST股票?*ST是什么意思?暂停上市呢?


(xuan) #3
克隆策略

1.带有止损的滚动策略

    可以测试多个因子的效果。
  • 1.特征
      ta_sma(close_0,80)-ta_sma(close_0,20)
      rank_fs_roe_ttm_0
    
    2.收益收益率 141.6% 年化收益率 16.24% 基准收益率 46.11% 阿尔法 0.12 贝塔 0.3 夏普比率 0.79 胜率 0.55 盈亏比 1.02 收益波动率 17.13% 信息比率 0.02 最大回撤 38.95%
  • 2.筹码

      winner
In [ ]:
 

    {"Description":"实验创建于2017/9/28","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-106:features","SourceOutputPortId":"-315:data"},{"DestinationInputPortId":"-115:features","SourceOutputPortId":"-315:data"},{"DestinationInputPortId":"-122:features","SourceOutputPortId":"-315:data"},{"DestinationInputPortId":"-129:features","SourceOutputPortId":"-315:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"-2125:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53: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:model","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:model"},{"DestinationInputPortId":"-122:instruments","SourceOutputPortId":"-2639:data"},{"DestinationInputPortId":"-141:instruments","SourceOutputPortId":"-2639:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-2669:data"},{"DestinationInputPortId":"-141:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"-2125:instruments","SourceOutputPortId":"-4129:data"},{"DestinationInputPortId":"-115:instruments","SourceOutputPortId":"-4129:data"},{"DestinationInputPortId":"-165:input_1","SourceOutputPortId":"-106:data"},{"DestinationInputPortId":"-174:input_data","SourceOutputPortId":"-115:data"},{"DestinationInputPortId":"-183:input_data","SourceOutputPortId":"-122:data"},{"DestinationInputPortId":"-946:input_1","SourceOutputPortId":"-129:data"},{"DestinationInputPortId":"-106:input_data","SourceOutputPortId":"-174:data"},{"DestinationInputPortId":"-129:input_data","SourceOutputPortId":"-183:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-165:data_1"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:features","SourceOutputPortId":"-938:data"},{"DestinationInputPortId":"-2669:input_data","SourceOutputPortId":"-946:data_1"}],"ModuleNodes":[{"Id":"-315","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"open_0\nclose_0\nadjust_factor_0\nturn_0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-315"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-315","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"-2125","ModuleId":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html\n# 添加benchmark_前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na_label","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"cast_label_int","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-2125"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-2125","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"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":6,"Comment":"","CommentCollapsed":true},{"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":7,"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":30,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":20,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"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":8,"Comment":"","CommentCollapsed":true},{"Id":"-2639","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2019-03-22","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":"-2639"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-2639","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"Comment":"","CommentCollapsed":true},{"Id":"-2669","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-2669"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-2669","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"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":14,"Comment":"","CommentCollapsed":true},{"Id":"-4129","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2011-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-4129"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-4129","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"Comment":"","CommentCollapsed":true},{"Id":"-106","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":"-106"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-106"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-106","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"Comment":"在衍生特征里配置自定义函数就可以了,也可以覆盖同名的预定义函数","CommentCollapsed":true},{"Id":"-115","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":"90","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-115"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-115"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-115","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"Comment":"","CommentCollapsed":true},{"Id":"-122","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":"90","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-122"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-122"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-122","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"Comment":"","CommentCollapsed":true},{"Id":"-129","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":"-129"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-129"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-129","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":17,"Comment":"在衍生特征里配置自定义函数就可以了,也可以覆盖同名的预定义函数","CommentCollapsed":true},{"Id":"-141","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"import talib\ndef benchmark_sma_risk(context,data):\n '''\n 大盘max_down 大于4\n '''\n today_date = data.current_dt.strftime('%Y-%m-%d')\n start_date= (pd.to_datetime(today_date) - datetime.timedelta(days=15)).strftime('%Y-%m-%d') \n benchmark_data=DataSource('bar1d_index_CN_STOCK_A').read(instruments=['000001.HIX'],fields=['close'],start_date=start_date,end_date=today_date)\n benchmark_close=benchmark_data.set_index('date').close\n benchmark_signal=benchmark_close[-1]/benchmark_close[-5:].max()-1<-0.04 \n return benchmark_signal\n \n\n# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n #获取当日日期\n today_date = data.current_dt.strftime('%Y-%m-%d')\n \n #大盘风控模块,读取风控数据 \n benckmark_risk=benchmark_sma_risk(context,data)\n #当risk为1时,市场有风险,全部平仓,不再执行其它操作\n if benckmark_risk :\n position_all = context.portfolio.positions.keys()\n for i in position_all:\n context.order_target(i, 0)\n print(today_date,'大盘风控止损触发,全仓卖出')\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.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n #---------------------------START:止赢止损模块(含建仓期)--------------------\n # 新建当日止赢止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断\n current_stopwin_stock=[]\n current_stoploss_stock = [] \n today_date = data.current_dt.strftime('%Y-%m-%d')\n positions_stop={e.symbol:p.cost_basis \n for e,p in context.portfolio.positions.items()}\n if len(positions_stop)>0:\n for i in positions_stop.keys():\n stock_cost=positions_stop[i] \n stock_market_price=data.current(context.symbol(i),'price') \n # 赚30%且为可交易状态就止盈\n if stock_market_price/stock_cost-1>0.8 and data.can_trade(context.symbol(i)) and not context.has_unfinished_sell_order(i):\n context.order_target_percent(context.symbol(i),0) \n current_stopwin_stock.append(i)\n # 亏10%并且为可交易状态就止损\n if stock_market_price/stock_cost-1 <= -0.05 and data.can_trade(context.symbol(i)) and not context.has_unfinished_sell_order(i): \n context.order_target_percent(context.symbol(i),0) \n current_stoploss_stock.append(i)\n if len(current_stopwin_stock)>0:\n print(today_date,'止盈股票列表',current_stopwin_stock)\n if len(current_stoploss_stock)>0:\n print(today_date,'止损股票列表',current_stoploss_stock)\n #--------------------------END: 止赢止损模块-----------------------------\n \n #--------------------------START:持有固定天数卖出(不含建仓期)---------------\n current_stopdays_stock = [] \n today = data.current_dt\n today_date = data.current_dt.strftime('%Y-%m-%d')\n # 不是建仓期(在前hold_days属于建仓期)\n if not is_staging:\n equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}\n if len(equities)>0:\n for i in equities:\n sid = equities[i].sid # 交易标的\n #如果上面的止盈止损已经卖出过了,就不要重复卖出以防止产生空单\n if i in current_stopwin_stock+current_stoploss_stock:\n continue\n # 今天和上次交易的时间相隔hold_days就全部卖出 datetime.timedelta(context.options['hold_days'])也可以换成自己需要的天数,比如datetime.timedelta(5)\n if today-equities[i].last_sale_date>=datetime.timedelta(5) and data.can_trade(context.symbol(i)) and not context.has_unfinished_sell_order(equities[i]):\n context.order_target_percent(sid, 0)\n current_stopdays_stock.append(i)\n if len(current_stopdays_stock)>0: \n print(today_date,'固定天数卖出列表',current_stopdays_stock)\n #-------------------------------END:持有固定天数卖出-------------------------- \n \n \n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰\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 for instrument in instruments:\n #防止多个止损条件同时满足,出现多次卖出产生空单\n if instrument not in current_stopdays_stock+current_stopwin_stock+current_stoploss_stock:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n else:\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_tmp = list(ranker_prediction.instrument)\n #防止卖出后再次买入\n buy_instruments=[k for k in buy_instruments_tmp if k not in current_stopdays_stock+current_stopwin_stock+current_stoploss_stock][: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","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","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.00012, sell_cost=0.0013, min_cost=0))\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.options['hold_days'] = 5\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":"100000","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.SHA","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-141"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-141"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-141"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-141"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-141"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-141","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":19,"Comment":"","CommentCollapsed":true},{"Id":"-174","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%3Atrue%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%3Afalse%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":"-174"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-174","OutputType":null},{"Name":"left_data","NodeId":"-174","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":22,"Comment":"","CommentCollapsed":true},{"Id":"-183","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%3Atrue%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%3Afalse%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":"-183"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-183","OutputType":null},{"Name":"left_data","NodeId":"-183","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":20,"Comment":"","CommentCollapsed":true},{"Id":"-4248","ModuleId":"BigQuantSpace.hyper_rolling_train.hyper_rolling_train-v1","ModuleParameters":[{"Name":"run","Value":"def bigquant_run(\n bq_graph,\n inputs,\n trading_days_market='CN', # 使用那个市场的交易日历, TODO\n train_instruments_mid='m18', # 训练数据 证券代码列表 模块id\n test_instruments_mid='m10', # 测试数据 证券代码列表 模块id\n predict_mid='m14', # 预测 模块id\n trade_mid='m19', # 回测 模块id\n start_date='2010-01-01', # 数据开始日期\n end_date=T.live_run_param('trading_date', '2019-03-29'), # 数据结束日期\n train_update_days=250, # 更新周期,按交易日计算,每多少天更新一次\n train_update_days_for_live=None, #模拟实盘模式下的更新周期,按交易日计算,每多少天更新一次。如果需要在模拟实盘阶段使用不同的模型更新周期,可以设置这个参数\n train_data_min_days=250*3, # 最小数据天数,按交易日计算,所以第一个滚动的结束日期是 从开始日期到开始日期+最小数据天数\n train_data_max_days=250*3, # 最大数据天数,按交易日计算,0,表示没有限制,否则每一个滚动的开始日期=max(此滚动的结束日期-最大数据天数, 开始日期\n rolling_count_for_live=1, #实盘模式下滚动次数,模拟实盘模式下,取最后多少次滚动。一般在模拟实盘模式下,只用到最后一次滚动训练的模型,这里可以设置为1;如果你的滚动训练数据时间段很短,以至于期间可能没有训练数据,这里可以设置大一点。0表示没有限制\n):\n def merge_datasources(input_1):\n df_list = [ds[0].read_df().set_index('date').ix[ds[1]:].reset_index() for ds in input_1]\n df = pd.concat(df_list)\n instrument_data = {\n 'start_date': df['date'].min().strftime('%Y-%m-%d'),\n 'end_date': df['date'].max().strftime('%Y-%m-%d'),\n 'instruments': list(set(df['instrument'])),\n }\n return Outputs(data=DataSource.write_df(df), instrument_data=DataSource.write_pickle(instrument_data))\n\n def gen_rolling_dates(trading_days_market, start_date, end_date, train_update_days, train_update_days_for_live, train_data_min_days, train_data_max_days, rolling_count_for_live):\n # 是否实盘模式\n tdays = list(D.trading_days(market=trading_days_market, start_date=start_date, end_date=end_date)['date'])\n is_live_run = T.live_run_param('trading_date', None) is not None\n\n if is_live_run and train_update_days_for_live:\n train_update_days = train_update_days_for_live\n\n rollings = []\n train_end_date = train_data_min_days\n while train_end_date < len(tdays):\n if train_data_max_days is not None:\n train_start_date = max(train_end_date - train_data_max_days, 0)\n else:\n train_start_date = start_date\n rollings.append({\n 'train_start_date': tdays[train_start_date].strftime('%Y-%m-%d'),\n 'train_end_date': tdays[train_end_date - 1].strftime('%Y-%m-%d'),\n 'test_start_date': tdays[train_end_date].strftime('%Y-%m-%d'),\n 'test_end_date': tdays[min(train_end_date + train_update_days, len(tdays)) - 1].strftime('%Y-%m-%d'),\n })\n train_end_date += train_update_days\n\n if not rollings:\n raise Exception('没有滚动需要执行,请检查配置')\n\n if is_live_run and rolling_count_for_live:\n rollings = rollings[-rolling_count_for_live:]\n\n return rollings\n\n g = bq_graph\n\n rolling_dates = gen_rolling_dates(\n trading_days_market, start_date, end_date, train_update_days, train_update_days_for_live, train_data_min_days, train_data_max_days, rolling_count_for_live)\n\n # 训练和预测\n results = []\n for rolling in rolling_dates:\n parameters = {}\n # 先禁用回测\n parameters[trade_mid + '.__enabled__'] = False\n parameters[train_instruments_mid + '.start_date'] = rolling['train_start_date']\n parameters[train_instruments_mid + '.end_date'] = rolling['train_end_date']\n parameters[test_instruments_mid + '.start_date'] = rolling['test_start_date']\n parameters[test_instruments_mid + '.end_date'] = rolling['test_end_date']\n # print('------ rolling_train:', parameters)\n results.append(g.run(parameters))\n\n # 合并预测结果并回测\n mx = M.cached.v3(run=merge_datasources, input_1=[[result[predict_mid].predictions, result[test_instruments_mid].data.read_pickle()['start_date']] for result in results])\n parameters = {}\n parameters['*.__enabled__'] = False\n parameters[trade_mid + '.__enabled__'] = True\n parameters[trade_mid + '.instruments'] = mx.instrument_data\n parameters[trade_mid + '.options_data'] = mx.data\n\n trade = g.run(parameters)\n\n return {'rollings': results, 'trade': trade}\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"run_now","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"bq_graph","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"bq_graph_port","NodeId":"-4248"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-4248"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-4248"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-4248"}],"OutputPortsInternal":[{"Name":"result","NodeId":"-4248","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":2,"Comment":"","CommentCollapsed":true},{"Id":"-165","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"#筹码分布\ndef cal_winner_day(df_all):\n winner=[]\n for k in list(df_all.date):\n df=df_all[df_all.date<=k]\n df['real_close']=df['close_0']/df['adjust_factor_0']#获取真实收盘价\n df['real_open']=df['open_0']/df['adjust_factor_0']#获取真实开盘价\n df['turn']=df['turn_0']/100#获取换手率\n df['avg_price']=np.round(df['real_close']+df['real_open'])/2#计算每日平均成本,这里按照0.5元一个价位做分析\n df=df.sort_values(by='date',ascending=False).reset_index(drop=True)#日期按降序排列\n df['turn_tomo']=df['turn'].shift(1)#计算明日的换手率\n df['remain_day']=1-df['turn_tomo'] #计算当日的剩余筹码比例\n #假设N日后,上市第一天的剩余筹码比率就是每日剩余比例的累乘即:剩余筹码比例=(1-明天换手率)*(1-后日换手率)*...*(1-最新日换手率),以此类推各日的剩余筹码\n df['remain_his']=df['remain_day'].cumprod()\n df['remain_his']=df['remain_his']*df['turn']\n df['remain_his']=df['remain_his'].fillna(df['turn'])#最新一日的筹码就是当日的换手率\n #关键统计,统计最后一天的各价位历史筹码堆积量(百分比)\n ss=df.groupby('avg_price')[['remain_his']].sum().rename(columns={'remain_his':'筹码量'}).reset_index()\n ss['real_close']=df['real_close'].iloc[0]\n #计算end_date时收盘价的获利比例\n winner_day=ss[ss.avg_price<=ss.real_close]['筹码量'].sum()\n winner.append(winner_day)\n result=pd.DataFrame({'winner':winner},index=df_all.date)\n return result\n\n# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read()\n win=df.groupby('instrument').apply(cal_winner_day)\n df=win.reset_index().merge(df,on=['date','instrument'],how='right')\n \n data_1 = DataSource.write_df(df)\n \n return Outputs(data_1=data_1, data_2=None, data_3=None)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-165"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-165"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-165"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-165","OutputType":null},{"Name":"data_2","NodeId":"-165","OutputType":null},{"Name":"data_3","NodeId":"-165","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":11,"Comment":"","CommentCollapsed":true},{"Id":"-938","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"winner","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-938"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-938","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"Comment":"","CommentCollapsed":true},{"Id":"-946","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"#筹码分布\ndef cal_winner_day(df_all):\n winner=[]\n for k in list(df_all.date):\n df=df_all[df_all.date<=k]\n df['real_close']=df['close_0']/df['adjust_factor_0']#获取真实收盘价\n df['real_open']=df['open_0']/df['adjust_factor_0']#获取真实开盘价\n df['turn']=df['turn_0']/100#获取换手率\n df['avg_price']=np.round(df['real_close']+df['real_open'])/2#计算每日平均成本,这里按照0.5元一个价位做分析\n df=df.sort_values(by='date',ascending=False).reset_index(drop=True)#日期按降序排列\n df['turn_tomo']=df['turn'].shift(1)#计算明日的换手率\n df['remain_day']=1-df['turn_tomo'] #计算当日的剩余筹码比例\n #假设N日后,上市第一天的剩余筹码比率就是每日剩余比例的累乘即:剩余筹码比例=(1-明天换手率)*(1-后日换手率)*...*(1-最新日换手率),以此类推各日的剩余筹码\n df['remain_his']=df['remain_day'].cumprod()\n df['remain_his']=df['remain_his']*df['turn']\n df['remain_his']=df['remain_his'].fillna(df['turn'])#最新一日的筹码就是当日的换手率\n #关键统计,统计最后一天的各价位历史筹码堆积量(百分比)\n ss=df.groupby('avg_price')[['remain_his']].sum().rename(columns={'remain_his':'筹码量'}).reset_index()\n ss['real_close']=df['real_close'].iloc[0]\n #计算end_date时收盘价的获利比例\n winner_day=ss[ss.avg_price<=ss.real_close]['筹码量'].sum()\n winner.append(winner_day)\n result=pd.DataFrame({'winner':winner},index=df_all.date)\n return result\n\n# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3):\n # 示例代码如下。在这里编写您的代码\n df=input_1.read()\n win=df.groupby('instrument').apply(cal_winner_day)\n df=win.reset_index().merge(df,on=['date','instrument'],how='right')\n \n data_1 = DataSource.write_df(df)\n \n return Outputs(data_1=data_1, data_2=None, data_3=None)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-946"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-946"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-946"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-946","OutputType":null},{"Name":"data_2","NodeId":"-946","OutputType":null},{"Name":"data_3","NodeId":"-946","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"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='-315' Position='283.4453430175781,-276.78965759277344,200,200'/><NodePosition Node='-2125' Position='-462,-4,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='-400,240,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='-108.78965759277344,307.94830322265625,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-43' Position='42.737945556640625,402.15863037109375,200,200'/><NodePosition Node='-2639' Position='722,-224,200,200'/><NodePosition Node='-2669' Position='707,381,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='313,494,200,200'/><NodePosition Node='-4129' Position='-329,-226,200,200'/><NodePosition Node='-106' Position='-97,86,200,200'/><NodePosition Node='-115' Position='-106,-97,200,200'/><NodePosition Node='-122' Position='796,-57,200,200'/><NodePosition Node='-129' Position='773.572265625,180.26556396484375,200,200'/><NodePosition Node='-141' Position='447,623,200,200'/><NodePosition Node='-174' Position='-92,-11,200,200'/><NodePosition Node='-183' Position='811.6827392578125,40.73795700073242,200,200'/><NodePosition Node='-4248' Position='-368,489.10693359375,200,200'/><NodePosition Node='-165' Position='-88,177,200,200'/><NodePosition Node='-938' Position='317,172,200,200'/><NodePosition Node='-946' Position='780.6827392578125,286.73797607421875,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 [2]:
    # 本代码由可视化策略环境自动生成 2019年4月1日 12:02
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    #筹码分布
    def cal_winner_day(df_all):
        winner=[]
        for k in list(df_all.date):
            df=df_all[df_all.date<=k]
            df['real_close']=df['close_0']/df['adjust_factor_0']#获取真实收盘价
            df['real_open']=df['open_0']/df['adjust_factor_0']#获取真实开盘价
            df['turn']=df['turn_0']/100#获取换手率
            df['avg_price']=np.round(df['real_close']+df['real_open'])/2#计算每日平均成本,这里按照0.5元一个价位做分析
            df=df.sort_values(by='date',ascending=False).reset_index(drop=True)#日期按降序排列
            df['turn_tomo']=df['turn'].shift(1)#计算明日的换手率
            df['remain_day']=1-df['turn_tomo'] #计算当日的剩余筹码比例
            #假设N日后,上市第一天的剩余筹码比率就是每日剩余比例的累乘即:剩余筹码比例=(1-明天换手率)*(1-后日换手率)*...*(1-最新日换手率),以此类推各日的剩余筹码
            df['remain_his']=df['remain_day'].cumprod()
            df['remain_his']=df['remain_his']*df['turn']
            df['remain_his']=df['remain_his'].fillna(df['turn'])#最新一日的筹码就是当日的换手率
            #关键统计,统计最后一天的各价位历史筹码堆积量(百分比)
            ss=df.groupby('avg_price')[['remain_his']].sum().rename(columns={'remain_his':'筹码量'}).reset_index()
            ss['real_close']=df['real_close'].iloc[0]
            #计算end_date时收盘价的获利比例
            winner_day=ss[ss.avg_price<=ss.real_close]['筹码量'].sum()
            winner.append(winner_day)
        result=pd.DataFrame({'winner':winner},index=df_all.date)
        return result
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m12_run_bigquant_run(input_1, input_2, input_3):
        # 示例代码如下。在这里编写您的代码
        df=input_1.read()
        win=df.groupby('instrument').apply(cal_winner_day)
        df=win.reset_index().merge(df,on=['date','instrument'],how='right')
        
        data_1 = DataSource.write_df(df)
        
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m12_post_run_bigquant_run(outputs):
        return outputs
    
    #筹码分布
    def cal_winner_day(df_all):
        winner=[]
        for k in list(df_all.date):
            df=df_all[df_all.date<=k]
            df['real_close']=df['close_0']/df['adjust_factor_0']#获取真实收盘价
            df['real_open']=df['open_0']/df['adjust_factor_0']#获取真实开盘价
            df['turn']=df['turn_0']/100#获取换手率
            df['avg_price']=np.round(df['real_close']+df['real_open'])/2#计算每日平均成本,这里按照0.5元一个价位做分析
            df=df.sort_values(by='date',ascending=False).reset_index(drop=True)#日期按降序排列
            df['turn_tomo']=df['turn'].shift(1)#计算明日的换手率
            df['remain_day']=1-df['turn_tomo'] #计算当日的剩余筹码比例
            #假设N日后,上市第一天的剩余筹码比率就是每日剩余比例的累乘即:剩余筹码比例=(1-明天换手率)*(1-后日换手率)*...*(1-最新日换手率),以此类推各日的剩余筹码
            df['remain_his']=df['remain_day'].cumprod()
            df['remain_his']=df['remain_his']*df['turn']
            df['remain_his']=df['remain_his'].fillna(df['turn'])#最新一日的筹码就是当日的换手率
            #关键统计,统计最后一天的各价位历史筹码堆积量(百分比)
            ss=df.groupby('avg_price')[['remain_his']].sum().rename(columns={'remain_his':'筹码量'}).reset_index()
            ss['real_close']=df['real_close'].iloc[0]
            #计算end_date时收盘价的获利比例
            winner_day=ss[ss.avg_price<=ss.real_close]['筹码量'].sum()
            winner.append(winner_day)
        result=pd.DataFrame({'winner':winner},index=df_all.date)
        return result
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m11_run_bigquant_run(input_1, input_2, input_3):
        # 示例代码如下。在这里编写您的代码
        df=input_1.read()
        win=df.groupby('instrument').apply(cal_winner_day)
        df=win.reset_index().merge(df,on=['date','instrument'],how='right')
        
        data_1 = DataSource.write_df(df)
        
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m11_post_run_bigquant_run(outputs):
        return outputs
    
    import talib
    def benchmark_sma_risk(context,data):
        '''
        大盘max_down 大于4
        '''
        today_date = data.current_dt.strftime('%Y-%m-%d')
        start_date= (pd.to_datetime(today_date) - datetime.timedelta(days=15)).strftime('%Y-%m-%d') 
        benchmark_data=DataSource('bar1d_index_CN_STOCK_A').read(instruments=['000001.HIX'],fields=['close'],start_date=start_date,end_date=today_date)
        benchmark_close=benchmark_data.set_index('date').close
        benchmark_signal=benchmark_close[-1]/benchmark_close[-5:].max()-1<-0.04    
        return benchmark_signal
        
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_handle_data_bigquant_run(context, data):
        #获取当日日期
        today_date = data.current_dt.strftime('%Y-%m-%d')
        
        #大盘风控模块,读取风控数据        
        benckmark_risk=benchmark_sma_risk(context,data)
        #当risk为1时,市场有风险,全部平仓,不再执行其它操作
        if benckmark_risk :
            position_all = context.portfolio.positions.keys()
            for i in position_all:
                context.order_target(i, 0)
            print(today_date,'大盘风控止损触发,全仓卖出')
            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.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
    
        #---------------------------START:止赢止损模块(含建仓期)--------------------
        # 新建当日止赢止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
        current_stopwin_stock=[]
        current_stoploss_stock = []   
        today_date = data.current_dt.strftime('%Y-%m-%d')
        positions_stop={e.symbol:p.cost_basis 
        for e,p in context.portfolio.positions.items()}
        if len(positions_stop)>0:
            for i in positions_stop.keys():
                stock_cost=positions_stop[i]  
                stock_market_price=data.current(context.symbol(i),'price')  
                # 赚30%且为可交易状态就止盈
                if stock_market_price/stock_cost-1>0.8 and data.can_trade(context.symbol(i)) and not context.has_unfinished_sell_order(i):
                    context.order_target_percent(context.symbol(i),0)      
                    current_stopwin_stock.append(i)
                # 亏10%并且为可交易状态就止损
                if stock_market_price/stock_cost-1 <= -0.05 and data.can_trade(context.symbol(i)) and not context.has_unfinished_sell_order(i):   
                    context.order_target_percent(context.symbol(i),0)     
                    current_stoploss_stock.append(i)
            if len(current_stopwin_stock)>0:
                print(today_date,'止盈股票列表',current_stopwin_stock)
            if len(current_stoploss_stock)>0:
                print(today_date,'止损股票列表',current_stoploss_stock)
        #--------------------------END: 止赢止损模块-----------------------------
        
        #--------------------------START:持有固定天数卖出(不含建仓期)---------------
        current_stopdays_stock = [] 
        today = data.current_dt
        today_date = data.current_dt.strftime('%Y-%m-%d')
        # 不是建仓期(在前hold_days属于建仓期)
        if not is_staging:
            equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
            if len(equities)>0:
                for i in equities:
                    sid = equities[i].sid  # 交易标的
                    #如果上面的止盈止损已经卖出过了,就不要重复卖出以防止产生空单
                    if i in current_stopwin_stock+current_stoploss_stock:
                        continue
                    # 今天和上次交易的时间相隔hold_days就全部卖出 datetime.timedelta(context.options['hold_days'])也可以换成自己需要的天数,比如datetime.timedelta(5)
                    if today-equities[i].last_sale_date>=datetime.timedelta(5) and data.can_trade(context.symbol(i)) and not context.has_unfinished_sell_order(equities[i]):
                        context.order_target_percent(sid, 0)
                        current_stopdays_stock.append(i)
                if len(current_stopdays_stock)>0:        
                    print(today_date,'固定天数卖出列表',current_stopdays_stock)
        #-------------------------------END:持有固定天数卖出--------------------------    
        
        
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
        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]))])))
            for instrument in instruments:
                #防止多个止损条件同时满足,出现多次卖出产生空单
                if instrument not in current_stopdays_stock+current_stopwin_stock+current_stoploss_stock:
                    context.order_target(context.symbol(instrument), 0)
                    cash_for_sell -= positions[instrument]
                else:
                    cash_for_sell -= positions[instrument]
                if cash_for_sell <= 0:
                    break
    
        # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
        buy_cash_weights = context.stock_weights
        buy_instruments_tmp = list(ranker_prediction.instrument)
        #防止卖出后再次买入
        buy_instruments=[k for k in buy_instruments_tmp if k not in current_stopdays_stock+current_stopwin_stock+current_stoploss_stock][: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_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:初始化函数,只执行一次
    def m19_initialize_bigquant_run(context):
        # 加载预测数据
        context.ranker_prediction = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.00012, sell_cost=0.0013, min_cost=0))
        # 预测数据,通过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.options['hold_days'] = 5
    
    
    g = T.Graph({
    
        'm1': 'M.input_features.v1',
        'm1.features': """open_0
    close_0
    adjust_factor_0
    turn_0""",
    
        'm10': 'M.instruments.v2',
        'm10.start_date': T.live_run_param('trading_date', '2017-01-01'),
        'm10.end_date': T.live_run_param('trading_date', '2019-03-22'),
        'm10.market': 'CN_STOCK_A',
        'm10.instrument_list': '',
        'm10.max_count': 0,
    
        'm16': 'M.general_feature_extractor.v7',
        'm16.instruments': T.Graph.OutputPort('m10.data'),
        'm16.features': T.Graph.OutputPort('m1.data'),
        'm16.start_date': '',
        'm16.end_date': '',
        'm16.before_start_days': 90,
    
        'm20': 'M.chinaa_stock_filter.v1',
        'm20.input_data': T.Graph.OutputPort('m16.data'),
        'm20.index_constituent_cond': ['全部'],
        'm20.board_cond': ['全部'],
        'm20.industry_cond': ['全部'],
        'm20.st_cond': ['全部'],
        'm20.output_left_data': False,
    
        'm17': 'M.derived_feature_extractor.v3',
        'm17.input_data': T.Graph.OutputPort('m20.data'),
        'm17.features': T.Graph.OutputPort('m1.data'),
        'm17.date_col': 'date',
        'm17.instrument_col': 'instrument',
        'm17.drop_na': False,
        'm17.remove_extra_columns': False,
        'm17.m_cached': False,
    
        'm12': 'M.cached.v3',
        'm12.input_1': T.Graph.OutputPort('m17.data'),
        'm12.run': m12_run_bigquant_run,
        'm12.post_run': m12_post_run_bigquant_run,
        'm12.input_ports': '',
        'm12.params': '{}',
        'm12.output_ports': '',
    
        'm13': 'M.dropnan.v1',
        'm13.input_data': T.Graph.OutputPort('m12.data_1'),
    
        'm18': 'M.instruments.v2',
        'm18.start_date': '2011-01-01',
        'm18.end_date': '2017-01-01',
        'm18.market': 'CN_STOCK_A',
        'm18.instrument_list': '',
        'm18.max_count': 0,
    
        'm5': 'M.advanced_auto_labeler.v2',
        'm5.instruments': T.Graph.OutputPort('m18.data'),
        'm5.label_expr': """# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html
    #   添加benchmark_前缀,可使用对应的benchmark数据
    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_
    
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    shift(close, -5) / shift(open, -1)
    
    # 极值处理:用1%和99%分位的值做clip
    clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
    
    # 将分数映射到分类,这里使用20个分类
    all_wbins(label, 20)
    
    # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
    where(shift(high, -1) == shift(low, -1), NaN, label)
    """,
        'm5.start_date': '',
        'm5.end_date': '',
        'm5.benchmark': '000300.SHA',
        'm5.drop_na_label': True,
        'm5.cast_label_int': True,
        'm5.user_functions': {},
    
        'm9': 'M.general_feature_extractor.v7',
        'm9.instruments': T.Graph.OutputPort('m18.data'),
        'm9.features': T.Graph.OutputPort('m1.data'),
        'm9.start_date': '',
        'm9.end_date': '',
        'm9.before_start_days': 90,
    
        'm22': 'M.chinaa_stock_filter.v1',
        'm22.input_data': T.Graph.OutputPort('m9.data'),
        'm22.index_constituent_cond': ['全部'],
        'm22.board_cond': ['全部'],
        'm22.industry_cond': ['全部'],
        'm22.st_cond': ['全部'],
        'm22.output_left_data': False,
    
        'm3': 'M.derived_feature_extractor.v3',
        'm3.input_data': T.Graph.OutputPort('m22.data'),
        'm3.features': T.Graph.OutputPort('m1.data'),
        'm3.date_col': 'date',
        'm3.instrument_col': 'instrument',
        'm3.drop_na': False,
        'm3.remove_extra_columns': False,
    
        'm11': 'M.cached.v3',
        'm11.input_1': T.Graph.OutputPort('m3.data'),
        'm11.run': m11_run_bigquant_run,
        'm11.post_run': m11_post_run_bigquant_run,
        'm11.input_ports': '',
        'm11.params': '{}',
        'm11.output_ports': '',
    
        'm6': 'M.join.v3',
        'm6.data1': T.Graph.OutputPort('m5.data'),
        'm6.data2': T.Graph.OutputPort('m11.data_1'),
        'm6.on': 'date,instrument',
        'm6.how': 'inner',
        'm6.sort': False,
    
        'm7': 'M.dropnan.v1',
        'm7.input_data': T.Graph.OutputPort('m6.data'),
    
        'm4': 'M.input_features.v1',
        'm4.features': 'winner',
    
        'm8': 'M.stock_ranker_train.v5',
        'm8.training_ds': T.Graph.OutputPort('m7.data'),
        'm8.features': T.Graph.OutputPort('m4.data'),
        'm8.learning_algorithm': '排序',
        'm8.number_of_leaves': 30,
        'm8.minimum_docs_per_leaf': 1000,
        'm8.number_of_trees': 20,
        'm8.learning_rate': 0.1,
        'm8.max_bins': 1023,
        'm8.feature_fraction': 1,
        'm8.m_lazy_run': False,
    
        'm14': 'M.stock_ranker_predict.v5',
        'm14.model': T.Graph.OutputPort('m8.model'),
        'm14.data': T.Graph.OutputPort('m13.data'),
        'm14.m_lazy_run': False,
    
        'm19': 'M.trade.v4',
        'm19.instruments': T.Graph.OutputPort('m10.data'),
        'm19.options_data': T.Graph.OutputPort('m14.predictions'),
        'm19.start_date': '',
        'm19.end_date': '',
        'm19.handle_data': m19_handle_data_bigquant_run,
        'm19.prepare': m19_prepare_bigquant_run,
        'm19.initialize': m19_initialize_bigquant_run,
        'm19.volume_limit': 0.025,
        'm19.order_price_field_buy': 'open',
        'm19.order_price_field_sell': 'close',
        'm19.capital_base': 100000,
        'm19.auto_cancel_non_tradable_orders': True,
        'm19.data_frequency': 'daily',
        'm19.price_type': '后复权',
        'm19.product_type': '股票',
        'm19.plot_charts': True,
        'm19.backtest_only': False,
        'm19.benchmark': '000300.SHA',
    })
    
    # g.run({})
    
    
    def m2_run_bigquant_run(
        bq_graph,
        inputs,
        trading_days_market='CN', # 使用那个市场的交易日历, TODO
        train_instruments_mid='m18', # 训练数据 证券代码列表 模块id
        test_instruments_mid='m10', # 测试数据 证券代码列表 模块id
        predict_mid='m14', # 预测 模块id
        trade_mid='m19', # 回测 模块id
        start_date='2010-01-01', # 数据开始日期
        end_date=T.live_run_param('trading_date', '2019-03-29'), # 数据结束日期
        train_update_days=250, # 更新周期,按交易日计算,每多少天更新一次
        train_update_days_for_live=None, #模拟实盘模式下的更新周期,按交易日计算,每多少天更新一次。如果需要在模拟实盘阶段使用不同的模型更新周期,可以设置这个参数
        train_data_min_days=250*3, # 最小数据天数,按交易日计算,所以第一个滚动的结束日期是 从开始日期到开始日期+最小数据天数
        train_data_max_days=250*3, # 最大数据天数,按交易日计算,0,表示没有限制,否则每一个滚动的开始日期=max(此滚动的结束日期-最大数据天数, 开始日期
        rolling_count_for_live=1, #实盘模式下滚动次数,模拟实盘模式下,取最后多少次滚动。一般在模拟实盘模式下,只用到最后一次滚动训练的模型,这里可以设置为1;如果你的滚动训练数据时间段很短,以至于期间可能没有训练数据,这里可以设置大一点。0表示没有限制
    ):
        def merge_datasources(input_1):
            df_list = [ds[0].read_df().set_index('date').ix[ds[1]:].reset_index() for ds in input_1]
            df = pd.concat(df_list)
            instrument_data = {
                'start_date': df['date'].min().strftime('%Y-%m-%d'),
                'end_date': df['date'].max().strftime('%Y-%m-%d'),
                'instruments': list(set(df['instrument'])),
            }
            return Outputs(data=DataSource.write_df(df), instrument_data=DataSource.write_pickle(instrument_data))
    
        def gen_rolling_dates(trading_days_market, start_date, end_date, train_update_days, train_update_days_for_live, train_data_min_days, train_data_max_days, rolling_count_for_live):
            # 是否实盘模式
            tdays = list(D.trading_days(market=trading_days_market, start_date=start_date, end_date=end_date)['date'])
            is_live_run = T.live_run_param('trading_date', None) is not None
    
            if is_live_run and train_update_days_for_live:
                train_update_days = train_update_days_for_live
    
            rollings = []
            train_end_date = train_data_min_days
            while train_end_date < len(tdays):
                if train_data_max_days is not None:
                    train_start_date = max(train_end_date - train_data_max_days, 0)
                else:
                    train_start_date = start_date
                rollings.append({
                    'train_start_date': tdays[train_start_date].strftime('%Y-%m-%d'),
                    'train_end_date': tdays[train_end_date - 1].strftime('%Y-%m-%d'),
                    'test_start_date': tdays[train_end_date].strftime('%Y-%m-%d'),
                    'test_end_date': tdays[min(train_end_date + train_update_days, len(tdays)) - 1].strftime('%Y-%m-%d'),
                })
                train_end_date += train_update_days
    
            if not rollings:
                raise Exception('没有滚动需要执行,请检查配置')
    
            if is_live_run and rolling_count_for_live:
                rollings = rollings[-rolling_count_for_live:]
    
            return rollings
    
        g = bq_graph
    
        rolling_dates = gen_rolling_dates(
            trading_days_market, start_date, end_date, train_update_days, train_update_days_for_live, train_data_min_days, train_data_max_days, rolling_count_for_live)
    
        # 训练和预测
        results = []
        for rolling in rolling_dates:
            parameters = {}
            # 先禁用回测
            parameters[trade_mid + '.__enabled__'] = False
            parameters[train_instruments_mid + '.start_date'] = rolling['train_start_date']
            parameters[train_instruments_mid + '.end_date'] = rolling['train_end_date']
            parameters[test_instruments_mid + '.start_date'] = rolling['test_start_date']
            parameters[test_instruments_mid + '.end_date'] = rolling['test_end_date']
            # print('------ rolling_train:', parameters)
            results.append(g.run(parameters))
    
        # 合并预测结果并回测
        mx = M.cached.v3(run=merge_datasources, input_1=[[result[predict_mid].predictions, result[test_instruments_mid].data.read_pickle()['start_date']] for result in results])
        parameters = {}
        parameters['*.__enabled__'] = False
        parameters[trade_mid + '.__enabled__'] = True
        parameters[trade_mid + '.instruments'] = mx.instrument_data
        parameters[trade_mid + '.options_data'] = mx.data
    
        trade = g.run(parameters)
    
        return {'rollings': results, 'trade': trade}
    
    
    m2 = M.hyper_rolling_train.v1(
        run=m2_run_bigquant_run,
        run_now=True,
        bq_graph=g
    )
    
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-2-34ba200cff51> in <module>()
         73     industry_cond=['全部'],
         74     st_cond=['全部'],
    ---> 75     output_left_data=False
         76 )
         77 
    
    AttributeError: 'NoneType' object has no attribute 'values'
    In [ ]:
     
    
    In [ ]:
    def cal_winner_day(df_all):
        winner=[]
        for k in list(df_all.date):
            df=df_all[df_all.date<=k]
            df['real_close']=df['close']/df['adjust_factor']#获取真实收盘价
            df['real_open']=df['open']/df['adjust_factor']#获取真实开盘价
            df['turn']=df['turn']/100#获取换手率
            df['avg_price']=np.round(df['real_close']+df['real_open'])/2#计算每日平均成本,这里按照0.5元一个价位做分析
            df=df.sort_values(by='date',ascending=False).reset_index(drop=True)#日期按降序排列
            df['turn_tomo']=df['turn'].shift(1)#计算明日的换手率
            df['remain_day']=1-df['turn_tomo'] #计算当日的剩余筹码比例
            #假设N日后,上市第一天的剩余筹码比率就是每日剩余比例的累乘即:剩余筹码比例=(1-明天换手率)*(1-后日换手率)*...*(1-最新日换手率),以此类推各日的剩余筹码
            df['remain_his']=df['remain_day'].cumprod()
            df['remain_his']=df['remain_his']*df['turn']
            df['remain_his']=df['remain_his'].fillna(df['turn'])#最新一日的筹码就是当日的换手率
            #关键统计,统计最后一天的各价位历史筹码堆积量(百分比)
            ss=df.groupby('avg_price')[['remain_his']].sum().rename(columns={'remain_his':'筹码量'}).reset_index()
            ss['real_close']=df['real_close'].iloc[0]
            #计算end_date时收盘价的获利比例
            winner_day=ss[ss.avg_price<=ss.real_close]['筹码量'].sum()
            winner.append(winner_day)
        result=pd.DataFrame({'winner':winner},index=df_all.date)
        return result
    

    A股股票过滤总是出错啊


    (iQuant) #4


    (iQuant) #5

    可以先参考上方模板修改


    (189) #6

    不理解这个过滤的模块为什么要放在基础特征下面??为什么不直接放在证券代码列表下面?这样过滤效率不是更高吗??


    (iQuant) #7

    因为成份股是按半年调整的,股票池不确定的,只能跟着日期来做DataFrame筛选


    (YYIFAN) #8

    这种说明应该放到模块文档里啊


    (YYIFAN) #9

    我在“过滤退市股票”里选“退市”,竟然输出的全是退市股票,全部和退市还能同时选,逻辑也太奇怪了,这块能仔细讲讲吗?


    (iQuant) #10

    您好,可以参考一下这篇帖子,平台学院板块有系列教程帖,可以多多参考:【宽客学院】条件过滤


    (inSightX) #11

    要选择正常。这里的文字确实有点模棱两可。


    (inSightX) #12

    我也是的,刚开始用直接放在获取数据模块下面了,查了文档才知道该放哪里