周高收益策略

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

(pal) #1
克隆策略
In [1]:
# 基础参数配置
class conf:
    start_date = '2010-01-01'
    end_date='2017-11-01'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2015-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 = [
        'return_5',  # 5日收益
        'avg_turn_5',  # 5日平均换手率
        'pe_ttm_0',  # 市盈率TTM
        'fs_roe_0',  # 净资产收益率
        'ta_sma_5_0',  # 5日移动平均
        'ta_sma_10_0',  # 10日移动平均
        'list_days_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', is_regression=True)
# 计算特征数据
m2 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.split_date,
    features=conf.features)

m3=M.add_columns.v1(data=m2.data, eval_list=conf.features)

# 数据预处理:缺失数据处理,数据规范化
m4 = M.transform.v2(
    data=m3.data, transforms=None,
    drop_null=True, astype='int32', except_columns=['date', 'instrument'],
    clip_lower=-200000000, clip_upper=200000000)
# 合并标注和特征数据
m5 = M.join.v2(data1=m1.data, data2=m4.data, on=['date', 'instrument'], sort=True)
# 随机森林训练
m6 = M.random_forest_train.v1(training_ds=m5.data, features=conf.features, is_regression=True)


## 量化回测 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,features=conf.features)
    n2=M.add_columns.v1(data=n1.data, eval_list=conf.features)
    n3 = M.transform.v2(
        data=n2.data, transforms=None,
        drop_null=True, astype='int32', except_columns=['date', 'instrument'],
        clip_lower=-200000000, clip_upper=200000000)
    n4 = M.random_forest_predict.v1(model=context.options['model_id'],data=n3.data)
    context.instruments = n4.instruments
    context.options['predictions'] = n4.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)


# 调用交易引擎
m7 = 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': m6.model}
)
[2017-11-20 17:00:17.850517] INFO: bigquant: fast_auto_labeler.v8 开始运行..
[2017-11-20 17:00:17.864827] INFO: bigquant: 命中缓存
[2017-11-20 17:00:17.913035] INFO: bigquant: fast_auto_labeler.v8 运行完成[0.062547s].
[2017-11-20 17:00:18.074838] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-11-20 17:01:01.331297] INFO: general_feature_extractor: year 2010, featurerows=431567
[2017-11-20 17:01:37.077944] INFO: general_feature_extractor: year 2011, featurerows=511455
[2017-11-20 17:02:23.690705] INFO: general_feature_extractor: year 2012, featurerows=565675
[2017-11-20 17:03:05.346769] INFO: general_feature_extractor: year 2013, featurerows=564168
[2017-11-20 17:03:40.768346] INFO: general_feature_extractor: year 2014, featurerows=569948
[2017-11-20 17:04:15.163350] INFO: general_feature_extractor: year 2015, featurerows=0
[2017-11-20 17:04:15.184319] INFO: general_feature_extractor: total feature rows: 2642813
[2017-11-20 17:04:15.187956] INFO: bigquant: general_feature_extractor.v5 运行完成[237.113173s].
[2017-11-20 17:04:15.201078] INFO: bigquant: add_columns.v1 开始运行..
[2017-11-20 17:04:16.779503] INFO: add_columns: add columns for /y_2010
[2017-11-20 17:04:18.236710] INFO: add_columns: add columns for /y_2011
[2017-11-20 17:04:19.731315] INFO: add_columns: add columns for /y_2012
[2017-11-20 17:04:20.809675] INFO: add_columns: add columns for /y_2013
[2017-11-20 17:04:21.852711] INFO: add_columns: add columns for /y_2014
[2017-11-20 17:04:21.926199] INFO: bigquant: add_columns.v1 运行完成[6.725069s].
[2017-11-20 17:04:21.978437] INFO: bigquant: transform.v2 开始运行..
[2017-11-20 17:04:23.640913] INFO: transform: transformed /y_2010, 404066/431567
[2017-11-20 17:04:25.481242] INFO: transform: transformed /y_2011, 485931/511455
[2017-11-20 17:04:27.161993] INFO: transform: transformed /y_2012, 548789/565675
[2017-11-20 17:04:28.611796] INFO: transform: transformed /y_2013, 559553/564168
[2017-11-20 17:04:30.679775] INFO: transform: transformed /y_2014, 562425/569948
[2017-11-20 17:04:30.718562] INFO: transform: transformed rows: 2560764/2642813
[2017-11-20 17:04:30.740925] INFO: bigquant: transform.v2 运行完成[8.76249s].
[2017-11-20 17:04:30.794040] INFO: bigquant: join.v2 开始运行..
[2017-11-20 17:04:41.813036] INFO: join: /y_2010, rows=403616/404066, timetaken=5.280063s
[2017-11-20 17:04:48.779089] INFO: join: /y_2011, rows=485493/485931, timetaken=6.919951s
[2017-11-20 17:04:53.889228] INFO: join: /y_2012, rows=547853/548789, timetaken=5.063757s
[2017-11-20 17:05:04.038979] INFO: join: /y_2013, rows=558624/559553, timetaken=10.105526s
[2017-11-20 17:05:14.809524] INFO: join: /y_2014, rows=545965/562425, timetaken=10.700681s
[2017-11-20 17:05:14.999651] INFO: join: total result rows: 2541551
[2017-11-20 17:05:15.002712] INFO: bigquant: join.v2 运行完成[44.208649s].
[2017-11-20 17:05:15.434484] INFO: bigquant: random_forest_train.v1 开始运行..
[2017-11-20 17:08:01.254790] INFO: random_forest_train: model train data score:0.05
[2017-11-20 17:08:01.281440] INFO: bigquant: random_forest_train.v1 运行完成[165.846961s].
[2017-11-20 17:08:01.347775] INFO: bigquant: backtest.v7 开始运行..
[2017-11-20 17:08:01.489651] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2017-11-20 17:08:14.835206] INFO: general_feature_extractor: year 2015, featurerows=569698
[2017-11-20 17:08:48.381237] INFO: general_feature_extractor: year 2016, featurerows=641546
[2017-11-20 17:09:07.246505] INFO: general_feature_extractor: year 2017, featurerows=607245
[2017-11-20 17:09:07.274424] INFO: general_feature_extractor: total feature rows: 1818489
[2017-11-20 17:09:07.284070] INFO: bigquant: general_feature_extractor.v5 运行完成[65.794424s].
[2017-11-20 17:09:07.293592] INFO: bigquant: add_columns.v1 开始运行..
[2017-11-20 17:09:08.172352] INFO: add_columns: add columns for /y_2015
[2017-11-20 17:09:08.955143] INFO: add_columns: add columns for /y_2016
[2017-11-20 17:09:09.693331] INFO: add_columns: add columns for /y_2017
[2017-11-20 17:09:09.739908] INFO: bigquant: add_columns.v1 运行完成[2.446372s].
[2017-11-20 17:09:09.748862] INFO: bigquant: transform.v2 开始运行..
[2017-11-20 17:09:11.224672] INFO: transform: transformed /y_2015, 554267/569698
[2017-11-20 17:09:12.734239] INFO: transform: transformed /y_2016, 628771/641546
[2017-11-20 17:09:14.367677] INFO: transform: transformed /y_2017, 580418/607245
[2017-11-20 17:09:14.393129] INFO: transform: transformed rows: 1763456/1818489
[2017-11-20 17:09:14.413900] INFO: bigquant: transform.v2 运行完成[4.665056s].
[2017-11-20 17:09:14.427480] INFO: bigquant: random_forest_predict.v1 开始运行..
[2017-11-20 17:09:22.937496] INFO: bigquant: random_forest_predict.v1 运行完成[8.510023s].
[2017-11-20 17:10:05.128484] INFO: Performance: Simulated 690 trading days out of 690.
[2017-11-20 17:10:05.130036] INFO: Performance: first open: 2015-01-05 14:30:00+00:00
[2017-11-20 17:10:05.131332] INFO: Performance: last close: 2017-11-01 19:00:00+00:00
[注意] 有 3 笔卖出是在多天内完成的。当日卖出股票超过了当日股票交易的2.5%会出现这种情况。
  • 收益率114.87%
  • 年化收益率32.23%
  • 基准收益率13.1%
  • 阿尔法0.28
  • 贝塔0.89
  • 夏普比率0.85
  • 收益波动率32.61%
  • 信息比率1.26
  • 最大回撤43.29%
[2017-11-20 17:10:09.325719] INFO: bigquant: backtest.v7 运行完成[127.977961s].