多策略组合收益分析

策略分享
策略组合
标签: #<Tag:0x00007f61de8f0ee8> #<Tag:0x00007f61de8f0d58>

(神龙斗士) #1

使用 M.multi_strategy_analysis 分析多个策略组合后的效果

克隆策略
In [8]:
# 基础参数配置
class conf:
    start_date = '2010-01-01'
    end_date='2017-06-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 = [
        'close_5/close_0',  # 5日收益
        'close_10/close_0',  # 10日收益
        'close_20/close_0',  # 20日收益
        'avg_amount_0/avg_amount_5',  # 当日/5日平均交易额
        'avg_amount_5/avg_amount_20',  # 5日/20日平均交易额
        'rank_avg_amount_0/rank_avg_amount_5',  # 当日/5日平均交易额排名
        'rank_avg_amount_5/rank_avg_amount_10',  # 5日/10日平均交易额排名
        'rank_return_0',  # 当日收益
        'rank_return_5',  # 5日收益
        'rank_return_10',  # 10日收益
        'rank_return_0/rank_return_5',  # 当日/5日收益排名
        'rank_return_5/rank_return_10',  # 5日/10日收益排名
        'pe_ttm_0',  # 市盈率TTM
    ]

# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
m1 = M.fast_auto_labeler.v5(
    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_1 = M.stock_ranker_train.v2(training_ds=m4.data, features=conf.features[:len(conf.features)//2])
m5_2 = M.stock_ranker_train.v2(training_ds=m4.data, features=conf.features[len(conf.features)//2:])


## 量化回测 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_1 = M.trade.v1(
    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_1.model_id},
    backtest_only=True
)
m6_2 = M.trade.v1(
    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_2.model_id},
    backtest_only=True
)
[2017-06-30 15:05:42.507792] INFO: bigquant: fast_auto_labeler.v5 start ..
[2017-06-30 15:05:42.510125] INFO: bigquant: hit cache
[2017-06-30 15:05:42.516162] INFO: bigquant: fast_auto_labeler.v5 end [0.00839s].
[2017-06-30 15:05:42.523485] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-06-30 15:05:42.525560] INFO: bigquant: hit cache
[2017-06-30 15:05:42.526818] INFO: bigquant: general_feature_extractor.v5 end [0.003354s].
[2017-06-30 15:05:42.531585] INFO: bigquant: transform.v2 start ..
[2017-06-30 15:05:42.532845] INFO: bigquant: hit cache
[2017-06-30 15:05:42.533560] INFO: bigquant: transform.v2 end [0.001977s].
[2017-06-30 15:05:42.536518] INFO: bigquant: join.v2 start ..
[2017-06-30 15:05:42.537703] INFO: bigquant: hit cache
[2017-06-30 15:05:42.538404] INFO: bigquant: join.v2 end [0.001885s].
[2017-06-30 15:05:42.569433] INFO: bigquant: stock_ranker_train.v2 start ..
[2017-06-30 15:05:42.583482] INFO: stock_ranker_train: training: 2604421 rows
[2017-06-30 15:07:12.821585] INFO: bigquant: stock_ranker_train.v2 end [90.25212s].
[2017-06-30 15:07:12.826160] INFO: bigquant: stock_ranker_train.v2 start ..
[2017-06-30 15:07:12.832283] INFO: stock_ranker_train: training: 2604421 rows
[2017-06-30 15:08:43.076189] INFO: bigquant: stock_ranker_train.v2 end [90.250001s].
[2017-06-30 15:08:43.121847] INFO: bigquant: backtest.v6 start ..
[2017-06-30 15:08:45.497517] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-06-30 15:08:57.230726] INFO: general_feature_extractor: year 2015, featurerows=569698
[2017-06-30 15:09:09.744442] INFO: general_feature_extractor: year 2016, featurerows=641546
[2017-06-30 15:09:17.927213] INFO: general_feature_extractor: year 2017, featurerows=286124
[2017-06-30 15:09:17.940371] INFO: general_feature_extractor: total feature rows: 1497368
[2017-06-30 15:09:17.956780] INFO: bigquant: general_feature_extractor.v5 end [32.459265s].
[2017-06-30 15:09:17.962140] INFO: bigquant: transform.v2 start ..
[2017-06-30 15:09:19.804357] INFO: transform: transformed /y_2015, 565355/569698
[2017-06-30 15:09:21.523036] INFO: transform: transformed /y_2016, 637125/641546
[2017-06-30 15:09:22.415547] INFO: transform: transformed /y_2017, 281769/286124
[2017-06-30 15:09:22.429523] INFO: transform: transformed rows: 1484249/1497368
[2017-06-30 15:09:22.438898] INFO: bigquant: transform.v2 end [4.476753s].
[2017-06-30 15:09:22.443825] INFO: bigquant: stock_ranker_predict.v2 start ..
[2017-06-30 15:09:23.438964] INFO: df2bin: prepare data: prediction ..
[2017-06-30 15:09:48.731830] INFO: stock_ranker_predict: prediction: 1484249 rows
[2017-06-30 15:10:06.184853] INFO: bigquant: stock_ranker_predict.v2 end [43.740966s].
[2017-06-30 15:10:47.605033] INFO: Performance: Simulated 586 trading days out of 586.
[2017-06-30 15:10:47.606994] INFO: Performance: first open: 2015-01-05 14:30:00+00:00
[2017-06-30 15:10:47.607957] INFO: Performance: last close: 2017-06-01 19:00:00+00:00
[注意] 有 5 笔卖出是在多天内完成的。当日卖出股票超过了当日股票交易的2.5%会出现这种情况。
  • 收益率220.65%
  • 年化收益率65.05%
  • 基准收益率-1.02%
  • 阿尔法0.65
  • 贝塔0.93
  • 夏普比率1.52
  • 收益波动率39.87%
  • 信息比率2.26
  • 最大回撤56.21%
[2017-06-30 15:10:50.091897] INFO: bigquant: backtest.v6 end [126.970042s].
[2017-06-30 15:10:50.129099] INFO: bigquant: backtest.v6 start ..
[2017-06-30 15:10:50.307435] INFO: bigquant: general_feature_extractor.v5 start ..
[2017-06-30 15:11:01.013019] INFO: general_feature_extractor: year 2015, featurerows=569698
[2017-06-30 15:11:13.687541] INFO: general_feature_extractor: year 2016, featurerows=641546
[2017-06-30 15:11:18.736697] INFO: general_feature_extractor: year 2017, featurerows=286124
[2017-06-30 15:11:18.745064] INFO: general_feature_extractor: total feature rows: 1497368
[2017-06-30 15:11:18.750471] INFO: bigquant: general_feature_extractor.v5 end [28.443099s].
[2017-06-30 15:11:18.755562] INFO: bigquant: transform.v2 start ..
[2017-06-30 15:11:20.396809] INFO: transform: transformed /y_2015, 567266/569698
[2017-06-30 15:11:21.711143] INFO: transform: transformed /y_2016, 639066/641546
[2017-06-30 15:11:22.551801] INFO: transform: transformed /y_2017, 283732/286124
[2017-06-30 15:11:22.563186] INFO: transform: transformed rows: 1490064/1497368
[2017-06-30 15:11:22.580243] INFO: bigquant: transform.v2 end [3.824621s].
[2017-06-30 15:11:22.585954] INFO: bigquant: stock_ranker_predict.v2 start ..
[2017-06-30 15:11:23.314791] INFO: df2bin: prepare data: prediction ..
[2017-06-30 15:11:40.012456] INFO: stock_ranker_predict: prediction: 1490064 rows
[2017-06-30 15:11:54.183205] INFO: bigquant: stock_ranker_predict.v2 end [31.597229s].
[2017-06-30 15:12:37.603159] INFO: Performance: Simulated 586 trading days out of 586.
[2017-06-30 15:12:37.604861] INFO: Performance: first open: 2015-01-05 14:30:00+00:00
[2017-06-30 15:12:37.605924] INFO: Performance: last close: 2017-06-01 19:00:00+00:00
  • 收益率146.03%
  • 年化收益率47.28%
  • 基准收益率-1.02%
  • 阿尔法0.48
  • 贝塔1.12
  • 夏普比率1.01
  • 收益波动率42.56%
  • 信息比率1.75
  • 最大回撤54.49%
[2017-06-30 15:12:40.249551] INFO: bigquant: backtest.v6 end [110.12045s].
In [12]:
m7 = M.multi_strategy_analysis.v1(raw_perfs=[m6_1.raw_perf, m6_2.raw_perf], weights=[0.4, 0.6], rebalance_period=30)
[2017-06-30 15:45:12.555902] INFO: bigquant: backtest.v6 start ..
[2017-06-30 15:45:12.560138] INFO: bigquant: hit cache
  • 收益率177.24%
  • 年化收益率55.04%
  • 基准收益率-1.02%
  • 阿尔法0.56
  • 贝塔1.04
  • 夏普比率1.26
  • 收益波动率40.31%
  • 信息比率2.12
  • 最大回撤55.07%
[2017-06-30 15:45:13.527068] INFO: bigquant: backtest.v6 end [0.971142s].

(kw) #2

啥意思呀,没有文字描述一下吗?


(神龙斗士) #3

使用场景:开发了两个不同的策略,分别有不同的收益曲线。组合两个策略能否降低波动率呢?比如分别分配40%和60%的资金给两个策略,收益曲线是什么样的么? M.multi_strategy_analysis.v1 来解决这个问题,输入是两个策略的收益曲线数据,和资金权重,输出组合的收益曲线数据。具体(包括源代码)见文档 M.multi_strategy_analysis