使用bigexpr表达式引擎开发AI策略

策略分享
标签: #<Tag:0x00007f73e37fe550>

(小马哥) #1

最近BigQuant开始支持表达式引擎构建因子了,策略开发速度更快、也更加灵活了。但策略代码和之前策略生成器的模板有些差异,虽然策略效果不太好,不过终于可以正常运行了。欢迎拍砖!

克隆策略

基础参数配置

In [11]:
class conf:
    start_date = '2014-01-01'
    end_date='2017-07-17'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2015-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, end_date)

    hold_days = 30
    
    # 因子,这里可以通过表达式构建因子,参考bigexpr:https://bigquant.com/docs/big_expr.html
    features = [ 'pb_lf_0',
                'shift(amount_0,2)/amount_0',  
                  ]
    
    # 标注
    label_expr = [
        
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    'shift(close, -30) / 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)'
    ]
    

策略函数定义

In [12]:
## 量化回测 https://bigquant.com/docs/module_trade.html
# 回测引擎:准备数据,只执行一次
def prepare(context):
    # context.start_date / end_date,回测的时候,为trader传入参数;在实盘运行的时候,由系统替换为实盘日期
    instruments = D.instruments()
    ## 在样本外数据上进行预测
    n0 = M.general_feature_extractor.v5(
        instruments=D.instruments(),
        start_date=context.start_date, end_date=context.end_date,
        features=conf.features)
    n1 = M.derived_feature_extractor.v1(
        data=n0.data,
        features= conf.features)
    n2 = M.transform.v2(data=n1.data, transforms=None, drop_null=True)
    n3 = M.stock_ranker_predict.v4(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 = 3
    # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[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)

模型训练

In [13]:
# 标注
m1 = M.advanced_auto_labeler.v1(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    label_expr=conf.label_expr, benchmark='000300.SHA', cast_label_int=True)           
            
# 抽取基础特征           
m2_1 = M.general_feature_extractor.v5(
        instruments=D.instruments(),
        start_date=conf.start_date, end_date=conf.split_date,
        features=conf.features)

# 抽取衍生特征 
m2_2 = M.derived_feature_extractor.v1(
        data=m2_1.data,
        features= conf.features)
# 特征转换
m3 = M.transform.v2(data=m2_2.data, transforms=None, drop_null=True)

# 合并标注和特征数据
m4 = M.join.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)

# 开始训练模型
m5 = M.stock_ranker_train.v4(training_ds=m4.data, features=conf.features)
[2017-08-25 18:21:33.510224] INFO: bigquant: advanced_auto_labeler.v1 start ..
[2017-08-25 18:21:33.512511] INFO: bigquant: hit cache
[2017-08-25 18:21:33.513352] INFO: bigquant: advanced_auto_labeler.v1 end [0.003185s].
[2017-08-25 18:21:33.537452] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-08-25 18:21:37.207015] INFO: general_feature_extractor: year 2014, featurerows=569948
[2017-08-25 18:21:40.586801] INFO: general_feature_extractor: year 2015, featurerows=0
[2017-08-25 18:21:40.599205] INFO: general_feature_extractor: total feature rows: 569948
[2017-08-25 18:21:40.601114] INFO: bigquant: general_feature_extractor.v5 end [7.063695s].
[2017-08-25 18:21:40.608866] INFO: bigquant: derived_feature_extractor.v1 start ..
[2017-08-25 18:21:40.851720] INFO: derived_feature_extractor: extracted shift(amount_0,2)/amount_0, 0.094s
[2017-08-25 18:21:40.991350] INFO: derived_feature_extractor: /y_2014, 569948
[2017-08-25 18:21:41.329435] INFO: bigquant: derived_feature_extractor.v1 end [0.720535s].
[2017-08-25 18:21:41.337474] INFO: bigquant: transform.v2 start ..
[2017-08-25 18:21:41.773802] INFO: transform: transformed /y_2014, 564769/569948
[2017-08-25 18:21:41.787112] INFO: transform: transformed rows: 564769/569948
[2017-08-25 18:21:41.807379] INFO: bigquant: transform.v2 end [0.469898s].
[2017-08-25 18:21:41.814391] INFO: bigquant: join.v2 start ..
[2017-08-25 18:21:43.042169] INFO: join: /y_2014, rows=486220/564769, timetaken=1.102641s
[2017-08-25 18:21:43.108169] INFO: join: total result rows: 486220
[2017-08-25 18:21:43.109936] INFO: bigquant: join.v2 end [1.295549s].
[2017-08-25 18:21:43.116937] INFO: bigquant: stock_ranker_train.v4 start ..
[2017-08-25 18:21:43.314173] INFO: df2bin: prepare bins ..
[2017-08-25 18:21:43.407410] INFO: df2bin: prepare data: training ..
[2017-08-25 18:21:48.948440] INFO: stock_ranker_train: 30d4b148 training: 486220 rows
[2017-08-25 18:23:00.382694] INFO: bigquant: stock_ranker_train.v4 end [77.265737s].

调用策略引擎

In [14]:
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=50000,               # 初始资金
    benchmark='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id},
    m_deps=np.random.rand()
)
[2017-08-25 18:23:00.413738] INFO: bigquant: backtest.v7 start ..
[2017-08-25 18:23:00.553180] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-08-25 18:23:01.763482] INFO: general_feature_extractor: year 2015, featurerows=569698
[2017-08-25 18:23:05.928287] INFO: general_feature_extractor: year 2016, featurerows=641546
[2017-08-25 18:23:07.781582] INFO: general_feature_extractor: year 2017, featurerows=382398
[2017-08-25 18:23:07.804534] INFO: general_feature_extractor: total feature rows: 1593642
[2017-08-25 18:23:07.811480] INFO: bigquant: general_feature_extractor.v5 end [7.25831s].
[2017-08-25 18:23:07.818402] INFO: bigquant: derived_feature_extractor.v1 start ..
[2017-08-25 18:23:08.531311] INFO: derived_feature_extractor: extracted shift(amount_0,2)/amount_0, 0.274s
[2017-08-25 18:23:08.665017] INFO: derived_feature_extractor: /y_2015, 569698
[2017-08-25 18:23:09.046601] INFO: derived_feature_extractor: /y_2016, 641546
[2017-08-25 18:23:09.495512] INFO: derived_feature_extractor: /y_2017, 382398
[2017-08-25 18:23:09.684924] INFO: bigquant: derived_feature_extractor.v1 end [1.866501s].
[2017-08-25 18:23:09.691957] INFO: bigquant: transform.v2 start ..
[2017-08-25 18:23:10.112401] INFO: transform: transformed /y_2015, 564083/569698
[2017-08-25 18:23:10.602977] INFO: transform: transformed /y_2016, 641063/641546
[2017-08-25 18:23:10.892532] INFO: transform: transformed /y_2017, 381874/382398
[2017-08-25 18:23:10.919343] INFO: transform: transformed rows: 1587020/1593642
[2017-08-25 18:23:10.930925] INFO: bigquant: transform.v2 end [1.238951s].
[2017-08-25 18:23:10.938232] INFO: bigquant: stock_ranker_predict.v4 start ..
[2017-08-25 18:23:11.578782] INFO: df2bin: prepare data: prediction ..
[2017-08-25 18:23:28.614331] INFO: stock_ranker_predict: prediction: 1587020 rows
[2017-08-25 18:23:37.998887] INFO: bigquant: stock_ranker_predict.v4 end [27.060632s].
[2017-08-25 18:24:15.841520] INFO: Performance: Simulated 618 trading days out of 618.
[2017-08-25 18:24:15.842780] INFO: Performance: first open: 2015-01-05 14:30:00+00:00
[2017-08-25 18:24:15.843599] INFO: Performance: last close: 2017-07-17 19:00:00+00:00
  • 收益率13.09%
  • 年化收益率5.14%
  • 基准收益率3.67%
  • 阿尔法0.03
  • 贝塔0.65
  • 夏普比率0.02
  • 收益波动率31.19%
  • 信息比率0.14
  • 最大回撤59.15%
[2017-08-25 18:24:18.251336] INFO: bigquant: backtest.v7 end [77.837594s].