测试旧的策略惊喜

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

(me_robot) #1
克隆策略
In [3]:
# 基础参数配置
class conf:
    start_date = '2016-09-01'
    end_date='2019-01-04'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2017-09-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, split_date)
    instrument = D.instruments(start_date,end_date)
    
    #获取股价 最高 最低 开盘 收盘
    D.history_data(instruments, start_date, end_date,fields=['open', 'high', 'low', 'close'])
    
    # 为保证策略回测的真实性,平台数据接口D.history_data和context.history都是获取的后复权数据。
    # 与交易所一致的真实交易价格=后复权数据/复权因子
    df = D.history_data(instrument,start_date,end_date,['open','high','low','close','volume','amount','adjust_factor'])
    for price in ['open','high','low','close']:df[price] /= df['adjust_factor']
   
    #过滤停牌 st *st
    df = D.history_data(instrument,start_date,end_date,['st_status','suspended'])
    print('总数据条数: ', len(df))
    df = df.query('st_status == 0 and suspended == False')
    print('总数据条数: ', len(df))
    
    #过滤一字板涨停股票
    df = D.history_data(instrument,start_date,end_date,['high','low','price_limit_status'])
    print('总数据条数: ', len(df))
    df = df[(df['high']!=df['low'])&(df['price_limit_status']!=3)]
    print('总数据条数: ', len(df))
    
    #剔除上市不足120天股票
    df = D.history_data(instrument,start_date,end_date,['list_date'])
    df['上市天数'] = (df['date'] - df['list_date']).map(lambda x:x.days)
    df[df['上市天数']>=240] 

    # 机器学习目标标注函数
    # 如下标注函数等价于 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(22)]
    
    # 持有天数,用于计算label_expr中的return值(收益) 
    hold_days = 1

    # 特征 https://bigquant.com/docs/data_features.html,你可以通过表达式构造任何特征
    features = [
        
        #'close_6/close_1',  # 5日收益
        #'close_11/close_1',  # 10日收益
        #'close_21/close_1',  # 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_1',  # 当日收益
        #'rank_return_6',  # 5日收益
        #'rank_return_11',  # 10日收益
        #'rank_return_1/rank_return_6',  # 当日/5日收益排名
        #'rank_return_6/rank_return_11',  # 5日/10日收益排名
        #'pe_ttm_0 >0',  # 市盈率TTM
        #'st_status_0==0',  # ST状态
        
        'open_5/open_0',  # 5日开盘价收益
        'open_10/open_0',  # 10日收益
        'open_20/open_0',  # 20日收益
        
        'close_5/close_0',  # 5日收盘价收益
        'close_10/close_0',  # 10日收益
        'close_20/close_0',  # 20日收益
        
        'high_5/high_0',  # 5日最高价收益
        'high_10/high_0',  # 10日收益
        'high_20/high_0',  # 20日收益
        
        'low_5/low_0',  # 5日最低价收益
        'low_10/low_0',  # 10日收益
        'low_20/low_0',  # 20日收益
        
        '((open_5+close_5+high_5+low_5)/4)/((open_0+close_0+high_0+low_0)/4)',  # 5日平均价收益
        '((open_10+close_10+high_10+low_10)/4)/((open_0+close_0+high_0+low_0)/4)',  # 10日收益
        '((open_20+close_20+high_20+low_20)/4)/((open_0+close_0+high_0+low_0)/4)',  # 20日收益
        
        'avg_amount_0/avg_amount_5',  # 当日/5日平均交易额
        'avg_amount_5/avg_amount_10',  # 5日/10日平均交易额
        'avg_amount_10/avg_amount_20',  # 10日/20日平均交易额
        
        'rank_avg_amount_0/rank_avg_amount_5',  # 当日/5日平均交易额排名
        'rank_avg_amount_5/rank_avg_amount_10',  # 5日/10日平均交易额排名
        'rank_avg_amount_10/rank_avg_amount_20',  # 10日/20日平均交易额排名
        
        'rank_return_0',  # 当日收益
        'rank_return_5',  # 5日收益
        'rank_return_10',  # 10日收益
        'rank_return_20',  # 20日收益
        
        'rank_return_0/rank_return_5',  # 当日/5日收益排名
        'rank_return_5/rank_return_10',  # 5日/10日收益排名
        'rank_return_10/rank_return_20',  # 5日/20日收益排名
        
        #'pe_ttm_0 > 0',  # 市盈率TTM
        'st_status_0 == 0',  # ST状态
    ]

# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
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)

# 每一个节点都可以点击展开
#m5.plot_model()

## 量化回测 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.0005, sell_cost=0.0015, min_cost=5))
    
       # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
       # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
    stock_count = 1
    
    # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
    #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(1, stock_count)])
    #context.stock_weights

    # 每只的股票等权重
    context.stock_weights = [1 / stock_count for _ in range(0, 5)]
    context.stock_weights
    
    # 设置每只股票占用的最大资金比例
    context.max_cash_per_instrument = 1.618/3

# 回测引擎:每日数据处理函数,每天执行一次
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, (0.618 if is_staging else 1.618) * 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:
            current_price = data.current(context.symbol(instrument), 'price')
             # 按整百股数下单
            amount = math.floor(cash / current_price / 100) * 100
            context.order(context.symbol(instrument), amount)


# 调用交易引擎
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}
)

# 因子风险分析
#m6.risk_analyze()  

#策略风险分析
m6.pyfolio_full_tear_sheet()

# 获取回测结果,DataFrame格式
df = m6.raw_perf.read_df()

# 存储到目录,文件保存为csv格式
#df.to_csv('回测结果.csv')
总数据条数:  1903740
总数据条数:  1757223
总数据条数:  1903740
总数据条数:  1765729
[2019-01-07 00:26:43.888090] INFO: bigquant: fast_auto_labeler.v8 开始运行..
[2019-01-07 00:26:43.894603] INFO: bigquant: 命中缓存
[2019-01-07 00:26:43.900070] INFO: bigquant: fast_auto_labeler.v8 运行完成[0.012001s].
[2019-01-07 00:26:43.904495] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2019-01-07 00:26:43.909911] INFO: bigquant: 命中缓存
[2019-01-07 00:26:43.911028] INFO: bigquant: general_feature_extractor.v5 运行完成[0.006521s].
[2019-01-07 00:26:43.943141] INFO: bigquant: transform.v2 开始运行..
[2019-01-07 00:26:43.948053] INFO: bigquant: 命中缓存
[2019-01-07 00:26:43.949028] INFO: bigquant: transform.v2 运行完成[0.005932s].
[2019-01-07 00:26:43.951940] INFO: bigquant: join.v2 开始运行..
[2019-01-07 00:26:43.956302] INFO: bigquant: 命中缓存
[2019-01-07 00:26:43.957130] INFO: bigquant: join.v2 运行完成[0.005215s].
[2019-01-07 00:26:43.960351] INFO: bigquant: stock_ranker_train.v3 开始运行..
[2019-01-07 00:26:43.965343] INFO: bigquant: 命中缓存
[2019-01-07 00:26:43.966519] INFO: bigquant: stock_ranker_train.v3 运行完成[0.006181s].
[2019-01-07 00:26:43.978704] INFO: bigquant: backtest.v7 开始运行..
[2019-01-07 00:26:43.984353] INFO: bigquant: 命中缓存
  • 收益率29.6%
  • 年化收益率22.12%
  • 基准收益率-20.57%
  • 阿尔法0.4
  • 贝塔0.87
  • 夏普比率0.64
  • 胜率0.52
  • 盈亏比1.15
  • 收益波动率37.46%
  • 信息比率0.08
  • 最大回撤21.79%
[2019-01-07 00:26:44.949338] INFO: bigquant: backtest.v7 运行完成[0.970604s].
Entire data start date: 2017-09-01
Entire data end date: 2019-01-04


Backtest Months: 15
Performance statistics Backtest
cum_returns_final 0.30
annual_return 0.22
annual_volatility 0.37
sharpe_ratio 0.72
calmar_ratio 1.02
stability_of_timeseries 0.63
max_drawdown -0.22
omega_ratio 1.13
sortino_ratio 1.05
skew -0.01
kurtosis 0.78
tail_ratio 1.02
common_sense_ratio 1.25
information_ratio 0.08
alpha 0.42
beta 0.93
Worst Drawdown Periods net drawdown in % peak date valley date recovery date duration
0 21.79 2018-04-11 2018-10-16 2018-11-14 156
1 16.64 2018-11-15 2019-01-04 NaT NaN
2 14.79 2017-11-13 2017-11-23 2017-12-29 35
3 7.26 2017-09-11 2017-10-19 2017-10-30 36
4 6.95 2017-12-29 2018-01-19 2018-02-22 40
[-0.046 -0.078]
Stress Events mean min max
New Normal 0.11% -7.97% 8.71%
Top 10 long positions of all time max
Equity(111 [002512.SZA]) 56.64%
Equity(1138 [002094.SZA]) 55.48%
Equity(850 [603989.SHA]) 55.03%
Equity(1507 [000616.SZA]) 54.95%
Equity(2888 [603579.SHA]) 54.90%
Equity(1350 [002336.SZA]) 54.85%
Equity(1804 [601086.SHA]) 54.70%
Equity(1549 [000722.SZA]) 54.69%
Equity(890 [603843.SHA]) 54.56%
Equity(2805 [002199.SZA]) 54.55%
Top 10 short positions of all time max
Top 10 positions of all time max
Equity(111 [002512.SZA]) 56.64%
Equity(1138 [002094.SZA]) 55.48%
Equity(850 [603989.SHA]) 55.03%
Equity(1507 [000616.SZA]) 54.95%
Equity(2888 [603579.SHA]) 54.90%
Equity(1350 [002336.SZA]) 54.85%
Equity(1804 [601086.SHA]) 54.70%
Equity(1549 [000722.SZA]) 54.69%
Equity(890 [603843.SHA]) 54.56%
Equity(2805 [002199.SZA]) 54.55%
All positions ever held max
Equity(111 [002512.SZA]) 56.64%
Equity(1138 [002094.SZA]) 55.48%
Equity(850 [603989.SHA]) 55.03%
Equity(1507 [000616.SZA]) 54.95%
Equity(2888 [603579.SHA]) 54.90%
Equity(1350 [002336.SZA]) 54.85%
Equity(1804 [601086.SHA]) 54.70%
Equity(1549 [000722.SZA]) 54.69%
Equity(890 [603843.SHA]) 54.56%
Equity(2805 [002199.SZA]) 54.55%
Equity(1838 [603179.SHA]) 54.53%
Equity(1901 [002472.SZA]) 54.48%
Equity(2262 [000868.SZA]) 54.44%
Equity(2719 [002222.SZA]) 54.37%
Equity(2052 [002638.SZA]) 54.30%
Equity(1816 [002867.SZA]) 54.18%
Equity(1018 [601005.SHA]) 54.11%
Equity(2373 [600455.SHA]) 54.10%
Equity(3457 [300470.SZA]) 54.10%
Equity(495 [000703.SZA]) 54.06%
Equity(1047 [002212.SZA]) 53.99%
Equity(1609 [600807.SHA]) 53.99%
Equity(3311 [300272.SZA]) 53.88%
Equity(3070 [300116.SZA]) 53.85%
Equity(436 [002231.SZA]) 53.82%
Equity(669 [300332.SZA]) 53.81%
Equity(3456 [002332.SZA]) 53.81%
Equity(884 [002159.SZA]) 53.74%
Equity(3255 [601952.SHA]) 53.73%
Equity(1376 [002847.SZA]) 53.62%
... ...
Equity(1717 [600971.SHA]) 1.34%
Equity(2905 [000982.SZA]) 1.31%
Equity(103 [600783.SHA]) 1.24%
Equity(1525 [300537.SZA]) 1.20%
Equity(3382 [000516.SZA]) 1.17%
Equity(3060 [000812.SZA]) 1.15%
Equity(687 [002017.SZA]) 1.13%
Equity(783 [300305.SZA]) 0.93%
Equity(2123 [300426.SZA]) 0.91%
Equity(1269 [603716.SHA]) 0.86%
Equity(699 [002271.SZA]) 0.86%
Equity(2685 [600095.SHA]) 0.83%
Equity(927 [300093.SZA]) 0.77%
Equity(126 [600708.SHA]) 0.75%
Equity(1363 [300269.SZA]) 0.67%
Equity(154 [000650.SZA]) 0.59%
Equity(3111 [300527.SZA]) 0.59%
Equity(2461 [300530.SZA]) 0.57%
Equity(2413 [300567.SZA]) 0.56%
Equity(16 [300010.SZA]) 0.53%
Equity(1640 [002247.SZA]) 0.52%
Equity(2995 [603817.SHA]) 0.45%
Equity(227 [002299.SZA]) 0.42%
Equity(477 [600425.SHA]) 0.40%
Equity(2243 [300502.SZA]) 0.35%
Equity(2822 [002499.SZA]) 0.29%
Equity(2269 [000582.SZA]) 0.22%
Equity(2600 [600658.SHA]) 0.19%
Equity(585 [002690.SZA]) 0.18%
Equity(1367 [300643.SZA]) 0.00%

395 rows × 1 columns