特征抽取报错,麻烦看看!

用户成长系列
自定义特征
标签: #<Tag:0x00007f8c60b6d868> #<Tag:0x00007f8c60b6d700>

(hugo) #1
克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-223:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-110:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-110:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-117:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-131:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"-117:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-143:data1","SourceOutputPortId":"-223:data"},{"DestinationInputPortId":"-131:training_ds","SourceOutputPortId":"-99:data"},{"DestinationInputPortId":"-143:data2","SourceOutputPortId":"-110:data"},{"DestinationInputPortId":"-123:input_data","SourceOutputPortId":"-117:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-123:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"-131:feature_gains"},{"DestinationInputPortId":"-99:input_data","SourceOutputPortId":"-143:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2009-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-12-31","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nlog(where(daily_return_0>mean(daily_return_0,60),(daily_return_0-mean(daily_return_0,60))*2)/where(daily_return_0<mean(daily_return_0,60),(daily_return_0-mean(daily_return_0,60))*2))\n\n\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"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":6,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-81","ModuleId":"BigQuantSpace.trade.trade-v3","ModuleParameters":[{"Name":"start_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2017-12-31","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.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 # 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 # 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. 生成买入订单:按机器学习算法预测的排序,买入前面的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":"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.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":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"000300.SHA","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":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"amount_integer","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":9,"Comment":"","CommentCollapsed":true},{"Id":"-223","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":"2009-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-12-31","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":"-223"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-223","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"Comment":"","CommentCollapsed":true},{"Id":"-99","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-99"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-99","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"Comment":"","CommentCollapsed":true},{"Id":"-110","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v6","ModuleParameters":[{"Name":"start_date","Value":"2009-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-12-31","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"60","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-110"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-110"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-110","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"Comment":"","CommentCollapsed":true},{"Id":"-117","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v6","ModuleParameters":[{"Name":"start_date","Value":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2017-12-31","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"60","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-117"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-117"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-117","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"Comment":"","CommentCollapsed":true},{"Id":"-123","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-123"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-123","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"Comment":"","CommentCollapsed":true},{"Id":"-131","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":"-131"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-131"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-131"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-131"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-131","OutputType":null},{"Name":"feature_gains","NodeId":"-131","OutputType":null},{"Name":"m_lazy_run","NodeId":"-131","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":19,"Comment":"","CommentCollapsed":true},{"Id":"-143","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":"-143"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-143"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-143","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":20,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='213,57.50578308105469,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='770.4942626953125,21,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='906,645,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1072,129.98841857910156,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-81' Position='1037,751,200,200'/><NodePosition Node='-223' Position='91,203,200,200'/><NodePosition Node='-99' Position='372.28704833984375,463.20098876953125,200,200'/><NodePosition Node='-110' Position='448.4918212890625,217.31997680664062,200,200'/><NodePosition Node='-117' Position='898.25,306.3086242675781,200,200'/><NodePosition Node='-123' Position='907.2152709960938,436.30517578125,200,200'/><NodePosition Node='-131' Position='545.6157836914062,552.853759765625,200,200'/><NodePosition Node='-143' Position='264.7037048339844,352.1311950683594,200,200'/></NodePositions><NodeGroups /></DataV1>"},"IsDraft":true,"ParentExperimentId":null,"WebService":{"IsWebServiceExperiment":false,"Inputs":[],"Outputs":[],"Parameters":[{"Name":"交易日期","Value":"","ParameterDefinition":{"Name":"交易日期","FriendlyName":"交易日期","DefaultValue":"","ParameterType":"String","HasDefaultValue":true,"IsOptional":true,"ParameterRules":[],"HasRules":false,"MarkupType":0,"CredentialDescriptor":null}}],"WebServiceGroupId":null,"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions></NodePositions><NodeGroups /></DataV1>"},"DisableNodesUpdate":false,"Category":"user","Tags":[],"IsPartialRun":true}
    In [1]:
    # 本代码由可视化策略环境自动生成 2018年1月7日 15:07
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date='2009-01-01',
        end_date='2015-12-31',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m12 = M.advanced_auto_labeler.v2(
        instruments=m1.data,
        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)
    """,
        start_date='2009-01-01',
        end_date='2015-12-31',
        benchmark='000300.SHA',
        drop_na_label=True,
        cast_label_int=True,
        user_functions={}
    )
    
    m2 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    log(where(daily_return_0>mean(daily_return_0,60),(daily_return_0-mean(daily_return_0,60))*2)/where(daily_return_0<mean(daily_return_0,60),(daily_return_0-mean(daily_return_0,60))*2))
    
    
    """
    )
    
    m16 = M.general_feature_extractor.v6(
        instruments=m1.data,
        features=m2.data,
        start_date='2009-01-01',
        end_date='2015-12-31',
        before_start_days=60
    )
    
    m20 = M.join.v3(
        data1=m12.data,
        data2=m16.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m14 = M.dropnan.v1(
        input_data=m20.data
    )
    
    m19 = M.stock_ranker_train.v5(
        training_ds=m14.data,
        features=m2.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
    )
    
    m7 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2016-01-01'),
        end_date=T.live_run_param('trading_date', '2017-01-01'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m17 = M.general_feature_extractor.v6(
        instruments=m2.data,
        features=m7.data,
        start_date='2016-01-01',
        end_date='2017-12-31',
        before_start_days=60
    )
    
    m18 = M.dropnan.v1(
        input_data=m17.data
    )
    
    m6 = M.stock_ranker_predict.v5(
        model=m19.feature_gains,
        data=m18.data,
        m_lazy_run=False
    )
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m9_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.options['hold_days'] # 是否在建仓期间(前 hold_days 天)
        cash_avg = context.portfolio.portfolio_value / context.options['hold_days']
        cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)
        cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
        positions = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
    
        # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按机器学习算法预测的排序末位淘汰
        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. 生成买入订单:按机器学习算法预测的排序,买入前面的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 m9_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:初始化函数,只执行一次
    def m9_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.options['hold_days'] = 5
    
    m9 = M.trade.v3(
        instruments=m7.data,
        options_data=m6.predictions,
        start_date='2016-01-01',
        end_date='2017-12-31',
        handle_data=m9_handle_data_bigquant_run,
        prepare=m9_prepare_bigquant_run,
        initialize=m9_initialize_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='close',
        capital_base=1000000,
        benchmark='000300.SHA',
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        plot_charts=True,
        backtest_only=False,
        amount_integer=False
    )
    
    [2018-01-07 14:59:26.882391] INFO: bigquant: instruments.v2 开始运行..
    [2018-01-07 14:59:26.887860] INFO: bigquant: 命中缓存
    [2018-01-07 14:59:26.888796] INFO: bigquant: instruments.v2 运行完成[0.006429s].
    [2018-01-07 14:59:26.949609] INFO: bigquant: advanced_auto_labeler.v2 开始运行..
    [2018-01-07 14:59:26.952921] INFO: bigquant: 命中缓存
    [2018-01-07 14:59:26.953979] INFO: bigquant: advanced_auto_labeler.v2 运行完成[0.004368s].
    [2018-01-07 14:59:26.963724] INFO: bigquant: input_features.v1 开始运行..
    [2018-01-07 14:59:26.966158] INFO: bigquant: 命中缓存
    [2018-01-07 14:59:26.966933] INFO: bigquant: input_features.v1 运行完成[0.003221s].
    [2018-01-07 14:59:26.984571] INFO: bigquant: general_feature_extractor.v6 开始运行..
    [2018-01-07 14:59:26.987988] INFO: bigquant: 命中缓存
    [2018-01-07 14:59:26.989000] INFO: bigquant: general_feature_extractor.v6 运行完成[0.004464s].
    [2018-01-07 14:59:26.999902] INFO: bigquant: join.v3 开始运行..
    [2018-01-07 14:59:38.087751] INFO: join: /y_2008, 行数=0/65022, 耗时=5.820095s
    [2018-01-07 14:59:44.222639] INFO: join: /y_2009, 行数=374465/375308, 耗时=6.131975s
    [2018-01-07 14:59:50.884705] INFO: join: /y_2010, 行数=431030/431567, 耗时=6.646576s
    [2018-01-07 14:59:57.255208] INFO: join: /y_2011, 行数=510922/511455, 耗时=6.356813s
    [2018-01-07 15:00:03.393611] INFO: join: /y_2012, 行数=564582/565675, 耗时=6.119804s
    [2018-01-07 15:00:09.421955] INFO: join: /y_2013, 行数=563137/564168, 耗时=6.004871s
    [2018-01-07 15:00:16.212845] INFO: join: /y_2014, 行数=567866/569948, 耗时=6.767527s
    [2018-01-07 15:00:22.699746] INFO: join: /y_2015, 行数=546721/569698, 耗时=6.463149s
    [2018-01-07 15:00:22.845240] INFO: join: 最终行数: 3558723
    [2018-01-07 15:00:22.847905] INFO: bigquant: join.v3 运行完成[55.847994s].
    [2018-01-07 15:00:22.859626] INFO: bigquant: dropnan.v1 开始运行..
    [2018-01-07 15:00:22.933669] INFO: dropnan: /y_2008, 0/0
    [2018-01-07 15:00:23.349444] INFO: dropnan: /y_2009, 374366/374465
    [2018-01-07 15:00:23.743505] INFO: dropnan: /y_2010, 430684/431030
    [2018-01-07 15:00:24.202002] INFO: dropnan: /y_2011, 510644/510922
    [2018-01-07 15:00:24.729190] INFO: dropnan: /y_2012, 564427/564582
    [2018-01-07 15:00:25.203749] INFO: dropnan: /y_2013, 563135/563137
    [2018-01-07 15:00:25.799043] INFO: dropnan: /y_2014, 567841/567866
    [2018-01-07 15:00:26.307679] INFO: dropnan: /y_2015, 546717/546721
    [2018-01-07 15:00:26.330575] INFO: dropnan: 行数: 3557814/3558723
    [2018-01-07 15:00:26.350253] INFO: bigquant: dropnan.v1 运行完成[3.490618s].
    [2018-01-07 15:00:26.367441] INFO: bigquant: stock_ranker_train.v5 开始运行..
    [2018-01-07 15:00:30.408148] INFO: df2bin: prepare bins ..
    [2018-01-07 15:00:30.411944] INFO: df2bin: prepare data: training ..
    
    ---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    <ipython-input-1-d202a5cd1f1f> in <module>()
         78     max_bins=1023,
         79     feature_fraction=1,
    ---> 80     m_lazy_run=False
         81 )
         82 
    
    KeyError: "[ 'log(where(daily_return_0>mean(daily_return_0,60),(daily_return_0-mean(daily_return_0,60))*2)/where(daily_return_0<mean(daily_return_0,60),(daily_return_0-mean(daily_return_0,60))*2))'] not in index"
    In [3]:
    m20.data.read_df()
    
    Out[3]:
    daily_return_0 date instrument m:close m:high m:low m:open m:amount label
    0 1.026427 2009-01-05 000001.SZA 348.642731 349.719879 341.461609 343.615936 3.275843e+08 8
    1 1.060762 2009-01-06 000001.SZA 369.826965 374.494690 349.360840 351.874207 6.441080e+08 5
    2 0.969903 2009-01-07 000001.SZA 358.696259 373.417542 358.696259 366.236420 6.223286e+08 10
    3 0.960961 2009-01-08 000001.SZA 344.693115 350.437988 341.102539 350.078949 3.792707e+08 12
    4 1.026042 2009-01-09 000001.SZA 353.669495 356.541931 344.693115 344.693115 5.894804e+08 12
    5 1.001015 2009-01-12 000001.SZA 354.028534 361.927765 347.206482 351.156097 4.098644e+08 19
    6 0.960446 2009-01-13 000001.SZA 340.025391 345.770264 318.841125 318.841125 1.592403e+09 19
    7 1.077085 2009-01-14 000001.SZA 366.236420 368.031708 333.921448 333.921448 7.524886e+08 17
    8 1.009804 2009-01-15 000001.SZA 369.826965 380.598633 357.978149 359.414368 9.284989e+08 15
    9 1.031068 2009-01-16 000001.SZA 381.316742 392.806519 371.263214 371.263214 7.106574e+08 13
    10 1.046139 2009-01-19 000001.SZA 398.910461 407.527802 382.393921 382.393921 1.046120e+09 11
    11 1.022502 2009-01-20 000001.SZA 407.886841 409.323059 395.678955 397.474243 5.323789e+08 11
    12 1.037852 2009-01-21 000001.SZA 423.326233 438.047485 394.960846 400.346680 9.651848e+08 13
    13 1.000000 2009-01-22 000001.SZA 423.326233 430.866394 409.323059 423.685272 5.499130e+08 13
    14 0.987277 2009-01-23 000001.SZA 417.940399 428.352997 415.786072 415.786072 4.060894e+08 14
    15 1.001718 2009-02-02 000001.SZA 418.658508 430.507324 413.272675 422.249054 3.864484e+08 17
    16 1.024871 2009-02-03 000001.SZA 429.071106 433.020721 416.504181 418.658508 4.385639e+08 15
    17 1.091213 2009-02-04 000001.SZA 468.208130 472.157745 431.584503 431.584503 6.878691e+08 11
    18 0.981595 2009-02-05 000001.SZA 459.590820 473.953033 453.486877 469.285309 4.833892e+08 10
    19 1.030469 2009-02-06 000001.SZA 473.593964 482.570343 460.308929 460.308929 4.277372e+08 9
    20 1.042456 2009-02-09 000001.SZA 493.701050 504.113678 482.929413 482.929413 6.522564e+08 11
    21 0.993455 2009-02-10 000001.SZA 490.469574 495.496338 473.234924 488.674286 7.195215e+08 11
    22 1.010249 2009-02-11 000001.SZA 495.496338 512.371948 468.926239 484.006561 1.112270e+09 9
    23 0.962319 2009-02-12 000001.SZA 476.825470 498.009735 462.822296 498.009735 7.418348e+08 9
    24 1.024849 2009-02-13 000001.SZA 488.674286 491.905792 466.412872 472.516815 6.894031e+08 8
    25 1.054372 2009-02-16 000001.SZA 515.244385 517.039673 491.187683 491.187683 9.735180e+08 10
    26 1.000697 2009-02-17 000001.SZA 515.603455 541.096375 498.368774 515.244385 1.053926e+09 11
    27 0.974930 2009-02-18 000001.SZA 502.677460 534.633362 491.905792 509.499512 1.383613e+09 7
    28 0.960714 2009-02-19 000001.SZA 482.929413 509.858551 466.771912 502.677460 8.618367e+08 11
    29 1.013383 2009-02-20 000001.SZA 489.392395 491.187683 470.362457 477.543579 5.492701e+08 8
    ... ... ... ... ... ... ... ... ... ...
    546691 0.937871 2015-11-13 603998.SHA 55.666851 58.637836 54.468033 58.637836 1.624694e+08 11
    546692 1.017088 2015-11-16 603998.SHA 56.618088 56.683239 53.946808 54.077114 7.593495e+07 7
    546693 0.987802 2015-11-17 603998.SHA 55.927464 58.702988 55.784126 56.709301 9.280228e+07 11
    546694 0.968779 2015-11-18 603998.SHA 54.181358 56.618088 53.425583 56.135956 8.327421e+07 13
    546695 1.051226 2015-11-19 603998.SHA 56.956882 57.178406 54.337727 54.468033 9.261830e+07 14
    546696 1.008922 2015-11-20 603998.SHA 57.465076 58.559650 56.683239 56.696270 9.134422e+07 14
    546697 0.973923 2015-11-23 603998.SHA 55.966557 57.478107 55.536545 57.334770 8.553845e+07 19
    546698 1.065658 2015-11-24 603998.SHA 59.641193 59.784531 55.640789 56.292320 1.416841e+08 13
    546699 1.002622 2015-11-25 603998.SHA 59.797562 60.592430 58.611774 59.549980 1.311139e+08 9
    546700 1.059272 2015-11-26 603998.SHA 63.341892 65.648315 59.549980 59.797562 2.569261e+08 9
    546701 1.016869 2015-11-27 603998.SHA 64.410400 67.498665 61.374268 62.286411 3.318590e+08 8
    546702 1.099939 2015-11-30 603998.SHA 70.847534 70.847534 62.547024 64.501617 3.476878e+08 3
    546703 0.919441 2015-12-01 603998.SHA 65.140121 74.013977 63.758873 72.971527 3.562847e+08 12
    546704 0.935987 2015-12-02 603998.SHA 60.970318 65.022842 58.624805 63.341892 1.986417e+08 14
    546705 1.038897 2015-12-03 603998.SHA 63.341892 64.267067 61.243961 61.348206 1.311996e+08 13
    546706 1.026538 2015-12-04 603998.SHA 65.022842 67.107742 62.520962 62.547024 1.934543e+08 8
    546707 1.012425 2015-12-07 603998.SHA 65.830742 66.586517 62.977036 64.749199 1.211466e+08 6
    546708 1.035233 2015-12-08 603998.SHA 68.150192 70.313278 63.850086 65.022842 1.587329e+08 4
    546709 1.021415 2015-12-09 603998.SHA 69.609627 71.212395 65.934990 66.951378 1.395939e+08 4
    546710 0.988019 2015-12-10 603998.SHA 68.775665 70.104790 67.941704 69.322952 9.085042e+07 5
    546711 0.947329 2015-12-11 603998.SHA 65.153152 68.814758 65.022842 68.436867 8.788581e+07 7
    546712 0.960000 2015-12-14 603998.SHA 62.547024 64.697075 61.243961 63.876148 1.747690e+08 10
    546713 0.977917 2015-12-15 603998.SHA 61.165779 63.719780 59.953930 62.547024 2.830169e+08 11
    546714 1.031103 2015-12-16 603998.SHA 63.068249 63.172493 60.853043 61.387299 1.625875e+08 9
    546715 1.018595 2015-12-17 603998.SHA 64.241005 64.605865 63.068249 63.159462 1.496237e+08 9
    546716 0.978905 2015-12-18 603998.SHA 62.885818 64.892540 62.547024 64.267067 1.338576e+08 11
    546717 1.034397 2015-12-21 603998.SHA 65.048904 65.544067 63.172493 63.185524 1.323836e+08 9
    546718 1.001202 2015-12-22 603998.SHA 65.127090 65.478912 63.954330 64.553741 1.052966e+08 10
    546719 0.992997 2015-12-23 603998.SHA 64.671013 66.260750 64.371315 65.009811 1.085388e+08 12
    546720 1.002620 2015-12-24 603998.SHA 64.840416 65.283455 62.677330 64.110703 7.974518e+07 9

    3558723 rows × 9 columns


    (iQuant) #2
    克隆策略

      {"Description":"实验创建于2017/9/28","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-311:instruments","SourceOutputPortId":"-303:data"},{"DestinationInputPortId":"-5157:instruments","SourceOutputPortId":"-303:data"},{"DestinationInputPortId":"-63:input_1","SourceOutputPortId":"-311:data"},{"DestinationInputPortId":"-311:features","SourceOutputPortId":"-315:data"},{"DestinationInputPortId":"-5248:features","SourceOutputPortId":"-315:data"},{"DestinationInputPortId":"-5168:data2","SourceOutputPortId":"-63:data_1"},{"DestinationInputPortId":"-5228:features","SourceOutputPortId":"-63:data_2"},{"DestinationInputPortId":"-5168:data1","SourceOutputPortId":"-5157:data"},{"DestinationInputPortId":"-5180:input_data","SourceOutputPortId":"-5168:data"},{"DestinationInputPortId":"-5228:training_ds","SourceOutputPortId":"-5180:data"},{"DestinationInputPortId":"-5264:model","SourceOutputPortId":"-5228:model"},{"DestinationInputPortId":"-5248:instruments","SourceOutputPortId":"-5239:data"},{"DestinationInputPortId":"-5269:instruments","SourceOutputPortId":"-5239:data"},{"DestinationInputPortId":"-5258:input_1","SourceOutputPortId":"-5248:data"},{"DestinationInputPortId":"-827:input_data","SourceOutputPortId":"-5258:data_1"},{"DestinationInputPortId":"-5269:options_data","SourceOutputPortId":"-5264:predictions"},{"DestinationInputPortId":"-5264:data","SourceOutputPortId":"-827:data"}],"ModuleNodes":[{"Id":"-303","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2016-06-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":"-303"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-303","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-311","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v6","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-311"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-311"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-311","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-315","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"close_0\n\n \n\n","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":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-63","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"def u_factor(df):\n \n df['daily_return']=df['close'].pct_change()\n df['avg_month_return']=pd.rolling_mean(df['daily_return'],60)\n up=df['daily_return']>df['avg_month_return']\n df['up']=((df['daily_return']-df['avg_month_return'])**2)[up]\n df['up']=pd.rolling_mean(df['up'],60,min_periods=1)\n down=df['daily_return']<df['avg_month_return']\n df['down']=((df['daily_return']-df['avg_month_return'])**2)[down]\n df['down']=pd.rolling_mean(df['down'],60,min_periods=1)\n df['factor']=np.log(df['down']/df['up'])\n df.drop(['up','down','daily_return','avg_month_return'],axis=1)\n return df['factor']\n \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_df()\n \n start_date = df.date.min().strftime('%Y-%m-%d')\n end_date = df.date.max().strftime('%Y-%m-%d')\n \n instruments = list(set(df.instrument))\n n1 = M.user_feature_extractor.v1(\n instruments=instruments, start_date=start_date, end_date=end_date,\n history_data_fields=['close'], look_back_days=60, features_by_instrument={\n 'u_factor': u_factor \n }) \n \n df = n1.data.read_df().drop(['close', 'amount', 'daily_return',\n 'avg_month_return', 'up', 'down', 'u_factor'],axis=1)\n ds1 = DataSource.write_df(df)\n feature_lst = list(df.columns)\n feature_lst.remove('date')\n feature_lst.remove('instrument')\n ds2=DataSource.write_pickle(feature_lst)\n return Outputs(data_1=ds1, data_2=ds2, data_3=None)\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-63"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-63"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-63"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-63","OutputType":null},{"Name":"data_2","NodeId":"-63","OutputType":null},{"Name":"data_3","NodeId":"-63","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5157","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":"-5157"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-5157","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5168","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":"-5168"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"-5168"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-5168","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5180","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-5180"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-5180","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5228","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":"-5228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-5228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"-5228"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"-5228"}],"OutputPortsInternal":[{"Name":"model","NodeId":"-5228","OutputType":null},{"Name":"feature_gains","NodeId":"-5228","OutputType":null},{"Name":"m_lazy_run","NodeId":"-5228","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5239","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2017-01-02","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2018-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":"-5239"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-5239","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":9,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5248","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v6","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-5248"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-5248"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-5248","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5258","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"def u_factor(df):\n \n df['daily_return']=df['close'].pct_change()\n df['avg_month_return']=pd.rolling_mean(df['daily_return'],60)\n up=df['daily_return']>df['avg_month_return']\n df['up']=((df['daily_return']-df['avg_month_return'])**2)[up]\n df['up']=pd.rolling_mean(df['up'],60,min_periods=1)\n down=df['daily_return']<df['avg_month_return']\n df['down']=((df['daily_return']-df['avg_month_return'])**2)[down]\n df['down']=pd.rolling_mean(df['down'],60,min_periods=1)\n df['factor']=np.log(df['down']/df['up'])\n df.drop(['up','down','daily_return','avg_month_return'],axis=1)\n return df['factor']\n \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_df()\n \n start_date = df.date.min().strftime('%Y-%m-%d')\n end_date = df.date.max().strftime('%Y-%m-%d')\n \n instruments = list(set(df.instrument))\n n1 = M.user_feature_extractor.v1(\n instruments=instruments, start_date=start_date, end_date=end_date,\n history_data_fields=['close'], look_back_days=60, features_by_instrument={\n 'u_factor': u_factor \n }) \n \n df = n1.data.read_df().drop(['close', 'amount', 'daily_return',\n 'avg_month_return', 'up', 'down', 'u_factor'],axis=1)\n ds1 = DataSource.write_df(df)\n feature_lst = list(df.columns)\n feature_lst.remove('date')\n feature_lst.remove('instrument')\n ds2=DataSource.write_pickle(feature_lst)\n return Outputs(data_1=ds1, data_2=ds2, data_3=None)\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-5258"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-5258"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-5258"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-5258","OutputType":null},{"Name":"data_2","NodeId":"-5258","OutputType":null},{"Name":"data_3","NodeId":"-5258","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":11,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5264","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":"-5264"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data","NodeId":"-5264"}],"OutputPortsInternal":[{"Name":"predictions","NodeId":"-5264","OutputType":null},{"Name":"m_lazy_run","NodeId":"-5264","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-5269","ModuleId":"BigQuantSpace.trade.trade-v3","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","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":"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":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":"0.023","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":"benchmark","Value":"000300.SHA","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":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"amount_integer","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-5269"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-5269"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-5269","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":13,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-827","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-827"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-827","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"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='-303' Position='56,-18,200,200'/><NodePosition Node='-311' Position='310,81,200,200'/><NodePosition Node='-315' Position='612,-15,200,200'/><NodePosition Node='-63' Position='321,159,200,200'/><NodePosition Node='-5157' Position='-36,80,200,200'/><NodePosition Node='-5168' Position='107,249,200,200'/><NodePosition Node='-5180' Position='103,345,200,200'/><NodePosition Node='-5228' Position='519,270,200,200'/><NodePosition Node='-5239' Position='1040,-15,200,200'/><NodePosition Node='-5248' Position='835,79,200,200'/><NodePosition Node='-5258' Position='839,141,200,200'/><NodePosition Node='-5264' Position='734,353,200,200'/><NodePosition Node='-5269' Position='833,473,200,200'/><NodePosition Node='-827' Position='837,211,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]:
      # 本代码由可视化策略环境自动生成 2018年1月9日 11:07
      # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
      
      
      m1 = M.instruments.v2(
          start_date='2016-06-01',
          end_date='2017-01-01',
          market='CN_STOCK_A',
          instrument_list=' ',
          max_count=0
      )
      
      m5 = M.advanced_auto_labeler.v2(
          instruments=m1.data,
          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)
      """,
          start_date='',
          end_date='',
          benchmark='000300.SHA',
          drop_na_label=True,
          cast_label_int=True,
          user_functions={}
      )
      
      m3 = M.input_features.v1(
          features="""close_0
      
       
      
      """
      )
      
      m2 = M.general_feature_extractor.v6(
          instruments=m1.data,
          features=m3.data,
          start_date='',
          end_date='',
          before_start_days=0
      )
      
      def u_factor(df):
          
          df['daily_return']=df['close'].pct_change()
          df['avg_month_return']=pd.rolling_mean(df['daily_return'],60)
          up=df['daily_return']>df['avg_month_return']
          df['up']=((df['daily_return']-df['avg_month_return'])**2)[up]
          df['up']=pd.rolling_mean(df['up'],60,min_periods=1)
          down=df['daily_return']<df['avg_month_return']
          df['down']=((df['daily_return']-df['avg_month_return'])**2)[down]
          df['down']=pd.rolling_mean(df['down'],60,min_periods=1)
          df['factor']=np.log(df['down']/df['up'])
          df.drop(['up','down','daily_return','avg_month_return'],axis=1)
          return df['factor']
       
          
      # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
      def m4_run_bigquant_run(input_1, input_2, input_3):
           # 示例代码如下。在这里编写您的代码
          df = input_1.read_df()
          
          start_date = df.date.min().strftime('%Y-%m-%d')
          end_date = df.date.max().strftime('%Y-%m-%d')
          
          instruments =  list(set(df.instrument))
          n1 = M.user_feature_extractor.v1(
          instruments=instruments, start_date=start_date, end_date=end_date,
          history_data_fields=['close'], look_back_days=60, features_by_instrument={
          'u_factor': u_factor 
          })  
          
          df = n1.data.read_df().drop(['close',   'amount', 'daily_return',
             'avg_month_return', 'up', 'down', 'u_factor'],axis=1)
          ds1 = DataSource.write_df(df)
          feature_lst = list(df.columns)
          feature_lst.remove('date')
          feature_lst.remove('instrument')
          ds2=DataSource.write_pickle(feature_lst)
          return Outputs(data_1=ds1, data_2=ds2, data_3=None)
      
      m4 = M.cached.v3(
          input_1=m2.data,
          run=m4_run_bigquant_run
      )
      
      m6 = M.join.v3(
          data1=m5.data,
          data2=m4.data_1,
          on='date,instrument',
          how='inner',
          sort=False
      )
      
      m7 = M.dropnan.v1(
          input_data=m6.data
      )
      
      m8 = M.stock_ranker_train.v5(
          training_ds=m7.data,
          features=m4.data_2,
          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
      )
      
      m9 = M.instruments.v2(
          start_date='2017-01-02',
          end_date='2018-01-01',
          market='CN_STOCK_A',
          instrument_list='',
          max_count=0
      )
      
      m10 = M.general_feature_extractor.v6(
          instruments=m9.data,
          features=m3.data,
          start_date='',
          end_date='',
          before_start_days=0
      )
      
      def u_factor(df):
          
          df['daily_return']=df['close'].pct_change()
          df['avg_month_return']=pd.rolling_mean(df['daily_return'],60)
          up=df['daily_return']>df['avg_month_return']
          df['up']=((df['daily_return']-df['avg_month_return'])**2)[up]
          df['up']=pd.rolling_mean(df['up'],60,min_periods=1)
          down=df['daily_return']<df['avg_month_return']
          df['down']=((df['daily_return']-df['avg_month_return'])**2)[down]
          df['down']=pd.rolling_mean(df['down'],60,min_periods=1)
          df['factor']=np.log(df['down']/df['up'])
          df.drop(['up','down','daily_return','avg_month_return'],axis=1)
          return df['factor']
       
          
      # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
      def m11_run_bigquant_run(input_1, input_2, input_3):
           # 示例代码如下。在这里编写您的代码
          df = input_1.read_df()
          
          start_date = df.date.min().strftime('%Y-%m-%d')
          end_date = df.date.max().strftime('%Y-%m-%d')
          
          instruments =  list(set(df.instrument))
          n1 = M.user_feature_extractor.v1(
          instruments=instruments, start_date=start_date, end_date=end_date,
          history_data_fields=['close'], look_back_days=60, features_by_instrument={
          'u_factor': u_factor 
          })  
          
          df = n1.data.read_df().drop(['close',   'amount', 'daily_return',
             'avg_month_return', 'up', 'down', 'u_factor'],axis=1)
          ds1 = DataSource.write_df(df)
          feature_lst = list(df.columns)
          feature_lst.remove('date')
          feature_lst.remove('instrument')
          ds2=DataSource.write_pickle(feature_lst)
          return Outputs(data_1=ds1, data_2=ds2, data_3=None)
      
      m11 = M.cached.v3(
          input_1=m10.data,
          run=m11_run_bigquant_run
      )
      
      m14 = M.dropnan.v1(
          input_data=m11.data_1
      )
      
      m12 = M.stock_ranker_predict.v5(
          model=m8.model,
          data=m14.data,
          m_lazy_run=False
      )
      
      # 回测引擎:每日数据处理函数,每天执行一次
      def m13_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 m13_prepare_bigquant_run(context):
          pass
      
      # 回测引擎:初始化函数,只执行一次
      def m13_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 m13_before_trading_start_bigquant_run(context, data):
          pass
      
      m13 = M.trade.v3(
          instruments=m9.data,
          options_data=m12.predictions,
          start_date='',
          end_date='',
          handle_data=m13_handle_data_bigquant_run,
          prepare=m13_prepare_bigquant_run,
          initialize=m13_initialize_bigquant_run,
          before_trading_start=m13_before_trading_start_bigquant_run,
          volume_limit=0.023,
          order_price_field_buy='open',
          order_price_field_sell='close',
          capital_base=1000000,
          benchmark='000300.SHA',
          auto_cancel_non_tradable_orders=True,
          data_frequency='daily',
          price_type='后复权',
          plot_charts=True,
          backtest_only=False,
          amount_integer=False
      )
      
      [2018-01-09 11:03:51.667252] INFO: bigquant: instruments.v2 开始运行..
      [2018-01-09 11:03:51.675979] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.678102] INFO: bigquant: instruments.v2 运行完成[0.010889s].
      [2018-01-09 11:03:51.691237] INFO: bigquant: advanced_auto_labeler.v2 开始运行..
      [2018-01-09 11:03:51.695795] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.697735] INFO: bigquant: advanced_auto_labeler.v2 运行完成[0.006475s].
      [2018-01-09 11:03:51.705586] INFO: bigquant: input_features.v1 开始运行..
      [2018-01-09 11:03:51.710664] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.712206] INFO: bigquant: input_features.v1 运行完成[0.006619s].
      [2018-01-09 11:03:51.727046] INFO: bigquant: general_feature_extractor.v6 开始运行..
      [2018-01-09 11:03:51.736257] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.738075] INFO: bigquant: general_feature_extractor.v6 运行完成[0.011033s].
      [2018-01-09 11:03:51.751365] INFO: bigquant: cached.v3 开始运行..
      [2018-01-09 11:03:51.756557] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.758060] INFO: bigquant: cached.v3 运行完成[0.006687s].
      [2018-01-09 11:03:51.768890] INFO: bigquant: join.v3 开始运行..
      [2018-01-09 11:03:51.776502] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.783975] INFO: bigquant: join.v3 运行完成[0.011997s].
      [2018-01-09 11:03:51.798464] INFO: bigquant: dropnan.v1 开始运行..
      [2018-01-09 11:03:51.802266] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.803843] INFO: bigquant: dropnan.v1 运行完成[0.005396s].
      [2018-01-09 11:03:51.837052] INFO: bigquant: stock_ranker_train.v5 开始运行..
      [2018-01-09 11:03:51.841689] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.843094] INFO: bigquant: stock_ranker_train.v5 运行完成[0.006096s].
      [2018-01-09 11:03:51.850974] INFO: bigquant: instruments.v2 开始运行..
      [2018-01-09 11:03:51.866097] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.869908] INFO: bigquant: instruments.v2 运行完成[0.018925s].
      [2018-01-09 11:03:51.887695] INFO: bigquant: general_feature_extractor.v6 开始运行..
      [2018-01-09 11:03:51.891576] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.893065] INFO: bigquant: general_feature_extractor.v6 运行完成[0.005396s].
      [2018-01-09 11:03:51.910639] INFO: bigquant: cached.v3 开始运行..
      [2018-01-09 11:03:51.917216] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.919714] INFO: bigquant: cached.v3 运行完成[0.009126s].
      [2018-01-09 11:03:51.935648] INFO: bigquant: dropnan.v1 开始运行..
      [2018-01-09 11:03:51.939263] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.940849] INFO: bigquant: dropnan.v1 运行完成[0.005193s].
      [2018-01-09 11:03:51.970169] INFO: bigquant: stock_ranker_predict.v5 开始运行..
      [2018-01-09 11:03:51.983970] INFO: bigquant: 命中缓存
      [2018-01-09 11:03:51.985710] INFO: bigquant: stock_ranker_predict.v5 运行完成[0.015592s].
      [2018-01-09 11:03:52.200970] INFO: algo: set price type:backward_adjusted
      [2018-01-09 11:04:36.661551] INFO: Performance: Simulated 244 trading days out of 244.
      [2018-01-09 11:04:36.663380] INFO: Performance: first open: 2017-01-03 01:30:00+00:00
      [2018-01-09 11:04:36.664648] INFO: Performance: last close: 2017-12-29 07:00:00+00:00
      
      • 收益率-11.31%
      • 年化收益率-11.66%
      • 基准收益率21.78%
      • 阿尔法-0.28
      • 贝塔0.65
      • 夏普比率-0.8
      • 胜率0.511
      • 盈亏比0.963
      • 收益波动率20.22%
      • 信息比率-1.76
      • 最大回撤21.17%