自定义模块教程-排序和股票代码过滤

策略分享
自定义模块
标签: #<Tag:0x00007fcf6a36db98> #<Tag:0x00007fcf6a36da08>

(iQuant) #1

参考 自定义模块教程-开发一个修改数据列名的模块为例-超级详细版 开发自定义模块

新增加了两个模块:

  • 排序,对输入数据源数据做排序,支持分组,在组内排序
  • 股票代码过滤,这个用来加速回测过程的,只选取需要的预测结果来传入到回测模块,可以减少回测需要加载的数据,加速回测

完整代码和测试例子如下:

克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-121:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-128:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-276:input_2","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-96:sort_by_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-121:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-276:input_1","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-96:input_ds","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"-181:input_data","SourceOutputPortId":"-121:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-128:data"},{"DestinationInputPortId":"-128:input_data","SourceOutputPortId":"-181:data"},{"DestinationInputPortId":"-154:input_1","SourceOutputPortId":"-122:data"},{"DestinationInputPortId":"-89:instrument_ds","SourceOutputPortId":"-122:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81:instruments","SourceOutputPortId":"-89:data_1"},{"DestinationInputPortId":"-154:input_2","SourceOutputPortId":"-96:data_1"},{"DestinationInputPortId":"-89:prediction_ds","SourceOutputPortId":"-96:data_1"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81:options_data","SourceOutputPortId":"-96:data_1"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"st_status_0\n-pe_ttm_0\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":3,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2018-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2018-08-14","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":9,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-81","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.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.5\n context.options['hold_days'] = 1\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":12,"Comment":"","CommentCollapsed":true},{"Id":"-86","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-86"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-86","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":14,"Comment":"","CommentCollapsed":true},{"Id":"-121","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-121"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-121"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-121","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"Comment":"","CommentCollapsed":true},{"Id":"-128","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":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-128"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-128"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-128","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"Comment":"","CommentCollapsed":true},{"Id":"-181","ModuleId":"BigQuantSpace.filter.filter-v3","ModuleParameters":[{"Name":"expr","Value":"st_status_0==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":"-181"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-181","OutputType":null},{"Name":"left_data","NodeId":"-181","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":26,"Comment":"","CommentCollapsed":true},{"Id":"-122","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2018-02-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2018-08-14","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":"-122"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-122","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":true},{"Id":"-276","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_ds, sort_by_ds, sort_by='', group_by='', keep_columns='', ascending=True):\n df = input_ds.read_df()\n group_by = group_by and group_by.strip()\n group_by = group_by.split(',')\n if sort_by_ds is not None:\n sort_by = sort_by_ds.read_pickle()\n else:\n sort_by = sort_by.strip().split(',')\n if not group_by or group_by == '--':\n df = df.sort_values(sort_by, ascending=ascending)\n else:\n group_by = group_by\n df = df.groupby('date').apply(lambda x: x.sort_values(sort_by, ascending=ascending)).reset_index(drop=True)\n\n if keep_columns and keep_columns != '--':\n keep_columns = keep_columns.strip()\n keep_columns = keep_columns.split(',')\n df = df[keep_columns]\n data = DataSource.write_df(df)\n return Outputs(data_1=data)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"input_ds,sort_by_ds","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'sort_by': '',\n 'group_by': 'date',\n 'keep_columns': '',\n 'ascending': true\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"data_1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-276"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-276"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-276"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-276","OutputType":null},{"Name":"data_2","NodeId":"-276","OutputType":null},{"Name":"data_3","NodeId":"-276","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"Comment":"","CommentCollapsed":true},{"Id":"-154","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(instrument_ds, prediction_ds, count):\n if T.live_run_param('trading_date', None):\n # 如果是模拟交易模式,不做任何操作,模拟模式下,预测结果里没有包含已经持有的股票\n return Outputs(data_1=instrument_ds)\n\n df = prediction_ds.read_df()\n if count > 0:\n df = df.groupby('date', as_index=False).apply(lambda x: x[:count]).reset_index(drop=True)\n prediction_instruments = set(df.instrument)\n data = instrument_ds.read_pickle()\n old_count = len(data['instruments'])\n data['instruments'] = [i for i in data['instruments'] if i in prediction_instruments]\n print('%s/%s' % (len(data['instruments']), old_count))\n data_ds = DataSource.write_pickle(data)\n return Outputs(data_1=data_ds)\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"post_run","Value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"input_ports","Value":"instrument_ds,prediction_ds","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"params","Value":"{\n 'count': 5\n}","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"output_ports","Value":"data_1","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-154"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-154"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-154"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-154","OutputType":null},{"Name":"data_2","NodeId":"-154","OutputType":null},{"Name":"data_3","NodeId":"-154","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"Comment":"","CommentCollapsed":true},{"Id":"-89","ModuleId":"BigQuantSpace.filter_instruments_with_predictions.filter_instruments_with_predictions-v3","ModuleParameters":[{"Name":"count","Value":"5","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instrument_ds","NodeId":"-89"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"prediction_ds","NodeId":"-89"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-89","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"Comment":"","CommentCollapsed":true},{"Id":"-96","ModuleId":"BigQuantSpace.sort.sort-v4","ModuleParameters":[{"Name":"sort_by","Value":"--","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"group_by","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"keep_columns","Value":"date,instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"ascending","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_ds","NodeId":"-96"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"sort_by_ds","NodeId":"-96"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-96","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='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='1311,-8,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='971,-18,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-81' Position='1075.93896484375,752.1268310546875,200,200'/><NodePosition Node='-86' Position='1078,398,200,200'/><NodePosition Node='-121' Position='1079,101,200,200'/><NodePosition Node='-128' Position='1081,304,200,200'/><NodePosition Node='-181' Position='1079,212,200,200'/><NodePosition Node='-122' Position='529,273,200,200'/><NodePosition Node='-276' Position='675,495,200,200'/><NodePosition Node='-154' Position='683,643,200,200'/><NodePosition Node='-89' Position='1075.2388916015625,635.751220703125,200,200'/><NodePosition Node='-96' Position='1074.812255859375,508.06097412109375,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 [59]:
    # 本代码由可视化策略环境自动生成 2018年8月15日 10:41
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m3 = M.input_features.v1(
        features="""st_status_0
    -pe_ttm_0
    """
    )
    
    m9 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2018-01-01'),
        end_date=T.live_run_param('trading_date', '2018-08-14'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m17 = M.general_feature_extractor.v7(
        instruments=m9.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m26 = M.filter.v3(
        input_data=m17.data,
        expr='st_status_0==0',
        output_left_data=False
    )
    
    m18 = M.derived_feature_extractor.v3(
        input_data=m26.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument'
    )
    
    m14 = M.dropnan.v1(
        input_data=m18.data
    )
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m1_run_bigquant_run(input_ds, sort_by_ds, sort_by='', group_by='', keep_columns='', ascending=True):
        df = input_ds.read_df()
        group_by = group_by and group_by.strip()
        group_by = group_by.split(',')
        if sort_by_ds is not None:
            sort_by = sort_by_ds.read_pickle()
        else:
            sort_by = sort_by.strip().split(',')
        if not group_by or group_by == '--':
            df = df.sort_values(sort_by, ascending=ascending)
        else:
            group_by = group_by
            df = df.groupby('date').apply(lambda x: x.sort_values(sort_by, ascending=ascending)).reset_index(drop=True)
    
        if keep_columns and keep_columns != '--':
            keep_columns = keep_columns.strip()
            keep_columns = keep_columns.split(',')
            df = df[keep_columns]
        data = DataSource.write_df(df)
        return Outputs(data_1=data)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m1_post_run_bigquant_run(outputs):
        return outputs
    
    m1 = M.cached.v3(
        input_1=m14.data,
        input_2=m3.data,
        run=m1_run_bigquant_run,
        post_run=m1_post_run_bigquant_run,
        input_ports='input_ds,sort_by_ds',
        params="""{
        'sort_by': '',
        'group_by': 'date',
        'keep_columns': '',
        'ascending': true
    }""",
        output_ports='data_1'
    )
    
    m7 = M.sort.v4(
        input_ds=m14.data,
        sort_by_ds=m3.data,
        sort_by='--',
        group_by='date',
        keep_columns='date,instrument',
        ascending=True
    )
    
    m4 = M.instruments.v2(
        start_date='2018-02-01',
        end_date='2018-08-14',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m2_run_bigquant_run(instrument_ds, prediction_ds, count):
        if T.live_run_param('trading_date', None):
            # 如果是模拟交易模式,不做任何操作,模拟模式下,预测结果里没有包含已经持有的股票
            return Outputs(data_1=instrument_ds)
    
        df = prediction_ds.read_df()
        if count > 0:
            df = df.groupby('date', as_index=False).apply(lambda x: x[:count]).reset_index(drop=True)
        prediction_instruments = set(df.instrument)
        data = instrument_ds.read_pickle()
        old_count = len(data['instruments'])
        data['instruments'] = [i for i in data['instruments'] if i in prediction_instruments]
        print('%s/%s' % (len(data['instruments']), old_count))
        data_ds = DataSource.write_pickle(data)
        return Outputs(data_1=data_ds)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m2_post_run_bigquant_run(outputs):
        return outputs
    
    m2 = M.cached.v3(
        input_1=m4.data,
        input_2=m7.data_1,
        run=m2_run_bigquant_run,
        post_run=m2_post_run_bigquant_run,
        input_ports='instrument_ds,prediction_ds',
        params="""{
        'count': 5
    }""",
        output_ports='data_1'
    )
    
    m6 = M.filter_instruments_with_predictions.v3(
        instrument_ds=m4.data,
        prediction_ds=m7.data_1,
        count=5
    )
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m12_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 m12_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:初始化函数,只执行一次
    def m12_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.5
        context.options['hold_days'] = 1
    
    m12 = M.trade.v3(
        instruments=m6.data_1,
        options_data=m7.data_1,
        start_date='',
        end_date='',
        handle_data=m12_handle_data_bigquant_run,
        prepare=m12_prepare_bigquant_run,
        initialize=m12_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-08-15 10:40:19.361068] INFO: bigquant: input_features.v1 开始运行..
    [2018-08-15 10:40:19.367790] INFO: bigquant: input_features.v1 运行完成[0.006728s].
    [2018-08-15 10:40:19.370125] INFO: bigquant: instruments.v2 开始运行..
    [2018-08-15 10:40:19.373018] INFO: bigquant: 命中缓存
    [2018-08-15 10:40:19.373687] INFO: bigquant: instruments.v2 运行完成[0.003552s].
    [2018-08-15 10:40:19.378054] INFO: bigquant: general_feature_extractor.v7 开始运行..
    [2018-08-15 10:40:19.381176] INFO: bigquant: 命中缓存
    [2018-08-15 10:40:19.381995] INFO: bigquant: general_feature_extractor.v7 运行完成[0.003975s].
    [2018-08-15 10:40:19.384313] INFO: bigquant: filter.v3 开始运行..
    [2018-08-15 10:40:19.386953] INFO: bigquant: 命中缓存
    [2018-08-15 10:40:19.387698] INFO: bigquant: filter.v3 运行完成[0.003393s].
    [2018-08-15 10:40:19.389950] INFO: bigquant: derived_feature_extractor.v3 开始运行..
    [2018-08-15 10:40:19.649971] INFO: derived_feature_extractor: 提取完成 -pe_ttm_0, 0.046s
    [2018-08-15 10:40:19.779297] INFO: derived_feature_extractor: /y_2018, 486608
    [2018-08-15 10:40:20.036120] INFO: bigquant: derived_feature_extractor.v3 运行完成[0.646132s].
    [2018-08-15 10:40:20.039059] INFO: bigquant: dropnan.v1 开始运行..
    [2018-08-15 10:40:20.461151] INFO: dropnan: /y_2018, 486608/486608
    [2018-08-15 10:40:20.474434] INFO: dropnan: 行数: 486608/486608
    [2018-08-15 10:40:20.492516] INFO: bigquant: dropnan.v1 运行完成[0.45342s].
    [2018-08-15 10:40:20.496100] INFO: bigquant: sort.v4 开始运行..
    [2018-08-15 10:40:21.678667] INFO: bigquant: sort.v4 运行完成[1.182556s].
    [2018-08-15 10:40:21.681446] INFO: bigquant: instruments.v2 开始运行..
    [2018-08-15 10:40:21.685026] INFO: bigquant: 命中缓存
    [2018-08-15 10:40:21.685960] INFO: bigquant: instruments.v2 运行完成[0.004518s].
    [2018-08-15 10:40:21.689355] INFO: bigquant: filter_instruments_with_predictions.v3 开始运行..
    19/3541
    [2018-08-15 10:40:21.940604] INFO: bigquant: filter_instruments_with_predictions.v3 运行完成[0.251234s].
    [2018-08-15 10:40:21.951638] INFO: bigquant: backtest.v7 开始运行..
    [2018-08-15 10:40:21.954125] INFO: bigquant: biglearning backtest:V7.1.2
    [2018-08-15 10:40:27.078166] INFO: algo: TradingAlgorithm V1.2.5
    [2018-08-15 10:40:30.086421] INFO: Performance: Simulated 129 trading days out of 129.
    [2018-08-15 10:40:30.087425] INFO: Performance: first open: 2018-02-01 09:30:00+00:00
    [2018-08-15 10:40:30.088440] INFO: Performance: last close: 2018-08-14 15:00:00+00:00
    
    • 收益率-13.41%
    • 年化收益率-24.51%
    • 基准收益率-21.12%
    • 阿尔法0.17
    • 贝塔0.92
    • 夏普比率-0.88
    • 胜率0.48
    • 盈亏比1.02
    • 收益波动率30.15%
    • 信息比率0.06
    • 最大回撤24.17%
    [2018-08-15 10:40:31.125691] INFO: bigquant: backtest.v7 运行完成[9.174035s].