【宽客学院】回测数据深入分析

回测机制
回测数据
宽客学院
标签: #<Tag:0x00007f5bff430ed8> #<Tag:0x00007f5bff430d48> #<Tag:0x00007f5bff430b18>

(iQuant) #1
作者:bigquant
阅读时间:15分钟
本文由BigQuant宽客学院推出,难度标签:☆☆☆☆

导语:本文介绍如何对一个回测结果进行深入分析。

1.策略完整代码

我们先看一个AI策略,以下是完整的策略代码。

克隆策略
In [42]:
# 基础参数配置
class conf:
    start_date = '2014-01-01'
    end_date='2017-08-01'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2016-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, split_date)
    # 持有天数,用于计算label_expr中的return值(收益)
    hold_days = 120
    label_expr = ['return * 100/%s'%(np.sqrt(hold_days/3)), 'where(label > {0}, {0}, where(label < -{0}, -{0}, label)) + {0}'.format(10)]
    # 特征 https://bigquant.com/docs/data_features.html,你可以通过表达式构造任何特征
    features = ['rank_pb_lf_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)
# 数据预处理:缺失数据处理,数据规范化,T.get_stock_ranker_default_transforms为StockRanker模型做数据预处理
m3 = M.transform.v2(
    data=m2.data, transforms=T.get_stock_ranker_default_transforms(),
    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.portfolio.positions.items()}

    # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰
    if not is_staging and cash_for_sell > 0:
        equities = {e.symbol: e for e, p in context.portfolio.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',             # 比较基准,不影响回测结果
    volume_limit=0,
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id}
)
[2017-08-07 10:03:14.243168] INFO: bigquant: fast_auto_labeler.v8 start ..
[2017-08-07 10:03:14.245613] INFO: bigquant: hit cache
[2017-08-07 10:03:14.249525] INFO: bigquant: fast_auto_labeler.v8 end [0.006376s].
[2017-08-07 10:03:14.254888] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-08-07 10:03:14.256411] INFO: bigquant: hit cache
[2017-08-07 10:03:14.257181] INFO: bigquant: general_feature_extractor.v5 end [0.002295s].
[2017-08-07 10:03:14.265135] INFO: bigquant: transform.v2 start ..
[2017-08-07 10:03:14.266623] INFO: bigquant: hit cache
[2017-08-07 10:03:14.267659] INFO: bigquant: transform.v2 end [0.002515s].
[2017-08-07 10:03:14.273329] INFO: bigquant: join.v2 start ..
[2017-08-07 10:03:14.274966] INFO: bigquant: hit cache
[2017-08-07 10:03:14.275712] INFO: bigquant: join.v2 end [0.002384s].
[2017-08-07 10:03:14.282638] INFO: bigquant: stock_ranker_train.v3 start ..
[2017-08-07 10:03:14.284196] INFO: bigquant: hit cache
[2017-08-07 10:03:14.284958] INFO: bigquant: stock_ranker_train.v3 end [0.002331s].
[2017-08-07 10:03:14.302182] INFO: bigquant: backtest.v7 start ..
[2017-08-07 10:03:14.303801] INFO: bigquant: hit cache
  • 收益率43.82%
  • 年化收益率26.85%
  • 基准收益率1.06%
  • 阿尔法0.24
  • 贝塔0.32
  • 夏普比率2.07
  • 收益波动率10.82%
  • 信息比率1.68
  • 最大回撤9.63%
[2017-08-07 10:03:15.411851] INFO: bigquant: backtest.v7 end [1.109634s].

2. 回测结果

回测结果一般指策略运行完毕之后输出的能够综合反映策略效果的综合图表,如下所示:

可以看出,回测结果包括收益概括、交易详情、每日持仓、输出日志。

对回测结果进行深入分析需要一定的基础知识,如下:

回测结果的简单解读参考第三点即可,本文主要介绍怎样对回测数据进行深入分析以验证回测结果。

3.读取回测详细数据

示例代码:

m6.raw_perf.read_df()

输出结果:

回测详细数据全部保存在m6.raw_perf对象中,为DataSource类型,因此需要使用read_df方法读取数据。该数据为时间序列数据,按交易日记录了详细信息,主要包括三块数据:

  • 策略相关,比如策略收益率、策略收益波动率、阿尔法、贝塔、夏普比率、信息比率、索提纳比率、基准收益率、基准收益波动率。
  • 交易相关。每日账户权益、每日持仓详情、订单、交易成本、交易时间段。
  • 起始资金、最终资金、每日盈亏、多头(空头)市值、多头(空头)风险暴露。

在策略回测结果图上,所有数据都是来自回测详细数据。

4.回测数据深入分析技巧

  • 检查策略杠杆是否正常

因为回测机制允许融资交易,当持仓市值超过总资金时借用资金杠杆,此时杠杆比率大于1,一方面可以通过 m6.raw_perf.read_df()[‘gross_leverage’] 查询,一方面可以观察回测结果图。

在上图中,下方的绿色曲线表示策略的杠杆比率,可以看出杠杆比率几乎都是小于1,表明没有借用资金杠杆,同时看出,杠杆比率在前期缓慢提高,这正是策略开始在建仓期间不断买入股票没有卖出直接相关。

  • 抽样检查买入股票是否正确
    通过回测结果查询的实际成交情况:
    image
    通过测试集预测结果验证买入股票:
    image
    因为是当日收盘以后,才能预测出下个交易日的股票排序,因此测试集预测结果当日的股票排序应该和下一个交易日的买入股票相对应。通过上面两图的对比,抽样检查买入股票是正确的。

  • 抽样检查买入价格是否是正确

通过交易详情,我们可以知道每只股票的买入价格,因此我们抽样验证股票买入价格,检查是否存在夸大策略收益的情形。我们先看2016-01-05买入的几只股票的买入价。

通过数据API单独获取数据检验成交价格,之所以获取开盘价,是因为股票成交策略回测假设是开盘买入。

通过两图的对比,我们发现成交价格是正确的,回测过程中并没有偷价漏价的情形。

  • 检查每只股票的成交金额是否正确

之所以检查成交金额,实际上是检查每只股票的仓位资金配置是否和策略的资金配置思想相一致。我们先看2016-01-05买入的5只股票的成交情况。


可以看出,当日买入股票的资金配置按高到低依次是:000155.SZA、600301.SHA、600179.SHA、000815.SZA、600678.SHA。
我们再看看,在测试集上当天的股票买入顺序是怎样的。

image

股票的买入顺序是根据股票得分(score)排序所得,得分高的股票优先买入,买入的仓位也会较大。从测试集上的股票排序顺序来看,和回测交给交易详情是对应的,之所以600301.SHA和600179.SHA顺序略有差异这是因为测试集上股票得分相等。

  • 检查手续费计算是否正确
    手续费对策略收益率具有直接影响,如果交易频繁,持仓时间短,手续费设置不合理将会高估策略收益。因此需要对交易手续费进行检查。我们先看2016-01-05实际买入手续费。

在策略设置(initialize函数)中,策略手续费设置如下:

 context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))

可以看出,买入股票交易费用为成交金额的万分之三,不足5元按5元收取。在2016-01-05买入的股票中,成交金额最大的股票为000155.SZA,成交金额为2685元,按照万三的手续费计算,手续费才0.8元。不足5元按五元收取,因此在手续费这块,回测试没有问题的。

  • 抽样检查卖出股票是否正确以及卖出价格

卖出股票的股票核对以及卖出价格是否合理的检查这里不做介绍,同上述买入股票及买入价格是一样的方法。

  • 通过代码查看回测细节

查看回测细节不仅可以通过回测结果点击可视化查询,还可以通过代码查询,查询的数据将会更加详细、深入,因为所有结果都是在m6.raw_perf.read_df()中,所以通过该函数就可以知道全部回测细节。点击下方 “点击查看代码”通过代码运行来查看回测细节。

点击查看代码
perf = m6.raw_perf.read_df()
period_data = perf['2016-02-01': '2016-02-15']
print(period_data.columns)
days = period_data.shape[0]
for i in range(days):
    cd = period_data.ix[i]
    dt = cd['period_open'] # 日期
    starting_cash = cd['starting_cash'] # 开始现金
    ending_cash = cd['ending_cash'] # 结束现金
    portfolio_value = cd['portfolio_value'] # 权益值
    gross_leverage = cd['gross_leverage'] # 杠杆
    print("{}".format(dt))
    # 持仓
    positions = cd['positions']
    positions_str = ''
    for p in positions:
        positions_str += '    '+"{}/{}/{}/{},".format(p['sid'].symbol, p['amount'], p['last_sale_price'],p['cost_basis'])
    print("positions: {}".format(positions_str))
    # 订单
    orders = cd['orders']
    orders_str = ''
    for o in orders:
        if o['status'] != 0:
            continue 
        orders_str += "{}/{}/{}/{},".format(o['sid'].symbol, o['amount'], o['filled'], o['commission'])
    print("orders: {}".format(orders_str))
    # 成交
    transactions = cd['transactions']
    transactions_str = ''
    for t in transactions:
        transactions_str += "{}/{}/{},".format(t['sid'].symbol, t['amount'], round(t['price'], 2))
    print("transactions: {}".format(transactions_str))
    print("\n") # 换行

输出结果为一个时间段上的每日持仓、每日订单、每日交易三个详细的信息,通过每日订单还能查询每个订单的具体成交结果,包括订单是否完全成交、是否有未成交订单、是否有遇到涨跌停、停牌情形无法成交订单。输出详情点击 “点击查看图片”。

点击查看图片

5.可视化策略的回测数据分析

上述案例是采用代码模式的策略模板,可视化的等效策略如下,与自动生成的模板不同,这里修改了自动标注模块的相关代码:

克隆策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"DestinationInputPortId":"-201: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-43:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-201:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-208:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-215:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-222:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24: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-81:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-215:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62: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"},{"DestinationInputPortId":"-208:input_data","SourceOutputPortId":"-201:data"},{"DestinationInputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","SourceOutputPortId":"-208:data"},{"DestinationInputPortId":"-222:input_data","SourceOutputPortId":"-215:data"},{"DestinationInputPortId":"-86:input_data","SourceOutputPortId":"-222:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2014-01-01","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-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日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\n100*(shift(close, -121) / shift(open, -1)-1)/sqrt(40)\n\n# 极值处理:用1%和99%分位的值做clip\n#clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\nclip(label, -10, 10)\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# 多个特征,每行一个,可以包含基础特征和衍生特征\nrank_pb_lf_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-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":"2016-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2017-08-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-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'] = 120\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":"-201","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-201"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-201"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-201","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":15,"Comment":"","CommentCollapsed":true},{"Id":"-208","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-208"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-208"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-208","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":16,"Comment":"","CommentCollapsed":true},{"Id":"-215","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-215"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-215"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-215","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":17,"Comment":"","CommentCollapsed":true},{"Id":"-222","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-222"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-222"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-222","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":18,"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,181.11386108398438,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='765,21,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,125.11386108398438,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'/><NodePosition Node='-201' Position='381,188,200,200'/><NodePosition Node='-208' Position='385,280,200,200'/><NodePosition Node='-215' Position='1078,236,200,200'/><NodePosition Node='-222' Position='1081,327,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 [2]:
    # 本代码由可视化策略环境自动生成 2018年7月26日 14:02
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    m1 = M.instruments.v2(
        start_date='2014-01-01',
        end_date='2016-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日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    100*(shift(close, -121) / shift(open, -1)-1)/sqrt(40)
    
    # 极值处理:用1%和99%分位的值做clip
    #clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
    clip(label, -10, 10)
    # 将分数映射到分类,这里使用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="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    rank_pb_lf_0
    """
    )
    
    m15 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m16 = M.derived_feature_extractor.v3(
        input_data=m15.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument'
    )
    
    m7 = M.join.v3(
        data1=m2.data,
        data2=m16.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,
        m_lazy_run=False
    )
    
    m9 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2016-01-01'),
        end_date=T.live_run_param('trading_date', '2017-08-01'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m17 = M.general_feature_extractor.v7(
        instruments=m9.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m18 = M.derived_feature_extractor.v3(
        input_data=m17.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument'
    )
    
    m14 = M.dropnan.v1(
        input_data=m18.data
    )
    
    m8 = M.stock_ranker_predict.v5(
        model=m6.model,
        data=m14.data,
        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'] = 120
    
    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-07-26 11:49:46.227051] INFO: bigquant: instruments.v2 开始运行..
    [2018-07-26 11:49:46.231773] INFO: bigquant: 命中缓存
    [2018-07-26 11:49:46.232690] INFO: bigquant: instruments.v2 运行完成[0.005654s].
    [2018-07-26 11:49:46.235535] INFO: bigquant: advanced_auto_labeler.v2 开始运行..
    [2018-07-26 11:49:47.681719] INFO: 自动数据标注: 加载历史数据: 1139646 行
    [2018-07-26 11:49:47.684035] INFO: 自动数据标注: 开始标注 ..
    [2018-07-26 11:49:50.013340] INFO: bigquant: advanced_auto_labeler.v2 运行完成[3.777763s].
    [2018-07-26 11:49:50.016686] INFO: bigquant: input_features.v1 开始运行..
    [2018-07-26 11:49:50.027137] INFO: bigquant: 命中缓存
    [2018-07-26 11:49:50.030390] INFO: bigquant: input_features.v1 运行完成[0.013695s].
    [2018-07-26 11:49:50.039416] INFO: bigquant: general_feature_extractor.v7 开始运行..
    [2018-07-26 11:49:50.044288] INFO: bigquant: 命中缓存
    [2018-07-26 11:49:50.045840] INFO: bigquant: general_feature_extractor.v7 运行完成[0.006449s].
    [2018-07-26 11:49:50.048461] INFO: bigquant: derived_feature_extractor.v3 开始运行..
    [2018-07-26 11:49:50.052632] INFO: bigquant: 命中缓存
    [2018-07-26 11:49:50.053912] INFO: bigquant: derived_feature_extractor.v3 运行完成[0.005443s].
    [2018-07-26 11:49:50.059752] INFO: bigquant: join.v3 开始运行..
    [2018-07-26 11:49:51.863879] INFO: join: /y_2014, 行数=563845/569948, 耗时=1.564419s
    [2018-07-26 11:49:52.887211] INFO: join: /y_2015, 行数=233213/569698, 耗时=0.998069s
    [2018-07-26 11:49:52.972840] INFO: join: 最终行数: 797058
    [2018-07-26 11:49:52.978455] INFO: bigquant: join.v3 运行完成[2.918685s].
    [2018-07-26 11:49:52.981757] INFO: bigquant: dropnan.v1 开始运行..
    [2018-07-26 11:49:53.728362] INFO: dropnan: /y_2014, 563845/563845
    [2018-07-26 11:49:54.039690] INFO: dropnan: /y_2015, 233213/233213
    [2018-07-26 11:49:54.058978] INFO: dropnan: 行数: 797058/797058
    [2018-07-26 11:49:54.072220] INFO: bigquant: dropnan.v1 运行完成[1.090413s].
    [2018-07-26 11:49:54.078014] INFO: bigquant: stock_ranker_train.v5 开始运行..
    [2018-07-26 11:49:54.491338] INFO: df2bin: prepare bins ..
    [2018-07-26 11:49:54.588338] INFO: df2bin: prepare data: training ..
    [2018-07-26 11:49:54.708270] INFO: df2bin: sort ..
    [2018-07-26 11:50:04.166647] INFO: stock_ranker_train: f4bebfe0 准备训练: 797058 行数
    [2018-07-26 11:51:16.624481] INFO: bigquant: stock_ranker_train.v5 运行完成[82.546468s].
    [2018-07-26 11:51:16.631814] INFO: bigquant: instruments.v2 开始运行..
    [2018-07-26 11:51:16.646423] INFO: bigquant: 命中缓存
    [2018-07-26 11:51:16.648158] INFO: bigquant: instruments.v2 运行完成[0.016343s].
    [2018-07-26 11:51:16.656513] INFO: bigquant: general_feature_extractor.v7 开始运行..
    [2018-07-26 11:51:16.664159] INFO: bigquant: 命中缓存
    [2018-07-26 11:51:16.665323] INFO: bigquant: general_feature_extractor.v7 运行完成[0.008815s].
    [2018-07-26 11:51:16.668258] INFO: bigquant: derived_feature_extractor.v3 开始运行..
    [2018-07-26 11:51:16.678310] INFO: bigquant: 命中缓存
    [2018-07-26 11:51:16.679752] INFO: bigquant: derived_feature_extractor.v3 运行完成[0.011498s].
    [2018-07-26 11:51:16.683231] INFO: bigquant: dropnan.v1 开始运行..
    [2018-07-26 11:51:16.691877] INFO: bigquant: 命中缓存
    [2018-07-26 11:51:16.693402] INFO: bigquant: dropnan.v1 运行完成[0.010169s].
    [2018-07-26 11:51:16.696509] INFO: bigquant: stock_ranker_predict.v5 开始运行..
    [2018-07-26 11:51:17.159643] INFO: df2bin: prepare data: prediction ..
    [2018-07-26 11:51:29.500987] INFO: stock_ranker_predict: 准备预测: 1057299 行
    [2018-07-26 11:51:36.213344] INFO: bigquant: stock_ranker_predict.v5 运行完成[19.516782s].
    [2018-07-26 11:51:36.233556] INFO: bigquant: backtest.v7 开始运行..
    [2018-07-26 11:51:36.240716] INFO: bigquant: biglearning backtest:V7.1.2
    [2018-07-26 11:52:02.711921] INFO: algo: TradingAlgorithm V1.2.1
    [2018-07-26 11:52:46.104652] INFO: Performance: Simulated 385 trading days out of 385.
    [2018-07-26 11:52:46.107699] INFO: Performance: first open: 2016-01-04 09:30:00+00:00
    [2018-07-26 11:52:46.109400] INFO: Performance: last close: 2017-08-01 15:00:00+00:00
    
    • 收益率46.43%
    • 年化收益率28.36%
    • 基准收益率1.06%
    • 阿尔法0.23
    • 贝塔0.31
    • 夏普比率2.16
    • 胜率0.82
    • 盈亏比2.34
    • 收益波动率10.43%
    • 信息比率0.09
    • 最大回撤8.74%
    [2018-07-26 11:52:49.274400] INFO: bigquant: backtest.v7 运行完成[73.040846s].
    

    而对应的结果读取方式变为:

    m12.raw_perf.read_df()
    

    预测结果的读取方式变为:

    m8.predictions.read_df()
    

    小结: 本文为大家提供分析回测数据时的几个技巧,帮助大家对回测数据有更加深刻的认识,让大家在对回测数据进行深入分析时有迹可循。


       本文由BigQuant宽客学院推出,版权归BigQuant所有,转载请注明出处。
    


    【宽客学院】策略止盈止损
    (xuqiang) #2

    一些不懂和觉得奇怪的地方,望给予解答,万分感谢
    1.关于系统默认的滑点,是VolumeShareSlippage 和FixedSlippage中的哪个,参数是多少呢?


    (xuqiang) #4

    thx :)


    (Beatricean) #5

    回测功能力在哪我没看到


    (qxxxq) #6

    ‘return * 100/%s’%(np.sqrt(hold_days/3)), 这个标记是什么意思,是否能解答下,特别是/%‘%这里。谢谢。


    (小Q) #7

    根据股票未来一段时间收益率的调整值,对数据进行标注。

    %s  是python编程语言的一个用法,用来格式化字符串
    
    比如'hello ,I am   %s!what is your name.'%'xiaoq'
    输出结果就是:
    》》》   hello, I am xiaoq! what is your name.
    

    (lytk02) #8

    如何获取夏普比率的具体值啊


    (iQuant) #9

    m6.raw_perf.read_df() 可以获取回测数据,包括策略各项指标。

    可以看出,有一列数据为sharpe就是记录夏普值。


    (lytk02) #10


    这个图片中的一行数据应该怎么获取啊


    (lytk02) #11

    按照你的方法,我得到的是每一天的夏普比率,我如何获取总体回测的夏普比率啊


    (iQuant) #12

    总体的数据其实就是最后一行的数据(最近的一个交易日的数据)


    (lytk02) #13

    ok,谢谢


    (ypf007) #14

    你好,我想把交易详情和持仓收益的所有信息都以.csv格式导出,这个该怎么导出呢


    (demonzyx) #15

    我怎么能把基准改成自己的策略呢?


    (大胡子) #16
    df = m6.raw_perf.read_df()
    df.to_csv('result.csv')
    

    然后,你可以在目录下找到 result.csv这个文件,右键下载即可


    (iQuant) #17

    目前基准设置为指数或者股票,默认是沪深300指数,如果是想策略之间进行比较的话,建议在同一个基准下进行比较。


    (mazl) #18

    score是什么?怎么计算的?谢谢


    (iQuant) #19

    参考学院这篇文章,根据plot_model各分支的决策得分综合得到
    https://community.bigquant.com/t/【宽客学院】StockRanker结果解读/1084


    (mazl) #20

    还是不太懂啊,文章里并未告诉具体这个score怎么算的~