大宽表达式因子,必须同步添加其元因子?

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

(chaoskey) #1

大宽表达式因子,必须同步添加其元因子?

下面这个策略是一个可正常运行的策略:

包括三个普通因子:

features = [
    'rank_return_20',     # 我需要的
    'pe_lyr_0',     # 我不需要的
    'fs_net_profit_yoy_0'   # 我不需要的
]

和一个表达式因子:

再计算一个衍生特征,比如 rank(return_10 / return_20)

m22 = M.derived_feature_extractor.v1(
data=m2.data,
features=[‘rank(pe_lyr_0/fs_net_profit_yoy_0)’])

目前这个策略是运行正常的。 但如果我把 下面两个两个因子屏蔽后,就会报错。

    'pe_lyr_0',     # 我不需要的
    'fs_net_profit_yoy_0'   # 我不需要的
克隆策略
In [8]:
# 基础参数配置
class conf:
    start_date = '2015-01-01'
    end_date='2017-01-01'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2016-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, split_date)

    # 机器学习目标标注函数
    # 如下标注函数等价于 min(max((持有期间的收益 * 100), -20), 20) + 20 (后面的M.fast_auto_labeler会做取整操作)
    # 说明:max/min这里将标注分数限定在区间[-20, 20],+20将分数变为非负数 (StockRanker要求标注分数非负整数)
    label_expr = ['return * 100', 'where(label > {0}, {0}, where(label < -{0}, -{0}, label)) + {0}'.format(20)]
    # 持有天数,用于计算label_expr中的return值(收益)
    hold_days = 5

    # 特征 https://bigquant.com/docs/data_features.html,你可以通过表达式构造任何特征
    features = [
        'rank_return_20',
        'pe_lyr_0',
        'fs_net_profit_yoy_0'
    ]

# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
m1 = M.fast_auto_labeler.v8(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    label_expr=conf.label_expr, hold_days=conf.hold_days,
    benchmark='000300.SHA', sell_at='open', buy_at='open')
# 计算特征数据
m2 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    features=conf.features)

# 再计算一个衍生特征,比如 rank(return_10 / return_20)
m22 = M.derived_feature_extractor.v1(
    data=m2.data,
    features=['rank(pe_lyr_0/fs_net_profit_yoy_0)'])


# 数据预处理:缺失数据处理,数据规范化,T.get_stock_ranker_default_transforms为StockRanker模型做数据预处理
m3 = M.transform.v2(
    data=m22.data, transforms=T.get_stock_ranker_default_transforms()+[('.*', None)],
    drop_null=True, astype='int32', except_columns=['date', 'instrument'],
    clip_lower=0, clip_upper=200000000)
# 合并标注和特征数据
m4 = M.join.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)
# StockRanker机器学习训练
m5 = M.stock_ranker_train.v3(training_ds=m4.data, features=conf.features)


## 量化回测 https://bigquant.com/docs/module_trade.html
# 回测引擎:准备数据,只执行一次
def prepare(context):
    # context.start_date / end_date,回测的时候,为trader传入参数;在实盘运行的时候,由系统替换为实盘日期
    n1 = M.general_feature_extractor.v5(
        instruments=D.instruments(),
        start_date=context.start_date, end_date=context.end_date,
        model_id=context.options['model_id'])
    n2 = M.transform.v2(
        data=n1.data, transforms=T.get_stock_ranker_default_transforms(),
        drop_null=True, astype='int32', except_columns=['date', 'instrument'],
        clip_lower=0, clip_upper=200000000)
    n3 = M.stock_ranker_predict.v2(model_id=context.options['model_id'], data=n2.data)
    context.instruments = n3.instruments
    context.options['predictions'] = n3.predictions

# 回测引擎:初始化函数,只执行一次
def initialize(context):
    # 加载预测数据
    context.ranker_prediction = context.options['predictions'].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

# 回测引擎:每日数据处理函数,每天执行一次
def handle_data(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天之后才开始卖出;对持仓的股票,按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)


# 调用交易引擎
m6 = M.trade.v2(
    instruments=None,
    start_date=conf.split_date,
    end_date=conf.end_date,
    prepare=prepare,
    initialize=initialize,
    handle_data=handle_data,
    order_price_field_buy='open',       # 表示 开盘 时买入
    order_price_field_sell='close',     # 表示 收盘 前卖出
    capital_base=1000000,               # 初始资金
    benchmark='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id}
)
[2017-09-26 15:15:58.307319] INFO: bigquant: fast_auto_labeler.v8 开始运行..
[2017-09-26 15:15:58.316180] INFO: bigquant: 命中缓存
[2017-09-26 15:15:58.323378] INFO: bigquant: fast_auto_labeler.v8 运行完成[0.016047s].
[2017-09-26 15:15:58.333044] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-26 15:16:15.037084] INFO: general_feature_extractor: year 2015, featurerows=569698
[2017-09-26 15:16:26.072748] INFO: general_feature_extractor: year 2016, featurerows=0
[2017-09-26 15:16:26.083910] INFO: general_feature_extractor: total feature rows: 569698
[2017-09-26 15:16:26.086901] INFO: bigquant: general_feature_extractor.v5 运行完成[27.75388s].
[2017-09-26 15:16:26.095959] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-26 15:16:26.577850] INFO: derived_feature_extractor: extracted rank(pe_lyr_0/fs_net_profit_yoy_0), 0.261s
[2017-09-26 15:16:26.732125] INFO: derived_feature_extractor: /y_2015, 569698
[2017-09-26 15:16:26.958481] INFO: bigquant: derived_feature_extractor.v1 运行完成[0.862486s].
[2017-09-26 15:16:26.969657] INFO: bigquant: transform.v2 开始运行..
[2017-09-26 15:16:28.150524] INFO: transform: transformed /y_2015, 556443/569698
[2017-09-26 15:16:28.165929] INFO: transform: transformed rows: 556443/569698
[2017-09-26 15:16:28.189679] INFO: bigquant: transform.v2 运行完成[1.219981s].
[2017-09-26 15:16:28.198119] INFO: bigquant: join.v2 开始运行..
[2017-09-26 15:16:31.441650] INFO: join: /y_2015, rows=533182/556443, timetaken=2.415624s
[2017-09-26 15:16:31.507163] INFO: join: total result rows: 533182
[2017-09-26 15:16:31.509357] INFO: bigquant: join.v2 运行完成[3.31123s].
[2017-09-26 15:16:31.519718] INFO: bigquant: stock_ranker_train.v3 开始运行..
[2017-09-26 15:16:32.051971] INFO: df2bin: prepare data: training ..
[2017-09-26 15:16:36.453709] INFO: stock_ranker_train: 9f05a586 training: 533182 rows
[2017-09-26 15:18:09.089292] INFO: bigquant: stock_ranker_train.v3 运行完成[97.569558s].
[2017-09-26 15:18:09.112730] INFO: bigquant: backtest.v7 开始运行..
[2017-09-26 15:18:09.142718] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-26 15:18:17.135467] INFO: general_feature_extractor: year 2016, featurerows=641546
[2017-09-26 15:18:27.594867] INFO: general_feature_extractor: year 2017, featurerows=0
[2017-09-26 15:18:27.604905] INFO: general_feature_extractor: total feature rows: 641546
[2017-09-26 15:18:27.607100] INFO: bigquant: general_feature_extractor.v5 运行完成[18.464373s].
[2017-09-26 15:18:27.620229] INFO: bigquant: transform.v2 开始运行..
[2017-09-26 15:18:28.792832] INFO: transform: transformed /y_2016, 636912/641546
[2017-09-26 15:18:28.806164] INFO: transform: transformed rows: 636912/641546
[2017-09-26 15:18:28.847205] INFO: bigquant: transform.v2 运行完成[1.22695s].
[2017-09-26 15:18:28.862050] INFO: bigquant: stock_ranker_predict.v2 开始运行..
[2017-09-26 15:18:29.214086] INFO: df2bin: prepare data: prediction ..
[2017-09-26 15:18:34.008828] INFO: stock_ranker_predict: prediction: 636912 rows
[2017-09-26 15:18:39.236220] INFO: bigquant: stock_ranker_predict.v2 运行完成[10.374097s].
[2017-09-26 15:19:03.708576] INFO: Performance: Simulated 244 trading days out of 244.
[2017-09-26 15:19:03.710017] INFO: Performance: first open: 2016-01-04 14:30:00+00:00
[2017-09-26 15:19:03.711353] INFO: Performance: last close: 2016-12-30 20:00:00+00:00
  • 收益率8.76%
  • 年化收益率9.06%
  • 基准收益率-11.28%
  • 阿尔法0.23
  • 贝塔1.12
  • 夏普比率0.17
  • 收益波动率34.39%
  • 信息比率0.87
  • 最大回撤18.25%
[2017-09-26 15:19:05.201241] INFO: bigquant: backtest.v7 运行完成[56.088474s].
In [ ]:
 

(iQuant) #2

你好,derived_feature_extractor 是在基础特征之上去计算衍生特征(这个模块可以对任何输入的数据做特征抽取,不限于股票等),输入的数据要求基础特征已经完成抽取。

可以参考如下代码修改,添加 general_feature_extractor

m2_1 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    features=[‘rank(pe_lyr_0/fs_net_profit_yoy_0)’])
m22 = M.derived_feature_extractor.v1(
    data=m2_1.data,
    features=[‘rank(pe_lyr_0/fs_net_profit_yoy_0)’])

我们在考虑是否再提供一个模块,可以实现基础特征和衍生特征同时抽取的。


(chaoskey) #3

完全按你的方法修改也报错(你这种方式我以前也试过),现在复现如下:

#特征 https://bigquant.com/docs/data_features.html,你可以通过表达式构造任何特征
features = [
    'rank(pe_lyr_0/fs_net_profit_yoy_0)',
]

#给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
m1 = M.fast_auto_labeler.v8(
instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
label_expr=conf.label_expr, hold_days=conf.hold_days,
benchmark=‘000300.SHA’, sell_at=‘open’, buy_at=‘open’)

#计算特征数据
m2 = M.general_feature_extractor.v5(
instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
features=conf.features)

#再计算一个衍生特征,比如 rank(return_10 / return_20)
m22 = M.derived_feature_extractor.v1(
data=m2.data,
features=conf.features)

克隆策略
In [14]:
# 基础参数配置
class conf:
    start_date = '2015-01-01'
    end_date='2017-01-01'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2016-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, split_date)

    # 机器学习目标标注函数
    # 如下标注函数等价于 min(max((持有期间的收益 * 100), -20), 20) + 20 (后面的M.fast_auto_labeler会做取整操作)
    # 说明:max/min这里将标注分数限定在区间[-20, 20],+20将分数变为非负数 (StockRanker要求标注分数非负整数)
    label_expr = ['return * 100', 'where(label > {0}, {0}, where(label < -{0}, -{0}, label)) + {0}'.format(20)]
    # 持有天数,用于计算label_expr中的return值(收益)
    hold_days = 5

    # 特征 https://bigquant.com/docs/data_features.html,你可以通过表达式构造任何特征
    features = [
        'rank(pe_lyr_0/fs_net_profit_yoy_0)',
    ]

# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
m1 = M.fast_auto_labeler.v8(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    label_expr=conf.label_expr, hold_days=conf.hold_days,
    benchmark='000300.SHA', sell_at='open', buy_at='open')

# 计算特征数据
m2 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    features=conf.features)

# 再计算一个衍生特征,比如 rank(return_10 / return_20)
m22 = M.derived_feature_extractor.v1(
    data=m2.data,
    features=conf.features)


# 数据预处理:缺失数据处理,数据规范化,T.get_stock_ranker_default_transforms为StockRanker模型做数据预处理
m3 = M.transform.v2(
    data=m22.data, transforms=T.get_stock_ranker_default_transforms()+[('.*', None)],
    drop_null=True, astype='int32', except_columns=['date', 'instrument'],
    clip_lower=0, clip_upper=200000000)

# 合并标注和特征数据
m4 = M.join.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)
# StockRanker机器学习训练
m5 = M.stock_ranker_train.v3(training_ds=m4.data, features=conf.features)


## 量化回测 https://bigquant.com/docs/module_trade.html
# 回测引擎:准备数据,只执行一次
def prepare(context):
    # context.start_date / end_date,回测的时候,为trader传入参数;在实盘运行的时候,由系统替换为实盘日期
    n1 = M.general_feature_extractor.v5(
        instruments=D.instruments(),
        start_date=context.start_date, end_date=context.end_date,
        model_id=context.options['model_id'])
    n2 = M.transform.v2(
        data=n1.data, transforms=T.get_stock_ranker_default_transforms(),
        drop_null=True, astype='int32', except_columns=['date', 'instrument'],
        clip_lower=0, clip_upper=200000000)
    n3 = M.stock_ranker_predict.v2(model_id=context.options['model_id'], data=n2.data)
    context.instruments = n3.instruments
    context.options['predictions'] = n3.predictions

# 回测引擎:初始化函数,只执行一次
def initialize(context):
    # 加载预测数据
    context.ranker_prediction = context.options['predictions'].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

# 回测引擎:每日数据处理函数,每天执行一次
def handle_data(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天之后才开始卖出;对持仓的股票,按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)


# 调用交易引擎
m6 = M.trade.v2(
    instruments=None,
    start_date=conf.split_date,
    end_date=conf.end_date,
    prepare=prepare,
    initialize=initialize,
    handle_data=handle_data,
    order_price_field_buy='open',       # 表示 开盘 时买入
    order_price_field_sell='close',     # 表示 收盘 前卖出
    capital_base=1000000,               # 初始资金
    benchmark='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id}
)
[2017-09-26 17:07:03.481278] INFO: bigquant: fast_auto_labeler.v8 开始运行..
[2017-09-26 17:07:03.516373] INFO: bigquant: 命中缓存
[2017-09-26 17:07:03.527104] INFO: bigquant: fast_auto_labeler.v8 运行完成[0.045834s].
[2017-09-26 17:07:03.539570] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-09-26 17:07:44.664052] INFO: general_feature_extractor: year 2015, featurerows=569698
[2017-09-26 17:08:25.038232] INFO: general_feature_extractor: year 2016, featurerows=0
[2017-09-26 17:08:25.081751] INFO: general_feature_extractor: total feature rows: 569698
[2017-09-26 17:08:25.091923] INFO: bigquant: general_feature_extractor.v5 运行完成[81.552354s].
[2017-09-26 17:08:25.140264] INFO: bigquant: derived_feature_extractor.v1 开始运行..
[2017-09-26 17:08:27.702037] INFO: derived_feature_extractor: extracted rank(pe_lyr_0/fs_net_profit_yoy_0), 1.706s
[2017-09-26 17:08:28.170414] INFO: derived_feature_extractor: /y_2015, 569698
[2017-09-26 17:08:28.570884] INFO: bigquant: derived_feature_extractor.v1 运行完成[3.430579s].
[2017-09-26 17:08:28.585725] INFO: bigquant: transform.v2 开始运行..
[2017-09-26 17:08:30.660529] INFO: transform: transformed /y_2015, 556447/569698
[2017-09-26 17:08:30.673055] INFO: transform: transformed rows: 556447/569698
[2017-09-26 17:08:30.710258] INFO: bigquant: transform.v2 运行完成[2.124515s].
[2017-09-26 17:08:30.814994] INFO: bigquant: join.v2 开始运行..
[2017-09-26 17:08:36.911353] INFO: join: /y_2015, rows=533186/556447, timetaken=4.84605s
[2017-09-26 17:08:37.154072] INFO: join: total result rows: 533186
[2017-09-26 17:08:37.162918] INFO: bigquant: join.v2 运行完成[6.347946s].
[2017-09-26 17:08:37.173201] INFO: bigquant: stock_ranker_train.v3 开始运行..
[2017-09-26 17:08:38.038912] INFO: df2bin: prepare data: training ..
[2017-09-26 17:08:54.865329] INFO: stock_ranker_train: 47d483c6 training: 533186 rows
Traceback (most recent call last):
  File "<string>", line 139, in _invoke_with_cache
  File "<string>", line 118, in _module_run
  File "<string>", line 104, in run
  File "<string>", line 104, in <listcomp>
  File "<string>", line 101, in in_order_to_pre_order
  File "/opt/conda/lib/python3.5/ast.py", line 245, in visit
    return visitor(node)
  File "<string>", line 11, in generic_visit
  File "/opt/conda/lib/python3.5/ast.py", line 245, in visit
    return visitor(node)
  File "<string>", line 13, in generic_visit
  File "/opt/conda/lib/python3.5/ast.py", line 245, in visit
    return visitor(node)
  File "<string>", line 69, in visit_Call
  File "<string>", line 19, in generic_visit
  File "<string>", line 50, in _generic_visit
KeyError: 'rank'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/conda/lib/python3.5/site-packages/logbook/handlers.py", line 213, in handle
    self.emit(record)
  File "/opt/conda/lib/python3.5/site-packages/logbook/handlers.py", line 840, in emit
    self.write(self.encode(msg))
  File "/opt/conda/lib/python3.5/site-packages/logbook/handlers.py", line 637, in encode
    self.ensure_stream_is_open()
  File "/opt/conda/lib/python3.5/site-packages/logbook/handlers.py", line 642, in ensure_stream_is_open
    self._open()
  File "/opt/conda/lib/python3.5/site-packages/logbook/handlers.py", line 615, in _open
    self.stream = io.open(self._filename, mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/var/app/log/biglab/ipython-20170926.log'
Logged from file <string>, line 142
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-14-da53eb7c7690> in <module>()
     45 m4 = M.join.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)
     46 # StockRanker机器学习训练
---> 47 m5 = M.stock_ranker_train.v3(training_ds=m4.data, features=conf.features)
     48 
     49 

KeyError: 'rank'
In [ ]:
 

(iQuant) #4

为了 1. 让系统策略,即使以前开发的策略也能长期稳定运行,2. 不断的优化和增加新功能,我们对模块做了版本管理。强烈建议使用可视化的界面开发策略(如下所示)。这里可以看到当前活跃的版本。

使用帮助

克隆策略

    {"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-43:training_ds","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-84:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","SourceOutputPortId":"-86:data"}],"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":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[],"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":"start_date","Value":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"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":"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# 多个特征,每行一个,可以包含基础特征和衍生特征\nrank(pe_lyr_0/fs_net_profit_yoy_0)\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[],"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":"2010-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2015-01-01","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}],"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}],"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":[],"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}],"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":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[],"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":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2017-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"}],"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":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2017-01-01","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天之后才开始卖出;对持仓的股票,按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.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":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","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}],"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='638,561,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='906,647,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='376,467,200,200'/><NodePosition Node='-86' Position='1078,418,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":false}
    In [1]:
    # 本代码由可视化策略环境自动生成 2017年9月26日 18:13
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date='2010-01-01',
        end_date='2015-01-01',
        market='CN_STOCK_A',
        max_count=0
    )
    
    m2 = M.advanced_auto_labeler.v2(
        instruments=m1.data,
        start_date='2010-01-01',
        end_date='2015-01-01',
        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)
    """,
        benchmark='000300.SHA',
        drop_na_label=True,
        cast_label_int=True
    )
    
    m3 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    rank(pe_lyr_0/fs_net_profit_yoy_0)
    """
    )
    
    m4 = M.general_feature_extractor.v6(
        instruments=m1.data,
        features=m3.data,
        start_date='2010-01-01',
        end_date='2015-01-01'
    )
    
    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
    )
    
    m6 = M.stock_ranker_train.v5(
        training_ds=m13.data,
        features=m3.data,
        learning_algorithm='排序',
        number_of_leaves=30,
        minimum_docs_per_leaf=1000,
        number_of_trees=20,
        learning_rate=0.1,
        max_bins=1023,
        feature_fraction=1
    )
    
    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',
        max_count=0
    )
    
    m10 = M.general_feature_extractor.v6(
        instruments=m9.data,
        features=m3.data,
        start_date=T.live_run_param('trading_date', '2015-01-01'),
        end_date=T.live_run_param('trading_date', '2017-01-01')
    )
    
    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
    )
    
    m8 = M.stock_ranker_predict.v5(
        model=m6.model,
        data=m14.data
    )
    
    # 回测引擎:每日数据处理函数,每天执行一次
    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天之后才开始卖出;对持仓的股票,按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 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='2015-01-01',
        end_date='2017-01-01',
        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',
        plot_charts=True,
        backtest_only=False
    )
    
    [2017-09-26 18:07:11.494827] INFO: bigquant: instruments.v2 开始运行..
    [2017-09-26 18:07:11.501464] INFO: bigquant: 命中缓存
    [2017-09-26 18:07:11.502825] INFO: bigquant: instruments.v2 运行完成[0.008037s].
    [2017-09-26 18:07:11.581636] INFO: bigquant: advanced_auto_labeler.v2 开始运行..
    [2017-09-26 18:07:11.585140] INFO: bigquant: 命中缓存
    [2017-09-26 18:07:11.586448] INFO: bigquant: advanced_auto_labeler.v2 运行完成[0.004857s].
    [2017-09-26 18:07:11.597107] INFO: bigquant: input_features.v1 开始运行..
    [2017-09-26 18:07:11.604884] INFO: bigquant: input_features.v1 运行完成[0.007782s].
    [2017-09-26 18:07:11.625664] INFO: bigquant: general_feature_extractor.v6 开始运行..
    [2017-09-26 18:07:17.206832] INFO: general_feature_extractor: 年份 2010, 特征行数=431567
    [2017-09-26 18:07:30.094665] INFO: general_feature_extractor: 年份 2011, 特征行数=511455
    [2017-09-26 18:07:53.140128] INFO: general_feature_extractor: 年份 2012, 特征行数=565675
    [2017-09-26 18:08:09.774155] INFO: general_feature_extractor: 年份 2013, 特征行数=564168
    [2017-09-26 18:08:29.275260] INFO: general_feature_extractor: 年份 2014, 特征行数=569948
    [2017-09-26 18:08:36.669216] INFO: general_feature_extractor: 年份 2015, 特征行数=0
    [2017-09-26 18:08:36.690212] INFO: general_feature_extractor: 总行数: 2642813
    [2017-09-26 18:08:36.692765] INFO: bigquant: general_feature_extractor.v6 运行完成[85.067087s].
    [2017-09-26 18:08:36.706252] INFO: bigquant: derived_feature_extractor.v2 开始运行..
    [2017-09-26 18:08:42.103597] INFO: derived_feature_extractor: 提取完成 rank(pe_lyr_0/fs_net_profit_yoy_0), 3.597s
    [2017-09-26 18:08:42.253587] INFO: derived_feature_extractor: /y_2010, 431567
    [2017-09-26 18:08:42.562979] INFO: derived_feature_extractor: /y_2011, 511455
    [2017-09-26 18:08:42.916170] INFO: derived_feature_extractor: /y_2012, 565675
    [2017-09-26 18:08:43.298023] INFO: derived_feature_extractor: /y_2013, 564168
    [2017-09-26 18:08:43.656962] INFO: derived_feature_extractor: /y_2014, 569948
    [2017-09-26 18:08:44.108581] INFO: bigquant: derived_feature_extractor.v2 运行完成[7.402264s].
    [2017-09-26 18:08:44.125957] INFO: bigquant: join.v3 开始运行..
    [2017-09-26 18:08:50.720554] INFO: join: /y_2010, 行数=431028/431567, 耗时=3.854061s
    [2017-09-26 18:08:54.946333] INFO: join: /y_2011, 行数=510922/511455, 耗时=4.209981s
    [2017-09-26 18:09:00.344359] INFO: join: /y_2012, 行数=564582/565675, 耗时=5.379671s
    [2017-09-26 18:09:04.244544] INFO: join: /y_2013, 行数=563132/564168, 耗时=3.867689s
    [2017-09-26 18:09:07.937808] INFO: join: /y_2014, 行数=555191/569948, 耗时=3.668596s
    [2017-09-26 18:09:08.051215] INFO: join: 最终行数: 2624855
    [2017-09-26 18:09:08.053177] INFO: bigquant: join.v3 运行完成[23.927245s].
    [2017-09-26 18:09:08.066167] INFO: bigquant: dropnan.v1 开始运行..
    [2017-09-26 18:09:08.516797] INFO: dropnan: /y_2010, 411411/431028
    [2017-09-26 18:09:09.023930] INFO: dropnan: /y_2011, 493229/510922
    [2017-09-26 18:09:09.640425] INFO: dropnan: /y_2012, 554146/564582
    [2017-09-26 18:09:10.563598] INFO: dropnan: /y_2013, 562783/563132
    [2017-09-26 18:09:11.259709] INFO: dropnan: /y_2014, 550373/555191
    [2017-09-26 18:09:11.291511] INFO: dropnan: 行数: 2571942/2624855
    [2017-09-26 18:09:11.319539] INFO: bigquant: dropnan.v1 运行完成[3.253342s].
    [2017-09-26 18:09:11.336665] INFO: bigquant: stock_ranker_train.v5 开始运行..
    [2017-09-26 18:09:14.061759] INFO: df2bin: prepare bins ..
    [2017-09-26 18:09:14.371035] INFO: df2bin: prepare data: training ..
    [2017-09-26 18:09:14.788738] INFO: df2bin: sort ..
    [2017-09-26 18:09:36.251206] INFO: stock_ranker_train: bdf45dda 准备训练: 2571942 行数
    [2017-09-26 18:11:28.086176] INFO: bigquant: stock_ranker_train.v5 运行完成[136.749503s].
    [2017-09-26 18:11:28.093050] INFO: bigquant: instruments.v2 开始运行..
    [2017-09-26 18:11:28.096237] INFO: bigquant: 命中缓存
    [2017-09-26 18:11:28.097600] INFO: bigquant: instruments.v2 运行完成[0.004543s].
    [2017-09-26 18:11:28.105992] INFO: bigquant: general_feature_extractor.v6 开始运行..
    [2017-09-26 18:11:31.218980] INFO: general_feature_extractor: 年份 2015, 特征行数=569698
    [2017-09-26 18:11:37.110489] INFO: general_feature_extractor: 年份 2016, 特征行数=641546
    [2017-09-26 18:11:39.732250] INFO: general_feature_extractor: 年份 2017, 特征行数=0
    [2017-09-26 18:11:39.750097] INFO: general_feature_extractor: 总行数: 1211244
    [2017-09-26 18:11:39.752052] INFO: bigquant: general_feature_extractor.v6 运行完成[11.646221s].
    [2017-09-26 18:11:39.760318] INFO: bigquant: derived_feature_extractor.v2 开始运行..
    [2017-09-26 18:11:41.111245] INFO: derived_feature_extractor: 提取完成 rank(pe_lyr_0/fs_net_profit_yoy_0), 0.809s
    [2017-09-26 18:11:41.242973] INFO: derived_feature_extractor: /y_2015, 569698
    [2017-09-26 18:11:41.809578] INFO: derived_feature_extractor: /y_2016, 641546
    [2017-09-26 18:11:42.432906] INFO: bigquant: derived_feature_extractor.v2 运行完成[2.672535s].
    [2017-09-26 18:11:42.440987] INFO: bigquant: dropnan.v1 开始运行..
    [2017-09-26 18:11:43.118932] INFO: dropnan: /y_2015, 556447/569698
    [2017-09-26 18:11:43.641711] INFO: dropnan: /y_2016, 630884/641546
    [2017-09-26 18:11:43.662468] INFO: dropnan: 行数: 1187331/1211244
    [2017-09-26 18:11:43.685774] INFO: bigquant: dropnan.v1 运行完成[1.244771s].
    [2017-09-26 18:11:43.703067] INFO: bigquant: stock_ranker_predict.v5 开始运行..
    [2017-09-26 18:11:44.290188] INFO: df2bin: prepare data: prediction ..
    [2017-09-26 18:11:52.510454] INFO: stock_ranker_predict: 准备预测: 1187331 行
    [2017-09-26 18:12:01.388412] INFO: bigquant: stock_ranker_predict.v5 运行完成[17.685336s].
    [2017-09-26 18:12:01.470803] INFO: bigquant: backtest.v7 开始运行..
    [2017-09-26 18:12:41.241210] INFO: Performance: Simulated 488 trading days out of 488.
    [2017-09-26 18:12:41.243215] INFO: Performance: first open: 2015-01-05 14:30:00+00:00
    [2017-09-26 18:12:41.246013] INFO: Performance: last close: 2016-12-30 20:00:00+00:00
    
    • 收益率92.11%
    • 年化收益率40.1%
    • 基准收益率-6.33%
    • 阿尔法0.43
    • 贝塔1.01
    • 夏普比率0.92
    • 收益波动率39.76%
    • 信息比率1.86
    • 最大回撤54.11%
    [2017-09-26 18:12:43.444627] INFO: bigquant: backtest.v7 运行完成[41.973767s].
    

    (copen) #5

    看出错的代码提示,可以猜测是M.stock_ranker_train版本太旧的原因。


    (chaoskey) #6

    在你的提示下搞定了。 虽然可视化策略我也用过(的确好用),但有时为了快速验证想法,我用的是老的策略向导(快速建立模版,然后手工修改)。 看来我还要习惯优先用可视化策略。

    谢谢你们细心的指导。


    (chaoskey) #7

    你说的对,版本太老,应该用v5 。谢谢你的回复。