BigStudio使用文档介绍(四)

bigstudio
标签: #<Tag:0x00007f5bff2814e8>

(iQuant) #1

本文详细介绍BigStudio可视化实验中各个模块,希望大家对每个模块的功能和使用更加了解。

通过上一篇文章《BigStudio使用文档介绍(三)》,了解到BigStudio可视化实验工作流如下:

从这幅图可以看出,BigStudio上的可视化AI量化策略主要包括数据标注、特征抽取、模型训练、模型预测、回测交易5个部分,但却包含了多个小模块。本文从微观层面单独介绍各个小模块。

(由于本文篇幅较长,为增强阅读体验,部分内容需手动点击才能展开,带黑色实心三角符号的内容可直接点击展开查阅。例如 属性窗格。)

属性窗格

我们从微观层面具体了解每一个模块。在单独介绍每个模块之前,先来介绍属性窗格的常用按钮。以 模块证券代码列表 举例:

image

其中图上一共有5个绿色标记。按从上到下的顺序,第一个点击可以折叠整个属性窗格,第二个可以折叠该模块的属性;第三个是下拉选项,点击可以展开下来列表进行选择;第四个是复选框,表明是否启用缓存加速, 如果开启,每次运行的时候会先检查之前是否有运行结果,如果有,就直接输出上次运行结果。最下面一个点击可以折叠帮助界面。点击帮助可以获得相关模块的文档介绍。

画布中的各个模块:

由于特征抽取部分包括训练数据的特征抽取和评估数据的特征抽取,本文只介绍训练数据的特征抽取。评估数据的特征抽取同理,只是数据不一样(数据由start_date和end_date决定)。

证券代码列表

帮助文档: 证券代码列表
image

  • 开始日期:start_date (str) 。示例 2017-02-12。
  • 结束日期:end_date (str) 。示例 2017-02-12。
  • 交易市场:market(str)。获取哪个市场的证券列表,下拉列表有多个选择
  • 最大数量:max_count(float)。获取证券数量,如果设置为0就表明没有限制。

自动数据标注

帮助文档: 自动数据标注
image

  • 开始日期:start_date (str) 。示例 2017-02-12。
  • 结束日期:start_date (str) 。示例 2017-02-12。
  • 标注表达式:这里是一个代码编辑器,点击可放大,也可以点击弹出代码编辑器窗口,可手动输入标注表达式。

输入特征列表

帮助文档: 输入特征列表
image

  • 特征数据 :为一个代码编辑器窗口,可手动输入特征数据

基础特征抽取

帮助文档: 基础特征抽取
image

  • 开始日期:start_date (str)。示例 2017-02-12。
  • 结束日期:end_date (str) 。示例 2017-02-12。

衍生特征抽取

帮助文档:衍生特征列表
image

  • 日期列名:date_col (str) 。如果在表达式中用到切面相关函数时,比如 rank,会用到此列名;默认值是date。
  • 证券代码列名:instrument_col (str) 。如果在表达式中用到时间序列相关函数时,比如 shift,会用到此列名;默认值是instrument。

连接数据

帮助文档: 连接数据
image

  • 关联列:on (str) 。多个列用英文逗号分隔;默认值是date,instrument。
  • 连接方式:how (choice) 。可选值有: left, right, outer, inner;默认值是inner。
  • 对结果排序:sort (bool) 。默认值是False。

缺失数据处理

image
除了是否启用缓存加速,缺失数据处理模块没有其他参数。

StockRanker训练

帮助文档:StockRanker训练
image

  • 学习算法:learning_algorithm (choice) 。机器学习优化算法;可选值有: 排序, 回归, 二分类, logloss;默认值是排序。

  • 叶节点数量:number_of_leaves (int) 。每棵树最大叶节点数量。一般情况下,叶子节点越多,则模型越复杂,表达能力越强,过拟合的可能性也越高;默认值是30。

  • 每叶节点最小样本数:minimum_docs_per_leaf (int) 。每个叶节点最少需要的样本数量,一般值越大,泛化性性越好;默认值是1000。

  • 树的数量:number_of_trees (int) 。一般情况下,树越多,则模型越复杂,表达能力越强,过拟合的可能性也越高;默认值是20。

  • 学习率:learning_rate (float) – 学习率:学习率如果太大,可能会使结果越过最优值,如果太小学习会很慢;默认值是0.1。

  • 特征值离散化数量:max_bins (int) 。一般情况下,max_bins越大,则学的越细,过拟合的可能性也越高;默认值是1023。

  • 特征使用率:feature_fraction (int)。在构建每一颗树时,每个特征被使用的概率,如果为1,则每棵树都会使用所有特征;默认值是1。


StockRanker预测

帮助文档:StockRanker预测
image

Trade(回测/模拟)

帮助文档:Trade(回测/模拟)
image

  • 开始日期:start_date (str)。设定值只在回测模式有效,在模拟实盘模式下为当前日期
  • 结束日期:end_date (str)。设定值只在回测模式有效,在模拟实盘模式下为当前日期
  • 主函数:handle_data (函数)。必须实现的函数,该函数每个单位时间会调用一次, 如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次,由于我们现在数据只有日K,所以是按天回调。在回测中,可以通过对象data获取单只股票或多只股票的时间窗口价格数据。如果算法中没有schedule_function函数,那么该函数为必选函数。一般策略的交易逻辑和订单生成体现在该函数中;默认值是None。
  • 数据准备函数:prepare (函数) 。准备数据函数,运行过程中只调用一次,在 initialize 前调用,准备交易中需要用到数据。目前支持设置交易中用到的股票列表,设置到 context.instruments。

image

  • 初始化函数:initialize (函数) 。整个回测中只在最开始时调用一次,用于初始化一些账户状态信息和策略基本参数,context也可以理解为一个全局变量,在回测中存放当前账户信息和策略基本参数便于会话;默认值是None。
  • 盘前处理函数:before_trading_start (函数) 。每个单位时间开始前调用一次,即每日开盘前调用一次,该函数是可选函数。你的算法可以在该函数中进行一些数据处理计算,比如确定当天有交易信号的股票池;
  • 成交率限制:volume_limit (float)。执行下单时控制成交量参数,默认值2.5%,若设置为0时,不进行成交量检查;默认值是0.025。

image

  • 买入点:order_price_field_buy (choice) 。open=开盘买入,close=收盘买入;可选值有: open, close;默认值是open。
  • 卖出点:order_price_field_sell (choice) 。open=开盘卖出,close=收盘卖出;可选值有: open, close;默认值是close。
  • 初始资金:capital_base (float) 。默认值是1000000.0。
  • 基准指数:benchmark (str)。不影响回测结果;默认值是000300.SHA。
  • 自动取消无法成交的订单:auto_cancel_non_tradable_orders (bool) 。是否自动取消因为停牌等原因不能成交的订单;默认值是True。
  • 回测数据频率:data_frequency (choice)。目前只支持日线 (daily),未来将支持分钟线 (minute);可选值有: daily;默认值是daily。
  • 显示回测结果图表:plot_charts (bool) – 显示回测结果图表;默认值是True。
  • 只在回测模式下运行:backtest_only (bool) 。默认情况下,Trade会在回测和实盘模拟模式下都运行。如果策略中有多个M.trade,在实盘模拟模式下,只能有一个设置为运行,其他的需要设置为 backtest_only=True,否则将会有未定义的行为错误;默认值是False。

现在,BigStudio上的AI量化策略的模块已经介绍完毕。当我们新建一个可视化AI量化策略的时候,我们不用做太多的改动,直接使用模板,然后调一下参数,将精力更多地放在特征抽取和数据标注上。接下来,我们会介绍如何自定义模块和使用更灵活地特征抽取和数据标注。



BigStudio使用文档介绍(三)
(1899) #4

像这种,在给训练阶段每个模块定义的时候,每次都要填开始日期和结束日期,但实际上是一样的。如果不填的话,会自动默认之前模块的开始以及结束日期么image


(iQuant) #5

是的,因为 基础特征抽取会以其他模块作为输入,比如证券代码列表,而证券代码列表是需要输入开始日期和结束日期的,因此基础特征抽取默认会以证券代码列表模块的开始日期和结束日期。


(1899) #6

请问每次在运行的时候都会做因子预处理么,包括极值处理、标准化等。要是不做的话会不会效果不好


(iQuant) #7

是这样的。数据预处理在数据分析、数据挖掘中非常普遍也非常重要,就本问题而言,如果不做极值处理或者标准化处理,结果是不可信的,即使获得了一个不错的结果,那也是没有太多的参考价值。


(PAYNE) #8

能说说 基础特征值 和 衍生特征值的区别么?


(小Q) #9

比如你在策略里有这样一个因子:

ta_rsi_14_0/ta_rsi_28_0

那么要抽取这个因子数据在平台上实际上是这样的一个流程:

  • 基础特征抽取,先抽取出ta_rsi_14_0 和ta_rsi_28_0

  • 衍生特征抽取,根据基础特征计算出ta_rsi_14_0/ta_rsi_28_0


(11117) #10

有两个问题请教一下:
(1)目前平台上的随机森林、GBDT都是支持多分类预测的,假如我根据收益率给股票打标签的时候分成了20个类别并且每个类别都有其对应的分数,那么使用模型预测时,是根据模型支持的多分类预测呢还是根据分数值做的回归预测呢?
(2)当我使用其他模型做预测时,例如决策树或者SVM,能不能也使用该标注方式呢?
谢谢!


(1899) #11

请问有没有推荐的list-wise排序模型的资料阿,谢谢


(神龙斗士) #12
  1. 用分类或者回归都可以尝试,分类或者排序可能更好一点
  2. 可以的,我们也在接入更多标准的算法进来。你也可以自己开发算法接入进来

[量化学堂-机器学习]机器学习有哪些常用算法
(神龙斗士) #13

可以Google:learning to rank list wise


(11117) #14

请问平台使用的排序算法是list-wise还是pair-wise?


(jove) #15

请问:StockRank训练模块之前的数据里面的Feature值都没有进行归一化,或标准化处理。这样的数据进入训练模块的到的结果是否合理?还是StockRank训练模块在训练前,自动对进入的数据进行了归一化,或标准化处理?
如果这个可视化环境没有进行归一化,或标准化处理,是否自己要添加模块,进行数据预处理?比如用M.transform模块,但可视化环境中没有找见这个模块,只有过滤模块。


(小Q) #17

你好,问题提的很好,在很多数据挖掘和机器学习的算法案例里,需要对数据进行一些处理,比如去极值、标准化等,样例策略里以StockRanker排序算法为例,该排序算法并不一定需要对数据进行这类的处理,如果你想处理的话,直接在可视化里面添加一个去极值和标准化处理的自定义模块即可,稍后我们给一个例子。


(iQuant) #18

今天室外雪花飘落,气温骤降,哪里也不愿去。小编按照 @jove的思想写了个例子,就是在模型训练之前对feature进行去极值和标准化处理,具体就是在模型训练之前加了一个自定义模块。自定义模块主要是去极值、标准化函数。
代码如下:

# 去极值
def remove_extremum(df,factors):
    factor_list = factors
    for factor in factor_list:
        df[factor][df[factor] >= np.percentile(df[factor], 95)] = np.percentile(df[factor], 95)
        df[factor][df[factor] <= np.percentile(df[factor], 5)] = np.percentile(df[factor], 5)
    return df

# 标准化
def standardization(df,factors):
    factor_list = factors
    for factor in factor_list:
        df[factor] = (df[factor] - df[factor].mean()) / df[factor].std()
    return df 

def deal_with_factors(df,factors):
    return standardization(remove_extremum(df,factors),factors)

# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
def bigquant_run(input_1, input_2, input_3):
    df = input_1.read_df()
    df.index = range(len(df))
    factors = [i for i in df.columns if i[0:2] != 'm:'and i not in ['date','instrument','label']]
    factors_df_after_deal_with = df.groupby('date').apply(deal_with_factors,factors=factors)
    factors_df_after_deal_with.reset_index(inplace=True,drop=True)
    data_1 = DataSource.write_df(factors_df_after_deal_with)
    return Outputs(data_1=data_1, data_2=None, data_3=None)

完整策略如下,从结果上来看,效果比不做标准化处理的结果差一半,这主要是与StockRanker排序算法有关,排序算法不需要对特征数据进行一些处理。

克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-29:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-29:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-35:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-35:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-29:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-35:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:model"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-81:options_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70:instruments","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-76:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76:data"},{"DestinationInputPortId":"-140:input_1","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"-148:input_1","SourceOutputPortId":"-86:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:training_ds","SourceOutputPortId":"-140:data_1"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-148:data_1"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_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,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nreturn_5\nreturn_10\nreturn_20\navg_amount_0/avg_amount_5\navg_amount_5/avg_amount_20\nrank_avg_amount_0/rank_avg_amount_5\nrank_avg_amount_5/rank_avg_amount_10\nrank_return_0\nrank_return_5\nrank_return_10\nrank_return_0/rank_return_5\nrank_return_5/rank_return_10\npe_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,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-29","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-29"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-29"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-29","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-35","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v2","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-35"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-35"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-35","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","ModuleId":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v5","ModuleParameters":[{"Name":"learning_algorithm","Value":"排序","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_leaves","Value":30,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"minimum_docs_per_leaf","Value":1000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"number_of_trees","Value":20,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"learning_rate","Value":0.1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_bins","Value":1023,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"feature_fraction","Value":1,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"m_lazy_run","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"training_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"test_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"base_model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43"}],"OutputPortsInternal":[{"Name":"model","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null},{"Name":"feature_gains","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null},{"Name":"m_lazy_run","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-43","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","ModuleId":"BigQuantSpace.join.join-v3","ModuleParameters":[{"Name":"on","Value":"date,instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"how","Value":"inner","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"sort","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data1","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"data2","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"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":8,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-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":9,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-70","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-70"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-70","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":10,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-76","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v2","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":"287d2cb0-f53c-4101-bdf8-104b137c8601-76"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-76","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":11,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"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.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":12,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","ModuleId":"BigQuantSpace.dropnan.dropnan-v1","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":13,"IsPartOfPartialRun":null,"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,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-140","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# 去极值\ndef remove_extremum(df,factors):\n factor_list = factors\n for factor in factor_list:\n df[factor][df[factor] >= np.percentile(df[factor], 95)] = np.percentile(df[factor], 95)\n df[factor][df[factor] <= np.percentile(df[factor], 5)] = np.percentile(df[factor], 5)\n return df\n\n# 标准化\ndef standardization(df,factors):\n factor_list = factors\n for factor in factor_list:\n df[factor] = (df[factor] - df[factor].mean()) / df[factor].std()\n return df \n\ndef deal_with_factors(df,factors):\n return standardization(remove_extremum(df,factors),factors)\n\n# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3):\n df = input_1.read_df()\n df.index = range(len(df))\n factors = [i for i in df.columns if i[0:2] != 'm:'and i not in ['date','instrument','label']]\n factors_df_after_deal_with = df.groupby('date').apply(deal_with_factors,factors=factors)\n factors_df_after_deal_with.reset_index(inplace=True,drop=True)\n data_1 = DataSource.write_df(factors_df_after_deal_with)\n return Outputs(data_1=data_1, data_2=None, data_3=None)\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-140"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-140"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-140"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-140","OutputType":null},{"Name":"data_2","NodeId":"-140","OutputType":null},{"Name":"data_3","NodeId":"-140","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-148","ModuleId":"BigQuantSpace.cached.cached-v3","ModuleParameters":[{"Name":"run","Value":"# 去极值\ndef remove_extremum(df,factors):\n factor_list = factors\n for factor in factor_list:\n df[factor][df[factor] >= np.percentile(df[factor], 95)] = np.percentile(df[factor], 95)\n df[factor][df[factor] <= np.percentile(df[factor], 5)] = np.percentile(df[factor], 5)\n return df\n\n# 标准化\ndef standardization(df,factors):\n factor_list = factors\n for factor in factor_list:\n df[factor] = (df[factor] - df[factor].mean()) / df[factor].std()\n return df \n\ndef deal_with_factors(df,factors):\n return standardization(remove_extremum(df,factors),factors)\n\n# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3):\n df = input_1.read_df()\n df.index = range(len(df))\n factors = [i for i in df.columns if i[0:2] != 'm:'and i not in ['date','instrument','label']]\n factors_df_after_deal_with = df.groupby('date').apply(deal_with_factors,factors=factors)\n factors_df_after_deal_with.reset_index(inplace=True,drop=True)\n data_1 = DataSource.write_df(factors_df_after_deal_with)\n return Outputs(data_1=data_1, data_2=None, data_3=None)\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-148"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_2","NodeId":"-148"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_3","NodeId":"-148"}],"OutputPortsInternal":[{"Name":"data_1","NodeId":"-148","OutputType":null},{"Name":"data_2","NodeId":"-148","OutputType":null},{"Name":"data_3","NodeId":"-148","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='211,64,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='70,183,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='765,21,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-29' Position='381,188,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-35' Position='385,280,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-43' Position='668,603,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='931,677,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1074,127,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-70' Position='1078,236,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-76' Position='1081,327,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-81' Position='1037,751,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-84' Position='303,451,200,200'/><NodePosition Node='-86' Position='1078,418,200,200'/><NodePosition Node='-140' Position='393,526,200,200'/><NodePosition Node='-148' Position='1080,505,200,200'/></NodePositions><NodeGroups /></DataV1>"},"IsDraft":true,"ParentExperimentId":null,"WebService":{"IsWebServiceExperiment":false,"Inputs":[],"Outputs":[],"Parameters":[{"Name":"交易日期","Value":"","ParameterDefinition":{"Name":"交易日期","FriendlyName":"交易日期","DefaultValue":"","ParameterType":"String","HasDefaultValue":true,"IsOptional":true,"ParameterRules":[],"HasRules":false,"MarkupType":0,"CredentialDescriptor":null}}],"WebServiceGroupId":null,"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions></NodePositions><NodeGroups /></DataV1>"},"DisableNodesUpdate":false,"Category":"user","Tags":[],"IsPartialRun":true}
    In [27]:
    # 本代码由可视化策略环境自动生成 2018年1月27日 14:12
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date='2010-01-01',
        end_date='2015-01-01',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m2 = 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
    )
    
    m3 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    return_5
    return_10
    return_20
    avg_amount_0/avg_amount_5
    avg_amount_5/avg_amount_20
    rank_avg_amount_0/rank_avg_amount_5
    rank_avg_amount_5/rank_avg_amount_10
    rank_return_0
    rank_return_5
    rank_return_10
    rank_return_0/rank_return_5
    rank_return_5/rank_return_10
    pe_ttm_0
    """
    )
    
    m4 = M.general_feature_extractor.v6(
        instruments=m1.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m5 = M.derived_feature_extractor.v2(
        input_data=m4.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument'
    )
    
    m7 = M.join.v3(
        data1=m2.data,
        data2=m5.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m13 = M.dropnan.v1(
        input_data=m7.data
    )
    
    # 去极值
    def remove_extremum(df,factors):
        factor_list = factors
        for factor in factor_list:
            df[factor][df[factor] >= np.percentile(df[factor], 95)] = np.percentile(df[factor], 95)
            df[factor][df[factor] <= np.percentile(df[factor], 5)] = np.percentile(df[factor], 5)
        return df
    
    # 标准化
    def standardization(df,factors):
        factor_list = factors
        for factor in factor_list:
            df[factor] = (df[factor] - df[factor].mean()) / df[factor].std()
        return df 
    
    def deal_with_factors(df,factors):
        return standardization(remove_extremum(df,factors),factors)
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m15_run_bigquant_run(input_1, input_2, input_3):
        df = input_1.read_df()
        df.index = range(len(df))
        factors = [i for i in df.columns if i[0:2] != 'm:'and i not in ['date','instrument','label']]
        factors_df_after_deal_with = df.groupby('date').apply(deal_with_factors,factors=factors)
        factors_df_after_deal_with.reset_index(inplace=True,drop=True)
        data_1 = DataSource.write_df(factors_df_after_deal_with)
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    m15 = M.cached.v3(
        input_1=m13.data,
        run=m15_run_bigquant_run
    )
    
    m6 = M.stock_ranker_train.v5(
        training_ds=m15.data_1,
        features=m3.data,
        learning_algorithm='排序',
        number_of_leaves=30,
        minimum_docs_per_leaf=1000,
        number_of_trees=20,
        learning_rate=0.1,
        max_bins=1023,
        feature_fraction=1,
        m_lazy_run=False
    )
    
    m9 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2015-01-01'),
        end_date=T.live_run_param('trading_date', '2017-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
    )
    
    m11 = M.derived_feature_extractor.v2(
        input_data=m10.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument'
    )
    
    m14 = M.dropnan.v1(
        input_data=m11.data
    )
    
    # 去极值
    def remove_extremum(df,factors):
        factor_list = factors
        for factor in factor_list:
            df[factor][df[factor] >= np.percentile(df[factor], 95)] = np.percentile(df[factor], 95)
            df[factor][df[factor] <= np.percentile(df[factor], 5)] = np.percentile(df[factor], 5)
        return df
    
    # 标准化
    def standardization(df,factors):
        factor_list = factors
        for factor in factor_list:
            df[factor] = (df[factor] - df[factor].mean()) / df[factor].std()
        return df 
    
    def deal_with_factors(df,factors):
        return standardization(remove_extremum(df,factors),factors)
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m16_run_bigquant_run(input_1, input_2, input_3):
        df = input_1.read_df()
        df.index = range(len(df))
        factors = [i for i in df.columns if i[0:2] != 'm:'and i not in ['date','instrument','label']]
        factors_df_after_deal_with = df.groupby('date').apply(deal_with_factors,factors=factors)
        factors_df_after_deal_with.reset_index(inplace=True,drop=True)
        data_1 = DataSource.write_df(factors_df_after_deal_with)
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    m16 = M.cached.v3(
        input_1=m14.data,
        run=m16_run_bigquant_run
    )
    
    m8 = M.stock_ranker_predict.v5(
        model=m6.model,
        data=m16.data_1,
        m_lazy_run=False
    )
    
    # 回测引擎:每日数据处理函数,每天执行一次
    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.2
        context.options['hold_days'] = 5
    
    m12 = M.trade.v3(
        instruments=m9.data,
        options_data=m8.predictions,
        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-01-27 14:04:26.524336] INFO: bigquant: instruments.v2 开始运行..
    [2018-01-27 14:04:26.554369] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.555937] INFO: bigquant: instruments.v2 运行完成[0.031656s].
    [2018-01-27 14:04:26.567083] INFO: bigquant: advanced_auto_labeler.v2 开始运行..
    [2018-01-27 14:04:26.596684] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.598753] INFO: bigquant: advanced_auto_labeler.v2 运行完成[0.03171s].
    [2018-01-27 14:04:26.605174] INFO: bigquant: input_features.v1 开始运行..
    [2018-01-27 14:04:26.709470] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.711706] INFO: bigquant: input_features.v1 运行完成[0.106482s].
    [2018-01-27 14:04:26.837360] INFO: bigquant: general_feature_extractor.v6 开始运行..
    [2018-01-27 14:04:26.854879] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.856248] INFO: bigquant: general_feature_extractor.v6 运行完成[0.018963s].
    [2018-01-27 14:04:26.865062] INFO: bigquant: derived_feature_extractor.v2 开始运行..
    [2018-01-27 14:04:26.883265] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.885255] INFO: bigquant: derived_feature_extractor.v2 运行完成[0.020157s].
    [2018-01-27 14:04:26.895930] INFO: bigquant: join.v3 开始运行..
    [2018-01-27 14:04:26.912068] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.913360] INFO: bigquant: join.v3 运行完成[0.017419s].
    [2018-01-27 14:04:26.922136] INFO: bigquant: dropnan.v1 开始运行..
    [2018-01-27 14:04:26.938580] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.940385] INFO: bigquant: dropnan.v1 运行完成[0.018246s].
    [2018-01-27 14:04:26.952919] INFO: bigquant: cached.v3 开始运行..
    [2018-01-27 14:04:26.956641] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.958541] INFO: bigquant: cached.v3 运行完成[0.005611s].
    [2018-01-27 14:04:26.969051] INFO: bigquant: stock_ranker_train.v5 开始运行..
    [2018-01-27 14:04:26.973747] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.975362] INFO: bigquant: stock_ranker_train.v5 运行完成[0.00632s].
    [2018-01-27 14:04:26.982932] INFO: bigquant: instruments.v2 开始运行..
    [2018-01-27 14:04:26.994925] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:26.996216] INFO: bigquant: instruments.v2 运行完成[0.013303s].
    [2018-01-27 14:04:27.106682] INFO: bigquant: general_feature_extractor.v6 开始运行..
    [2018-01-27 14:04:27.112566] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:27.114217] INFO: bigquant: general_feature_extractor.v6 运行完成[0.007568s].
    [2018-01-27 14:04:27.123159] INFO: bigquant: derived_feature_extractor.v2 开始运行..
    [2018-01-27 14:04:27.128675] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:27.129873] INFO: bigquant: derived_feature_extractor.v2 运行完成[0.00672s].
    [2018-01-27 14:04:27.139095] INFO: bigquant: dropnan.v1 开始运行..
    [2018-01-27 14:04:27.144745] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:27.146034] INFO: bigquant: dropnan.v1 运行完成[0.006935s].
    [2018-01-27 14:04:27.158007] INFO: bigquant: cached.v3 开始运行..
    [2018-01-27 14:04:27.162531] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:27.164147] INFO: bigquant: cached.v3 运行完成[0.006138s].
    [2018-01-27 14:04:27.174632] INFO: bigquant: stock_ranker_predict.v5 开始运行..
    [2018-01-27 14:04:27.183393] INFO: bigquant: 命中缓存
    [2018-01-27 14:04:27.185056] INFO: bigquant: stock_ranker_predict.v5 运行完成[0.01044s].
    [2018-01-27 14:04:27.228832] INFO: bigquant: backtest.v7 开始运行..
    [2018-01-27 14:04:27.232046] INFO: bigquant: 命中缓存
    
    • 收益率122.23%
    • 年化收益率51.04%
    • 基准收益率-6.33%
    • 阿尔法0.55
    • 贝塔1.04
    • 夏普比率1.05
    • 胜率0.609
    • 盈亏比0.869
    • 收益波动率45.32%
    • 信息比率1.77
    • 最大回撤61.67%
    [2018-01-27 14:04:30.054527] INFO: bigquant: backtest.v7 运行完成[2.825581s].