[AI Alphas(A股版)] 因子测试AI策略代码示例

alpha101
ai_alphas
策略分享
标签: #<Tag:0x00007fc05ca1d460> #<Tag:0x00007fc05ca1d320> #<Tag:0x00007fc05ca1d1b8>

(iQuant) #1

本文是 AI Alphas(A股版)的附录

克隆策略

示例1:以市净率排序因子举例

直接使用基础因子 (例如:rank_pb_lf_0) 或者通过表达式组合基础因子构建衍生因子 (例如: (close_1 + close_2 + close_3) / close_0)

In [5]:
# 基础参数配置
class conf:
    start_date = '2011-01-01'
    end_date='2017-07-18'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2016-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, split_date)
    hold_days = 40
    
    # 机器学习目标标注函数
    # 如下标注函数等价于 min(max((持有期间的收益 * 100), -20), 20) + 20 (后面的M.fast_auto_labeler会做取整操作)
    # 说明:max/min这里将标注分数限定在区间[-20, 20],+20将分数变为非负数 (StockRanker要求标注分数非负整数)
    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',
    ]
[2017-07-29 11:52:40.845498] INFO: bigquant: fast_auto_labeler.v8 start ..
[2017-07-29 11:52:40.864893] INFO: bigquant: hit cache
[2017-07-29 11:52:40.870142] INFO: bigquant: fast_auto_labeler.v8 end [0.024696s].
[2017-07-29 11:52:40.880713] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-07-29 11:52:40.912562] INFO: bigquant: hit cache
[2017-07-29 11:52:40.913643] INFO: bigquant: general_feature_extractor.v5 end [0.032942s].
[2017-07-29 11:52:40.923546] INFO: bigquant: transform.v2 start ..
[2017-07-29 11:52:40.937908] INFO: bigquant: hit cache
[2017-07-29 11:52:40.939024] INFO: bigquant: transform.v2 end [0.015499s].
[2017-07-29 11:52:40.946128] INFO: bigquant: join.v2 start ..
[2017-07-29 11:53:28.428285] INFO: join: /y_2011, rows=510701/511343, timetaken=23.558177s
[2017-07-29 11:53:57.323767] INFO: join: /y_2012, rows=564520/565675, timetaken=28.859163s
[2017-07-29 11:54:27.036695] INFO: join: /y_2013, rows=562953/564168, timetaken=29.668641s
[2017-07-29 11:54:55.273305] INFO: join: /y_2014, rows=567564/569948, timetaken=28.188987s
[2017-07-29 11:55:14.040650] INFO: join: /y_2015, rows=447609/569698, timetaken=18.721402s
[2017-07-29 11:55:14.173195] INFO: join: total result rows: 2653347
[2017-07-29 11:55:14.174939] INFO: bigquant: join.v2 end [153.228819s].
[2017-07-29 11:55:14.186669] INFO: bigquant: stock_ranker_train.v3 start ..
[2017-07-29 11:55:23.254698] INFO: df2bin: prepare data: training ..
[2017-07-29 11:55:49.191184] INFO: stock_ranker_train: ba00a630 training: 2653347 rows
[2017-07-29 11:58:19.677243] INFO: bigquant: stock_ranker_train.v3 end [185.490562s].
In [ ]:
# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
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)
In [9]:
## 量化回测 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()
    buy_cost = 0.0003
    sell_cost = 0.0013
    # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
    context.set_commission(PerOrder(buy_cost=buy_cost, sell_cost=sell_cost, 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)
In [10]:
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=100000,               # 初始资金
    benchmark='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id})
[2017-07-29 12:03:11.531522] INFO: bigquant: backtest.v7 start ..
[2017-07-29 12:03:11.639292] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-07-29 12:03:25.379126] INFO: general_feature_extractor: year 2016, featurerows=641546
[2017-07-29 12:03:34.205450] INFO: general_feature_extractor: year 2017, featurerows=385417
[2017-07-29 12:03:34.221188] INFO: general_feature_extractor: total feature rows: 1026963
[2017-07-29 12:03:34.227685] INFO: bigquant: general_feature_extractor.v5 end [22.588403s].
[2017-07-29 12:03:34.237387] INFO: bigquant: transform.v2 start ..
[2017-07-29 12:03:34.849723] INFO: transform: transformed /y_2016, 641520/641546
[2017-07-29 12:03:35.141263] INFO: transform: transformed /y_2017, 385417/385417
[2017-07-29 12:03:35.158352] INFO: transform: transformed rows: 1026937/1026963
[2017-07-29 12:03:35.172799] INFO: bigquant: transform.v2 end [0.935408s].
[2017-07-29 12:03:35.183622] INFO: bigquant: stock_ranker_predict.v2 start ..
[2017-07-29 12:03:35.587558] INFO: df2bin: prepare data: prediction ..
[2017-07-29 12:03:45.913678] INFO: stock_ranker_predict: prediction: 1026937 rows
[2017-07-29 12:03:52.763739] INFO: bigquant: stock_ranker_predict.v2 end [17.5801s].
[2017-07-29 12:04:34.491798] INFO: Performance: Simulated 375 trading days out of 375.
[2017-07-29 12:04:34.492866] INFO: Performance: first open: 2016-01-04 14:30:00+00:00
[2017-07-29 12:04:34.493672] INFO: Performance: last close: 2017-07-18 19:00:00+00:00
  • 收益率34.62%
  • 年化收益率22.11%
  • 基准收益率-1.71%
  • 阿尔法0.21
  • 贝塔0.55
  • 夏普比率1.18
  • 收益波动率15.03%
  • 信息比率1.69
  • 最大回撤11.92%
[2017-07-29 12:04:35.893815] INFO: bigquant: backtest.v7 end [84.362237s].

示例2:以国泰君安100因子举例

使用 M.user_feature_extractor 可以构建出任何复杂的因子

In [1]:
class conf:
    start_date = '2011-01-01'
    end_date='2017-07-18'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2016-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, split_date)
    hold_days = 6
    
    # 机器学习目标标注函数
    # 如下标注函数等价于 min(max((持有期间的收益 * 100), -20), 20) + 20 (后面的M.fast_auto_labeler会做取整操作)
    # 说明:max/min这里将标注分数限定在区间[-20, 20],+20将分数变为非负数 (StockRanker要求标注分数非负整数)
    label_expr = ['return * 100/%s'%(np.sqrt(hold_days/3)), 'where(label > {0}, {0}, where(label < -{0}, -{0}, label)) + {0}'.format(10)]

# 自定义因子举例 
user_features = {
     'gtja_100':lambda x:x.volume.rolling(20).std()
}
In [2]:
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',plot_charts=False)

m2_u = M.user_feature_extractor.v1(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    history_data_fields=['volume'],look_back_days=30,
    features_by_instrument={'gtja_100': lambda x:x.volume.rolling(20).std()},
                     )

m3 = M.transform.v2(
    data=m2_u.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)


# 只对于一个特征
m5 = M.stock_ranker_train.v2(training_ds=m4.data, features=['gtja_100'])
[2017-07-29 11:49:47.481188] INFO: bigquant: fast_auto_labeler.v8 start ..
[2017-07-29 11:49:47.484940] INFO: bigquant: hit cache
[2017-07-29 11:49:47.485715] INFO: bigquant: fast_auto_labeler.v8 end [0.004572s].
[2017-07-29 11:49:47.496941] INFO: bigquant: user_feature_extractor.v1 start ..
[2017-07-29 11:49:47.498289] INFO: bigquant: hit cache
[2017-07-29 11:49:47.499032] INFO: bigquant: user_feature_extractor.v1 end [0.002093s].
[2017-07-29 11:49:47.510881] INFO: bigquant: transform.v2 start ..
[2017-07-29 11:49:47.512244] INFO: bigquant: hit cache
[2017-07-29 11:49:47.512955] INFO: bigquant: transform.v2 end [0.002077s].
[2017-07-29 11:49:47.521332] INFO: bigquant: join.v2 start ..
[2017-07-29 11:49:47.522730] INFO: bigquant: hit cache
[2017-07-29 11:49:47.523489] INFO: bigquant: join.v2 end [0.002167s].
[2017-07-29 11:49:47.566354] WARNING: bigquant: 此模块版本 M.stock_ranker_train.v2 已不再维护,并可能在未来被删除:请更新到 stock_ranker_train 最新版本
[2017-07-29 11:49:47.567195] INFO: bigquant: stock_ranker_train.v2 start ..
[2017-07-29 11:49:47.568690] INFO: bigquant: hit cache
[2017-07-29 11:49:47.569458] INFO: bigquant: stock_ranker_train.v2 end [0.002257s].
In [3]:
def prepare(context):
    instruments = D.instruments(context.start_date, context.end_date)
    n1 = M.user_feature_extractor.v1(
        instruments=instruments, start_date=context.start_date, end_date=context.end_date,
        history_data_fields=['open', 'close', 'high', 'low', 'volume', 'adjust_factor', 'amount'],look_back_days=30,
        features_by_instrument={'gtja_100': lambda x:x.volume.rolling(20).std()},
    )
    n2 = M.transform.v2(
        data=n1.data, transforms=T.get_stock_ranker_default_transforms()+[('.*', None)],
        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()
    buy_cost =  0.0003
    sell_cost = 0.0013
    # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
    context.set_commission(PerOrder(buy_cost=buy_cost, sell_cost=sell_cost, 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)
In [4]:
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=100000,               # 初始资金
    benchmark='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id})
[2017-07-29 11:49:47.898109] INFO: bigquant: backtest.v7 start ..
[2017-07-29 11:49:47.899997] INFO: bigquant: hit cache
  • 收益率23.12%
  • 年化收益率15.0%
  • 基准收益率-1.71%
  • 阿尔法0.17
  • 贝塔1.12
  • 夏普比率0.33
  • 收益波动率31.55%
  • 信息比率0.68
  • 最大回撤28.18%
[2017-07-29 11:49:48.930160] INFO: bigquant: backtest.v7 end [1.032045s].

【重磅】AI Alphas(A股版)
(Aaron7) #2

您好,

  1. 请问如果把所有策略都作为feature放进去后,是不是还需要调整一下stockranker的参数值,比如叶子节点数,树的深度和颗数。

  2. 如果把split_date之前的数据都作为training数据,那么股票的rank会比较依赖过去feature的表现,如果某些因子最近失效了,会不会依然将这些feature的权重调的较高?

如何避免这些问题呢,还麻烦您回复一下,多谢。


(iQuant) #3

您好,

  1. 如果把所有单因子策略的特征(因子)全部放在一起传入到feature中,此时该策略唯一的区别只是变成了多因子AI策略。没有更多的证据说明应该调整一下stockranker的参数值。

  2. 是的。将split_date之前的数据作为training数据,训练出来的模型的确会更多的依赖过去feature的表现,如果最近风格突变,那么模型可能会失效,如果模型没有使用最近的数据重新训练,那么模型就没有改变,以前某些因子的feature_gains较高未来这些因子的feature_gains依然较高。你可以采取滚动学习的方法,即模型会隔段时间进行更新。
    .


(大胡子) #4

您好,我试的是rank_pe_lf_0这个因子,也是克隆的本文的策略,为什么夏普只有2.5呢?


(iQuant) #5

本文的M.trade.v2修改成下面这样,就可以了,回测结果就和报告《AI Alphas(A股版)》是一致的了。

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,               # 初始资金
    volume_limit=0,
    benchmark='000300.SHA',             # 比较基准,不影响回测结果
    # 通过 options 参数传递预测数据和参数给回测引擎
    options={'hold_days': conf.hold_days, 'model_id': m5.model_id})

(urget) #6

这个例子很好,可以让对python不熟的人直接使用来测试各种因子。
请问我把示例中的市场改为期货市场了,为什么运行后仍然是买卖股票呢?还有能不能给一个关于期货市场的这样的示例?


(iQuant) #7

期货的例子我们最近10来天会依次放出。


(cph315) #8

hi,iQuant,你好,单因子测试版本一个一个feature手动修改并记录收益率,效率也太差了,能不能搞成一个自动测试并记录收益率的版本啊?


(sensezeng) #9


根据AI Alphas(A股版) 国泰君安100因子的年化收益为0.62。
可是这个代码回测只是15%。有哪里不一样?

已经使用:
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, # 初始资金
volume_limit=0,
benchmark=‘000300.SHA’, # 比较基准,不影响回测结果
# 通过 options 参数传递预测数据和参数给回测引擎
options={‘hold_days’: conf.hold_days, ‘model_id’: m5.model_id})


(sakalymyer) #10

是不是持仓时间