用几个ETF做股票池,自动标注V2版本出错,提示参数输入不够数??

新手专区
标签: #<Tag:0x00007f4cd3811a88>

(189) #1
克隆策略
In [46]:
m9.data.read().tail()
Out[46]:
date instrument open close high low avg_close ret_c ratio_c rank(ret_c) m:open m:close m:high m:low label
2030 2014-12-22 510050.HOF 2.370 2.405 2.457 2.355 2.260846 0.226 1.063761 0.8 2.370 2.405 2.457 2.355 13
2031 2014-12-22 159905.ZOF 1.040 1.034 1.053 1.022 1.020538 0.059 1.013191 0.6 1.040 1.034 1.053 1.022 12
2032 2014-12-23 510300.HOF 3.385 3.341 3.454 3.331 3.293538 0.180 1.014411 1.0 3.385 3.341 3.454 3.331 14
2033 2014-12-23 510050.HOF 2.378 2.353 2.440 2.330 2.274231 0.157 1.034636 0.8 2.378 2.353 2.440 2.330 15
2034 2014-12-23 159905.ZOF 1.023 1.030 1.055 1.023 1.024769 0.067 1.005104 0.6 1.023 1.030 1.055 1.023 13

    {"Description":"实验创建于2019/11/2","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-295:instruments","SourceOutputPortId":"-286:data"},{"DestinationInputPortId":"-306:input_data","SourceOutputPortId":"-295:data"},{"DestinationInputPortId":"-8173:input_data","SourceOutputPortId":"-295:data"},{"DestinationInputPortId":"-295:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-306:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-2420:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-1625:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-9439:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-73:input_ds","SourceOutputPortId":"-306:data"},{"DestinationInputPortId":"-169:input_data","SourceOutputPortId":"-73:sorted_data"},{"DestinationInputPortId":"-1260:data2","SourceOutputPortId":"-169:data"},{"DestinationInputPortId":"-2420:training_ds","SourceOutputPortId":"-1260:data"},{"DestinationInputPortId":"-2864:instruments","SourceOutputPortId":"-1609:data"},{"DestinationInputPortId":"-9439:instruments","SourceOutputPortId":"-1609:data"},{"DestinationInputPortId":"-2642:data","SourceOutputPortId":"-1625:data"},{"DestinationInputPortId":"-2642:model","SourceOutputPortId":"-2420:model"},{"DestinationInputPortId":"-2864:options_data","SourceOutputPortId":"-2642:predictions"},{"DestinationInputPortId":"-1260:data1","SourceOutputPortId":"-8173:data"},{"DestinationInputPortId":"-1625:input_data","SourceOutputPortId":"-9439:data"}],"ModuleNodes":[{"Id":"-286","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"510300.HOF\n510050.HOF\n510500.HOF\n159915.ZOF\n159949.ZOF\n159905.ZOF\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-286"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-286","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-295","ModuleId":"BigQuantSpace.use_datasource.use_datasource-v1","ModuleParameters":[{"Name":"datasource_id","Value":"bar1d_CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-295"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-295"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-295","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-301","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nopen\nhigh\nlow \nclose\navg_close=mean(close,13)\nret_c=close-shift(close, 12)\nratio_c=close/avg_close\nrank(ret_c)","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-301"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-301","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-306","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":"-306"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-306"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-306","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-73","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"ret_c","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-73"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-73"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-73","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-169","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"ret_c>0","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":"-169"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-169","OutputType":null},{"Name":"left_data","NodeId":"-169","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1260","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":"-1260"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-1260"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1260","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1609","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-11-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"510300.HOF\n510050.HOF\n510500.HOF\n159915.ZOF\n159949.ZOF\n159905.ZOF\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-1609"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1609","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1625","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":"-1625"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1625"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1625","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2420","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":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-2420"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-2420","OutputType":null},{"Name":"feature_gains","NodeId":"-2420","OutputType":null},{"Name":"m_lazy_run","NodeId":"-2420","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2642","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":"-2642"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"-2642"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"-2642","OutputType":null},{"Name":"m_lazy_run","NodeId":"-2642","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-2864","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = 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\n","ValueType":"Literal","LinkedGlobalParameter":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 = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按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 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":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"真实价格","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"product_type","Value":"股票","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-2864"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-2864","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":16,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-8173","ModuleId":"BigQuantSpace.auto_labeler_on_datasource.auto_labeler_on_datasource-v1","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","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":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-8173"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8173","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-9439","ModuleId":"BigQuantSpace.use_datasource.use_datasource-v1","ModuleParameters":[{"Name":"datasource_id","Value":"bar1d_CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-9439"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-9439"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-9439","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='-286' Position='187,-38,200,200'/><NodePosition Node='-295' Position='272,58,200,200'/><NodePosition Node='-301' Position='669,-90,200,200'/><NodePosition Node='-306' Position='458,152,200,200'/><NodePosition Node='-73' Position='495,242,200,200'/><NodePosition Node='-169' Position='493,323,200,200'/><NodePosition Node='-1260' Position='148,454,200,200'/><NodePosition Node='-1609' Position='1165,-53,200,200'/><NodePosition Node='-1625' Position='1097.8006591796875,411.1267395019531,200,200'/><NodePosition Node='-2420' Position='331,571,200,200'/><NodePosition Node='-2642' Position='377,698,200,200'/><NodePosition Node='-2864' Position='557,793,200,200'/><NodePosition Node='-8173' Position='-129,208,200,200'/><NodePosition Node='-9439' Position='1221,268,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 [43]:
    # 本代码由可视化策略环境自动生成 2019年11月4日 01:13
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m16_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 m16_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 = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
    
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
        if not is_staging and cash_for_sell > 0:
            equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
            instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                    lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
            # print('rank order for sell %s' % instruments)
            for instrument in instruments:
                context.order_target(context.symbol(instrument), 0)
                cash_for_sell -= positions[instrument]
                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.get(instrument, 0):
                # 确保股票持仓量不会超过每次股票最大的占用资金量
                cash = max_cash_per_instrument - positions.get(instrument, 0)
            if cash > 0:
                context.order_value(context.symbol(instrument), cash)
    
    # 回测引擎:准备数据,只执行一次
    def m16_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m16_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m1 = M.instruments.v2(
        start_date='2010-01-01',
        end_date='2015-01-01',
        market='CN_FUND',
        instrument_list="""510300.HOF
    510050.HOF
    510500.HOF
    159915.ZOF
    159949.ZOF
    159905.ZOF
    """,
        max_count=0
    )
    
    m3 = M.input_features.v1(
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    open
    high
    low 
    close
    avg_close=mean(close,13)
    ret_c=close-shift(close, 12)
    ratio_c=close/avg_close
    rank(ret_c)"""
    )
    
    m2 = M.use_datasource.v1(
        instruments=m1.data,
        features=m3.data,
        datasource_id='bar1d_CN_FUND',
        start_date='',
        end_date=''
    )
    
    m8 = M.auto_labeler_on_datasource.v1(
        input_data=m2.data,
        label_expr="""# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
    
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    shift(close, -5) / shift(open, -1)
    
    # 极值处理:用1%和99%分位的值做clip
    clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
    
    # 将分数映射到分类,这里使用20个分类
    all_wbins(label, 20)
    
    # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
    where(shift(high, -1) == shift(low, -1), NaN, label)
    """,
        drop_na_label=True,
        cast_label_int=True,
        date_col='date',
        instrument_col='instrument',
        user_functions={}
    )
    
    m4 = M.derived_feature_extractor.v3(
        input_data=m2.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m5 = M.sort.v4(
        input_ds=m4.data,
        sort_by='ret_c',
        group_by='date',
        keep_columns='--',
        ascending=False
    )
    
    m6 = M.filter.v3(
        input_data=m5.sorted_data,
        expr='ret_c>0',
        output_left_data=False
    )
    
    m9 = M.join.v3(
        data1=m8.data,
        data2=m6.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m14 = M.stock_ranker_train.v5(
        training_ds=m9.data,
        features=m3.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
    )
    
    m10 = M.instruments.v2(
        start_date='2015-01-01',
        end_date='2019-11-01',
        market='CN_FUND',
        instrument_list="""510300.HOF
    510050.HOF
    510500.HOF
    159915.ZOF
    159949.ZOF
    159905.ZOF
    """,
        max_count=0
    )
    
    m17 = M.use_datasource.v1(
        instruments=m10.data,
        features=m3.data,
        datasource_id='bar1d_CN_FUND',
        start_date='',
        end_date=''
    )
    
    m12 = M.derived_feature_extractor.v3(
        input_data=m17.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m15 = M.stock_ranker_predict.v5(
        model=m14.model,
        data=m12.data,
        m_lazy_run=False
    )
    
    m16 = M.trade.v4(
        instruments=m10.data,
        options_data=m15.predictions,
        start_date='',
        end_date='',
        initialize=m16_initialize_bigquant_run,
        handle_data=m16_handle_data_bigquant_run,
        prepare=m16_prepare_bigquant_run,
        before_trading_start=m16_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=''
    )
    
    设置测试数据集,查看训练迭代过程的NDCG
    bigcharts-data-start/{"__id":"bigchart-3eaa2e56995d41b2874676527516ad65","__type":"tabs"}/bigcharts-data-end

    自动标注(股票)(advanced_auto_labeler)使用错误,你可以:

    1.一键查看文档

    2.一键搜索答案

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-43-0dbacbd1d7af> in <module>()
        199     drop_na_label=True,
        200     cast_label_int=True,
    --> 201     user_functions={}
        202 )
        203 
    
    TypeError: __init__() takes at least 3 positional arguments (1 given)

    (iQuant) #2

    收到您的提问,已提交至策略工程师,会尽快为您回复。


    (达达) #3

    需要自己传入回测行情数据,必须包含高开低收和成交量,因此增加了一个特征列表模块区分训练因子和辅助数据因子

    克隆策略

      {"Description":"实验创建于2019/11/2","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-295:instruments","SourceOutputPortId":"-286:data"},{"DestinationInputPortId":"-306:input_data","SourceOutputPortId":"-295:data"},{"DestinationInputPortId":"-8173:input_data","SourceOutputPortId":"-295:data"},{"DestinationInputPortId":"-295:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-306:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-1625:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-123:input_1","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-126:features_ds","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-73:input_ds","SourceOutputPortId":"-306:data"},{"DestinationInputPortId":"-169:input_data","SourceOutputPortId":"-73:sorted_data"},{"DestinationInputPortId":"-1260:data2","SourceOutputPortId":"-169:data"},{"DestinationInputPortId":"-120:input_data","SourceOutputPortId":"-1260:data"},{"DestinationInputPortId":"-2864:instruments","SourceOutputPortId":"-1609:data"},{"DestinationInputPortId":"-9439:instruments","SourceOutputPortId":"-1609:data"},{"DestinationInputPortId":"-2642:data","SourceOutputPortId":"-1625:data"},{"DestinationInputPortId":"-2642:model","SourceOutputPortId":"-2420:model"},{"DestinationInputPortId":"-2864:options_data","SourceOutputPortId":"-2642:predictions"},{"DestinationInputPortId":"-1260:data1","SourceOutputPortId":"-8173:data"},{"DestinationInputPortId":"-1625:input_data","SourceOutputPortId":"-9439:data"},{"DestinationInputPortId":"-2864:history_ds","SourceOutputPortId":"-9439:data"},{"DestinationInputPortId":"-2420:training_ds","SourceOutputPortId":"-120:data"},{"DestinationInputPortId":"-2420:features","SourceOutputPortId":"-123:data_1"},{"DestinationInputPortId":"-9439:features","SourceOutputPortId":"-126:data"}],"ModuleNodes":[{"Id":"-286","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"510300.HOF\n510050.HOF\n510500.HOF\n159915.ZOF\n159949.ZOF\n159905.ZOF\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-286"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-286","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"-295","ModuleId":"BigQuantSpace.use_datasource.use_datasource-v1","ModuleParameters":[{"Name":"datasource_id","Value":"bar1d_CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-295"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-295"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-295","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"Comment":"","CommentCollapsed":true},{"Id":"-301","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nopen\nhigh\nlow \nclose\navg_close=mean(close,13)\nret_c=close-shift(close, 12)\nratio_c=close/avg_close\nrank(ret_c)","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-301"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-301","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"Comment":"","CommentCollapsed":true},{"Id":"-306","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":"-306"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-306"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-306","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"Comment":"","CommentCollapsed":true},{"Id":"-73","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"ret_c","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-73"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-73"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-73","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"Comment":"","CommentCollapsed":true},{"Id":"-169","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"ret_c>0","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":"-169"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-169","OutputType":null},{"Name":"left_data","NodeId":"-169","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"Comment":"","CommentCollapsed":true},{"Id":"-1260","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":"-1260"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-1260"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1260","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"Comment":"","CommentCollapsed":true},{"Id":"-1609","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-11-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"510300.HOF\n510050.HOF\n510500.HOF\n159915.ZOF\n159949.ZOF\n159905.ZOF\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-1609"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1609","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"Comment":"","CommentCollapsed":true},{"Id":"-1625","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":"-1625"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1625"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1625","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"Comment":"","CommentCollapsed":true},{"Id":"-2420","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":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-2420"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-2420","OutputType":null},{"Name":"feature_gains","NodeId":"-2420","OutputType":null},{"Name":"m_lazy_run","NodeId":"-2420","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"Comment":"","CommentCollapsed":true},{"Id":"-2642","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":"-2642"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"-2642"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"-2642","OutputType":null},{"Name":"m_lazy_run","NodeId":"-2642","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"Comment":"","CommentCollapsed":true},{"Id":"-2864","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = 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\n","ValueType":"Literal","LinkedGlobalParameter":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 = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按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 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":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"真实价格","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"product_type","Value":"股票","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-2864"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-2864","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":16,"Comment":"","CommentCollapsed":true},{"Id":"-8173","ModuleId":"BigQuantSpace.auto_labeler_on_datasource.auto_labeler_on_datasource-v1","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","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":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-8173"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8173","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"Comment":"","CommentCollapsed":true},{"Id":"-9439","ModuleId":"BigQuantSpace.use_datasource.use_datasource-v1","ModuleParameters":[{"Name":"datasource_id","Value":"bar1d_CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-9439"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-9439"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-9439","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"Comment":"","CommentCollapsed":true},{"Id":"-120","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-120"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-120","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"Comment":"","CommentCollapsed":true},{"Id":"-123","ModuleId":"BigQuantSpace.features_short.features_short-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-123"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-123","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":11,"Comment":"","CommentCollapsed":true},{"Id":"-126","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nvolume","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-126"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-126","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"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='-286' Position='187,-38,200,200'/><NodePosition Node='-295' Position='272,58,200,200'/><NodePosition Node='-301' Position='669,-90,200,200'/><NodePosition Node='-306' Position='458,152,200,200'/><NodePosition Node='-73' Position='495,242,200,200'/><NodePosition Node='-169' Position='493,323,200,200'/><NodePosition Node='-1260' Position='161.04000854492188,407.0559997558594,200,200'/><NodePosition Node='-1609' Position='1183.908203125,152.626558303833,200,200'/><NodePosition Node='-1625' Position='1097,411,200,200'/><NodePosition Node='-2420' Position='458.7919921875,589.2559814453125,200,200'/><NodePosition Node='-2642' Position='716.0399780273438,703.2160034179688,200,200'/><NodePosition Node='-2864' Position='846.4879760742188,793,200,200'/><NodePosition Node='-8173' Position='50.951995849609375,252.33599853515625,200,200'/><NodePosition Node='-9439' Position='1218.636474609375,268,200,200'/><NodePosition Node='-120' Position='276.1433410644531,498.3426208496094,200,200'/><NodePosition Node='-123' Position='584.3428955078125,431.5242919921875,200,200'/><NodePosition Node='-126' Position='729.72705078125,121.7183609008789,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 [27]:
      # 本代码由可视化策略环境自动生成 2019年11月4日 14:36
      # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
      
      
      # 回测引擎:初始化函数,只执行一次
      def m16_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 m16_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 = {e.symbol: p.amount * p.last_sale_price
                       for e, p in context.perf_tracker.position_tracker.positions.items()}
      
          # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
          if not is_staging and cash_for_sell > 0:
              equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
              instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                      lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
              # print('rank order for sell %s' % instruments)
              for instrument in instruments:
                  context.order_target(context.symbol(instrument), 0)
                  cash_for_sell -= positions[instrument]
                  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.get(instrument, 0):
                  # 确保股票持仓量不会超过每次股票最大的占用资金量
                  cash = max_cash_per_instrument - positions.get(instrument, 0)
              if cash > 0:
                  context.order_value(context.symbol(instrument), cash)
      
      # 回测引擎:准备数据,只执行一次
      def m16_prepare_bigquant_run(context):
          pass
      
      # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
      def m16_before_trading_start_bigquant_run(context, data):
          pass
      
      
      m1 = M.instruments.v2(
          start_date='2010-01-01',
          end_date='2015-01-01',
          market='CN_FUND',
          instrument_list="""510300.HOF
      510050.HOF
      510500.HOF
      159915.ZOF
      159949.ZOF
      159905.ZOF
      """,
          max_count=0
      )
      
      m3 = M.input_features.v1(
          features="""
      # #号开始的表示注释,注释需单独一行
      # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
      open
      high
      low 
      close
      avg_close=mean(close,13)
      ret_c=close-shift(close, 12)
      ratio_c=close/avg_close
      rank(ret_c)"""
      )
      
      m2 = M.use_datasource.v1(
          instruments=m1.data,
          features=m3.data,
          datasource_id='bar1d_CN_FUND',
          start_date='',
          end_date=''
      )
      
      m8 = M.auto_labeler_on_datasource.v1(
          input_data=m2.data,
          label_expr="""# #号开始的表示注释
      # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
      # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
      # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
      
      # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
      shift(close, -5) / shift(open, -1)
      
      # 极值处理:用1%和99%分位的值做clip
      clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
      
      # 将分数映射到分类,这里使用20个分类
      all_wbins(label, 20)
      
      # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
      where(shift(high, -1) == shift(low, -1), NaN, label)
      """,
          drop_na_label=True,
          cast_label_int=True,
          date_col='date',
          instrument_col='instrument',
          user_functions={}
      )
      
      m4 = M.derived_feature_extractor.v3(
          input_data=m2.data,
          features=m3.data,
          date_col='date',
          instrument_col='instrument',
          drop_na=False,
          remove_extra_columns=False,
          user_functions={}
      )
      
      m5 = M.sort.v4(
          input_ds=m4.data,
          sort_by='ret_c',
          group_by='date',
          keep_columns='--',
          ascending=False
      )
      
      m6 = M.filter.v3(
          input_data=m5.sorted_data,
          expr='ret_c>0',
          output_left_data=False
      )
      
      m9 = M.join.v3(
          data1=m8.data,
          data2=m6.data,
          on='date,instrument',
          how='inner',
          sort=False
      )
      
      m7 = M.dropnan.v1(
          input_data=m9.data
      )
      
      m11 = M.features_short.v1(
          input_1=m3.data
      )
      
      m14 = M.stock_ranker_train.v5(
          training_ds=m7.data,
          features=m11.data_1,
          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
      )
      
      m13 = M.input_features.v1(
          features_ds=m3.data,
          features="""
      # #号开始的表示注释,注释需单独一行
      # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
      volume"""
      )
      
      m10 = M.instruments.v2(
          start_date='2015-01-01',
          end_date='2019-11-01',
          market='CN_FUND',
          instrument_list="""510300.HOF
      510050.HOF
      510500.HOF
      159915.ZOF
      159949.ZOF
      159905.ZOF
      """,
          max_count=0
      )
      
      m17 = M.use_datasource.v1(
          instruments=m10.data,
          features=m13.data,
          datasource_id='bar1d_CN_FUND',
          start_date='',
          end_date=''
      )
      
      m12 = M.derived_feature_extractor.v3(
          input_data=m17.data,
          features=m3.data,
          date_col='date',
          instrument_col='instrument',
          drop_na=False,
          remove_extra_columns=False,
          user_functions={}
      )
      
      m15 = M.stock_ranker_predict.v5(
          model=m14.model,
          data=m12.data,
          m_lazy_run=False
      )
      
      m16 = M.trade.v4(
          instruments=m10.data,
          options_data=m15.predictions,
          history_ds=m17.data,
          start_date='',
          end_date='',
          initialize=m16_initialize_bigquant_run,
          handle_data=m16_handle_data_bigquant_run,
          prepare=m16_prepare_bigquant_run,
          before_trading_start=m16_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=''
      )
      
      设置测试数据集,查看训练迭代过程的NDCG
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-5e83073506ab4eb69405b208dc179f7f"}/bigcharts-data-end
      • 收益率51.18%
      • 年化收益率9.25%
      • 基准收益率11.85%
      • 阿尔法0.08
      • 贝塔0.73
      • 夏普比率0.33
      • 胜率0.53
      • 盈亏比1.11
      • 收益波动率30.62%
      • 信息比率0.02
      • 最大回撤45.89%
      bigcharts-data-start/{"__type":"tabs","__id":"bigchart-f0cbceae4b2147389be52ce83f2dca61"}/bigcharts-data-end

      (189) #4

      多谢!1/我照着你给的答案做了微小改动,本以为出来的结果是一样的,却发现差异很大!2/我修改后的曲线,跟你给出的回测曲线,都有一个异常,我查了是2015年4月15日这天突然净值增加了25%左右,显然是数据问题,请你们检查一下!

      克隆策略
      In [49]:
      m9.data.read().tail()
      
      Out[49]:
      date instrument open close high low avg_close ret_c ratio_c rank(ret_c) m:open m:close m:high m:low label
      2030 2014-12-22 510050.HOF 2.370 2.405 2.457 2.355 2.260846 0.226 1.063761 0.8 2.370 2.405 2.457 2.355 13
      2031 2014-12-22 159905.ZOF 1.040 1.034 1.053 1.022 1.020538 0.059 1.013191 0.6 1.040 1.034 1.053 1.022 12
      2032 2014-12-23 510300.HOF 3.385 3.341 3.454 3.331 3.293538 0.180 1.014411 1.0 3.385 3.341 3.454 3.331 14
      2033 2014-12-23 510050.HOF 2.378 2.353 2.440 2.330 2.274231 0.157 1.034636 0.8 2.378 2.353 2.440 2.330 15
      2034 2014-12-23 159905.ZOF 1.023 1.030 1.055 1.023 1.024769 0.067 1.005104 0.6 1.023 1.030 1.055 1.023 13

        {"Description":"实验创建于2019/11/2","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-295:instruments","SourceOutputPortId":"-286:data"},{"DestinationInputPortId":"-306:input_data","SourceOutputPortId":"-295:data"},{"DestinationInputPortId":"-8173:input_data","SourceOutputPortId":"-295:data"},{"DestinationInputPortId":"-295:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-306:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-1625:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-9439:features","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-121:input_1","SourceOutputPortId":"-301:data"},{"DestinationInputPortId":"-73:input_ds","SourceOutputPortId":"-306:data"},{"DestinationInputPortId":"-169:input_data","SourceOutputPortId":"-73:sorted_data"},{"DestinationInputPortId":"-1260:data2","SourceOutputPortId":"-169:data"},{"DestinationInputPortId":"-2420:training_ds","SourceOutputPortId":"-1260:data"},{"DestinationInputPortId":"-2864:instruments","SourceOutputPortId":"-1609:data"},{"DestinationInputPortId":"-9439:instruments","SourceOutputPortId":"-1609:data"},{"DestinationInputPortId":"-2642:data","SourceOutputPortId":"-1625:data"},{"DestinationInputPortId":"-2642:model","SourceOutputPortId":"-2420:model"},{"DestinationInputPortId":"-2864:options_data","SourceOutputPortId":"-2642:predictions"},{"DestinationInputPortId":"-1260:data1","SourceOutputPortId":"-8173:data"},{"DestinationInputPortId":"-1625:input_data","SourceOutputPortId":"-9439:data"},{"DestinationInputPortId":"-2864:history_ds","SourceOutputPortId":"-9439:data"},{"DestinationInputPortId":"-2420:features","SourceOutputPortId":"-121:data_1"}],"ModuleNodes":[{"Id":"-286","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"510300.HOF\n510050.HOF\n510500.HOF\n159915.ZOF\n159949.ZOF\n159905.ZOF\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-286"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-286","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"-295","ModuleId":"BigQuantSpace.use_datasource.use_datasource-v1","ModuleParameters":[{"Name":"datasource_id","Value":"bar1d_CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-295"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-295"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-295","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"Comment":"","CommentCollapsed":true},{"Id":"-301","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nopen\nhigh\nlow \nclose\nvolume\navg_close=mean(close,13)\nret_c=close-shift(close, 12)\nratio_c=close/mean(close,13)\nrank(close-shift(close, 12))","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-301"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-301","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":3,"Comment":"","CommentCollapsed":true},{"Id":"-306","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":"-306"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-306"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-306","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"Comment":"","CommentCollapsed":true},{"Id":"-73","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"ret_c","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-73"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-73"}],"OutputPortsInternal":[{"Name":"sorted_data","NodeId":"-73","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"Comment":"","CommentCollapsed":true},{"Id":"-169","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"ret_c>0","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":"-169"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-169","OutputType":null},{"Name":"left_data","NodeId":"-169","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"Comment":"","CommentCollapsed":true},{"Id":"-1260","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":"-1260"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-1260"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1260","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"Comment":"","CommentCollapsed":true},{"Id":"-1609","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2019-11-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"510300.HOF\n510050.HOF\n510500.HOF\n159915.ZOF\n159949.ZOF\n159905.ZOF\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-1609"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1609","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"Comment":"","CommentCollapsed":true},{"Id":"-1625","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":"-1625"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1625"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1625","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"Comment":"","CommentCollapsed":true},{"Id":"-2420","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":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-2420"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-2420"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-2420","OutputType":null},{"Name":"feature_gains","NodeId":"-2420","OutputType":null},{"Name":"m_lazy_run","NodeId":"-2420","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"Comment":"","CommentCollapsed":true},{"Id":"-2642","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":"-2642"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"-2642"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"-2642","OutputType":null},{"Name":"m_lazy_run","NodeId":"-2642","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"Comment":"","CommentCollapsed":true},{"Id":"-2864","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = 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\n","ValueType":"Literal","LinkedGlobalParameter":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 = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按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 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":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"close","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"真实价格","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"product_type","Value":"股票","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-2864"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-2864"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-2864","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":16,"Comment":"","CommentCollapsed":true},{"Id":"-8173","ModuleId":"BigQuantSpace.auto_labeler_on_datasource.auto_labeler_on_datasource-v1","ModuleParameters":[{"Name":"label_expr","Value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -5) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","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":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-8173"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-8173","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"Comment":"","CommentCollapsed":true},{"Id":"-9439","ModuleId":"BigQuantSpace.use_datasource.use_datasource-v1","ModuleParameters":[{"Name":"datasource_id","Value":"bar1d_CN_FUND","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-9439"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-9439"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-9439","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"Comment":"","CommentCollapsed":true},{"Id":"-121","ModuleId":"BigQuantSpace.features_short.features_short-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-121"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-121","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"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='-286' Position='187,-38,200,200'/><NodePosition Node='-295' Position='272,58,200,200'/><NodePosition Node='-301' Position='669,-90,200,200'/><NodePosition Node='-306' Position='458,152,200,200'/><NodePosition Node='-73' Position='379,249,200,200'/><NodePosition Node='-169' Position='425,330,200,200'/><NodePosition Node='-1260' Position='148,454,200,200'/><NodePosition Node='-1609' Position='1165,-53,200,200'/><NodePosition Node='-1625' Position='1097,411,200,200'/><NodePosition Node='-2420' Position='331,571,200,200'/><NodePosition Node='-2642' Position='377,698,200,200'/><NodePosition Node='-2864' Position='557,793,200,200'/><NodePosition Node='-8173' Position='-7.063163757324219,221.7178955078125,200,200'/><NodePosition Node='-9439' Position='1271.2989501953125,229.89468383789062,200,200'/><NodePosition Node='-121' Position='600.5625610351562,440.8092346191406,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 [8]:
        # 本代码由可视化策略环境自动生成 2019年11月4日 15:25
        # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
        
        
        # 回测引擎:初始化函数,只执行一次
        def m16_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 m16_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 = {e.symbol: p.amount * p.last_sale_price
                         for e, p in context.perf_tracker.position_tracker.positions.items()}
        
            # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
            if not is_staging and cash_for_sell > 0:
                equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}
                instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(
                        lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))
                # print('rank order for sell %s' % instruments)
                for instrument in instruments:
                    context.order_target(context.symbol(instrument), 0)
                    cash_for_sell -= positions[instrument]
                    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.get(instrument, 0):
                    # 确保股票持仓量不会超过每次股票最大的占用资金量
                    cash = max_cash_per_instrument - positions.get(instrument, 0)
                if cash > 0:
                    context.order_value(context.symbol(instrument), cash)
        
        # 回测引擎:准备数据,只执行一次
        def m16_prepare_bigquant_run(context):
            pass
        
        # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
        def m16_before_trading_start_bigquant_run(context, data):
            pass
        
        
        m1 = M.instruments.v2(
            start_date='2010-01-01',
            end_date='2015-01-01',
            market='CN_FUND',
            instrument_list="""510300.HOF
        510050.HOF
        510500.HOF
        159915.ZOF
        159949.ZOF
        159905.ZOF
        """,
            max_count=0
        )
        
        m3 = M.input_features.v1(
            features="""
        # #号开始的表示注释,注释需单独一行
        # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
        open
        high
        low 
        close
        volume
        avg_close=mean(close,13)
        ret_c=close-shift(close, 12)
        ratio_c=close/mean(close,13)
        rank(close-shift(close, 12))"""
        )
        
        m2 = M.use_datasource.v1(
            instruments=m1.data,
            features=m3.data,
            datasource_id='bar1d_CN_FUND',
            start_date='',
            end_date=''
        )
        
        m8 = M.auto_labeler_on_datasource.v1(
            input_data=m2.data,
            label_expr="""# #号开始的表示注释
        # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
        # 1. 可用数据字段见 https://bigquant.com/docs/develop/datasource/deprecated/history_data.html
        # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/develop/bigexpr/usage.html>`_
        
        # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
        shift(close, -5) / shift(open, -1)
        
        # 极值处理:用1%和99%分位的值做clip
        clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
        
        # 将分数映射到分类,这里使用20个分类
        all_wbins(label, 20)
        
        # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
        where(shift(high, -1) == shift(low, -1), NaN, label)
        """,
            drop_na_label=True,
            cast_label_int=True,
            date_col='date',
            instrument_col='instrument',
            user_functions={}
        )
        
        m4 = M.derived_feature_extractor.v3(
            input_data=m2.data,
            features=m3.data,
            date_col='date',
            instrument_col='instrument',
            drop_na=False,
            remove_extra_columns=False,
            user_functions={}
        )
        
        m5 = M.sort.v4(
            input_ds=m4.data,
            sort_by='ret_c',
            group_by='date',
            keep_columns='--',
            ascending=False
        )
        
        m6 = M.filter.v3(
            input_data=m5.sorted_data,
            expr='ret_c>0',
            output_left_data=False
        )
        
        m9 = M.join.v3(
            data1=m8.data,
            data2=m6.data,
            on='date,instrument',
            how='inner',
            sort=False
        )
        
        m7 = M.features_short.v1(
            input_1=m3.data
        )
        
        m14 = M.stock_ranker_train.v5(
            training_ds=m9.data,
            features=m7.data_1,
            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
        )
        
        m10 = M.instruments.v2(
            start_date='2015-01-01',
            end_date='2019-11-01',
            market='CN_FUND',
            instrument_list="""510300.HOF
        510050.HOF
        510500.HOF
        159915.ZOF
        159949.ZOF
        159905.ZOF
        """,
            max_count=0
        )
        
        m17 = M.use_datasource.v1(
            instruments=m10.data,
            features=m3.data,
            datasource_id='bar1d_CN_FUND',
            start_date='',
            end_date=''
        )
        
        m12 = M.derived_feature_extractor.v3(
            input_data=m17.data,
            features=m3.data,
            date_col='date',
            instrument_col='instrument',
            drop_na=False,
            remove_extra_columns=False,
            user_functions={}
        )
        
        m15 = M.stock_ranker_predict.v5(
            model=m14.model,
            data=m12.data,
            m_lazy_run=False
        )
        
        m16 = M.trade.v4(
            instruments=m10.data,
            options_data=m15.predictions,
            history_ds=m17.data,
            start_date='',
            end_date='',
            initialize=m16_initialize_bigquant_run,
            handle_data=m16_handle_data_bigquant_run,
            prepare=m16_prepare_bigquant_run,
            before_trading_start=m16_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=''
        )
        
        设置测试数据集,查看训练迭代过程的NDCG
        bigcharts-data-start/{"__id":"bigchart-94fd58968c064cdbaad9a09c437825b7","__type":"tabs"}/bigcharts-data-end
        • 收益率27.1%
        • 年化收益率5.27%
        • 基准收益率11.85%
        • 阿尔法0.03
        • 贝塔0.73
        • 夏普比率0.21
        • 胜率0.54
        • 盈亏比1.17
        • 收益波动率22.15%
        • 信息比率0.01
        • 最大回撤40.73%
        bigcharts-data-start/{"__id":"bigchart-df483e1ec53247cd8c067e98ee0d4e40","__type":"tabs"}/bigcharts-data-end

        (达达) #5

        好的 感谢反馈 我们修复一下