新手训练

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

(gary_ho122) #1
克隆策略
In [1]:
# 基础参数配置
class conf:
    start_date = '2009-01-01'
    end_date='2017-06-21'
    # split_date 之前的数据用于训练,之后的数据用作效果评估
    split_date = '2015-01-01'
    # D.instruments: https://bigquant.com/docs/data_instruments.html
    instruments = D.instruments(start_date, end_date)

    # 机器学习目标标注函数
    # 如下标注函数等价于 min(max((持有期间的收益 * 100), -20), 20) + 20 (后面的M.fast_auto_labeler会做取整操作)
    # 说明:max/min这里将标注分数限定在区间[-20, 20],+20将分数变为非负数 (StockRanker要求标注分数非负整数)
    label_expr = ['return* 30', 'where(label > {0}, {0}, where(label < -{0}, -{0}, label)) + {0}'.format(1)]
    # 持有天数,用于计算label_expr中的return值(收益)
    hold_days = 10
    features = [
        'ta_sma_10_0/ta_sma_20_0',
        'ta_sma_20_0/ta_sma_30_0',
        'ta_sma_30_0/ta_sma_60_0',
        'ta_atr_14_0',
        'ta_atr_28_0',
        'ta_rsi_14_0',
        'ta_rsi_28_0',
        
    ]


# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好
m1 = M.fast_auto_labeler.v6(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.end_date,
    label_expr=conf.label_expr, hold_days=conf.hold_days,
    benchmark='000300.SHA', sell_at='close', buy_at='open', is_regression=False)
# 计算特征数据

m2 = M.general_feature_extractor.v5(
    instruments=conf.instruments, start_date=conf.start_date, end_date=conf.end_date,
    features=conf.features)

def calcu_relative_ret(df):
    start_date = min(m11.data.read_df().date).strftime('%Y-%m-%d')
    end_date = max(m11.data.read_df().date).strftime('%Y-%m-%d')
   
    sz50_df = D.history_data(
    '000300.SHA',
    start_date=(pd.to_datetime(start_date) - datetime.timedelta(days=10)).strftime('%Y-%m-%d'),  # 多取几天的数据
    end_date=end_date)[['date', 'close']].rename(columns={'close': 'hs300_close'})
    df = df[['date', 'close_0']].reset_index().merge(sz50_df, on='date', how='left').set_index('index')
    return df['close_0'].pct_change() - df['hs300_close'].pct_change()

def groupby_calcu_relative_ret(df, close_0):
    return df.groupby('instrument', group_keys=False).apply(calcu_relative_ret)


m2_1=M.derived_feature_extractor.v2(input_data=m2.data, features=conf.features,user_functions={'groupby_calcu_relative_ret'})


#m2_1=M.derived_feature_extractor.v1(data=m2.data, features=conf.features)
# 数据预处理:缺失数据处理,数据规范化,T.get_stock_ranker_default_transforms为StockRanker模型做数据预处理
m3=M.add_columns.v1(data=m2_1.data, eval_list=conf.features)
m4 = M.transform.v2(
    data=m3.data, transforms=None,
    drop_null=True, astype='float32', except_columns=['date', 'instrument'],
    clip_lower=0, clip_upper=200000000)
# 合并标注和特征数据
m5 = M.join.v2(data1=m4.data, data2=m1.data, on=['date', 'instrument'], sort=True)

# 训练数据集
m6_training = M.filter.v2(data=m5.data, expr='date < "%s"' % conf.split_date)
# 评估数据集
m6_evaluation = M.filter.v2(data=m5.data, expr='"%s" <= date' % conf.split_date)

m7 = M.linear_sgd_train.v1(training_ds=m6_training.data, features=conf.features, is_regression=False)

stock_num=40
# 3. 策略主体函数
# 初始化虚拟账户状态,只在第一个交易日运行
def initialize(context):
    # 设置手续费,买入时万3,卖出是千分之1.3,不足5元以5元计
    context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    m8 = M.linear_sgd_predict.v1(model=context.options['model'],data=m6_evaluation.data)
    context.pred_df = m8.predictions.read_df()
    context.pred_df = context.pred_df.groupby('date').apply(lambda x:x.sort_values('pred_label',ascending=False))

# 策略交易逻辑,每个交易日运行一次
def handle_data(context,data):
    today = data.current_dt
    today_str=str(today.date())

    equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}

    # 调仓:卖出所有持有股票
    for instrument in equities:
        # 停牌的股票,将不能卖出,将在下一个调仓期处理
        if data.can_trade(context.symbol(instrument)) and today-equities[instrument].last_sale_date>=datetime.timedelta(context.options['rebalance_period']):
            context.order_target_percent(context.symbol(instrument), 0)

    # 调仓:买入新的股票
    if today_str not in context.pred_df.index:
        return
    instruments_to_buy = context.pred_df.ix[today_str].instrument
    if len(instruments_to_buy) == 0:
        return
    # 等量分配资金买入股票
    weight = 1.0 / stock_num
    can_buy_num = stock_num - len(equities)
    for instrument in instruments_to_buy:
        if can_buy_num>0 and data.can_trade(context.symbol(instrument)) and instrument not in equities:
            context.order_target_percent(context.symbol(instrument), weight)
            can_buy_num -= 1

# 4. 策略回测:https://bigquant.com/docs/module_trade.html
m = M.trade.v3(
    instruments=conf.instruments,
    start_date=conf.split_date,
    end_date=conf.end_date,
    initialize=initialize,
    handle_data=handle_data,
    # 买入订单以开盘价成交
    order_price_field_buy='open',
    # 卖出订单以开盘价成交
    order_price_field_sell='close',
    capital_base=1000000,
    benchmark='000300.SHA',
    # 传入数据给回测模块,所有回测函数里用到的数据都要从这里传入,并通过 context.options 使用,否则可能会遇到缓存问题
    options={'rebalance_period': conf.hold_days, 'model':m7.model},
)
m.risk_analyze()
m.pyfolio_full_tear_sheet()
[2018-06-26 15:01:39.727367] WARNING: bigquant: 此模块版本 M.fast_auto_labeler.v6 已不再维护。你仍然可以使用,但建议升级到最新版本:请更新到 fast_auto_labeler 最新版本
[2018-06-26 15:01:39.729524] INFO: bigquant: fast_auto_labeler.v6 开始运行..
[2018-06-26 15:01:39.814127] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.015887] INFO: bigquant: fast_auto_labeler.v6 运行完成[0.286326s].
[2018-06-26 15:01:40.066557] INFO: bigquant: general_feature_extractor.v5 开始运行..
[2018-06-26 15:01:40.069220] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.069869] INFO: bigquant: general_feature_extractor.v5 运行完成[0.003343s].
[2018-06-26 15:01:40.084162] INFO: bigquant: derived_feature_extractor.v2 开始运行..
[2018-06-26 15:01:40.086311] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.087032] INFO: bigquant: derived_feature_extractor.v2 运行完成[0.002873s].
[2018-06-26 15:01:40.095596] INFO: bigquant: add_columns.v1 开始运行..
[2018-06-26 15:01:40.097906] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.098778] INFO: bigquant: add_columns.v1 运行完成[0.00317s].
[2018-06-26 15:01:40.108884] INFO: bigquant: transform.v2 开始运行..
[2018-06-26 15:01:40.110935] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.111717] INFO: bigquant: transform.v2 运行完成[0.002827s].
[2018-06-26 15:01:40.122322] INFO: bigquant: join.v2 开始运行..
[2018-06-26 15:01:40.124476] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.125400] INFO: bigquant: join.v2 运行完成[0.003067s].
[2018-06-26 15:01:40.133956] INFO: bigquant: filter.v2 开始运行..
[2018-06-26 15:01:40.247634] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.248663] INFO: bigquant: filter.v2 运行完成[0.114717s].
[2018-06-26 15:01:40.264398] INFO: bigquant: filter.v2 开始运行..
[2018-06-26 15:01:40.267066] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.267991] INFO: bigquant: filter.v2 运行完成[0.00362s].
[2018-06-26 15:01:40.421179] INFO: bigquant: linear_sgd_train.v1 开始运行..
[2018-06-26 15:01:40.424904] INFO: bigquant: 命中缓存
[2018-06-26 15:01:40.425879] INFO: bigquant: linear_sgd_train.v1 运行完成[0.004753s].
[2018-06-26 15:01:40.475394] INFO: bigquant: backtest.v7 开始运行..
[2018-06-26 15:01:40.542383] INFO: bigquant: 命中缓存
  • 收益率91.92%
  • 年化收益率31.5%
  • 基准收益率1.54%
  • 阿尔法0.31
  • 贝塔0.99
  • 夏普比率0.76
  • 胜率0.582
  • 盈亏比0.938
  • 收益波动率35.5%
  • 信息比率1.5
  • 最大回撤36.22%
[2018-06-26 15:01:43.505022] INFO: bigquant: backtest.v7 运行完成[3.029616s].
Entire data start date: 2015-01-05
Entire data end date: 2017-06-21


Backtest Months: 28
Performance statistics Backtest
cum_returns_final 0.92
annual_return 0.31
annual_volatility 0.35
sharpe_ratio 0.95
calmar_ratio 0.87
stability_of_timeseries 0.48
max_drawdown -0.36
omega_ratio 1.19
sortino_ratio 1.29
skew -0.70
kurtosis 2.16
tail_ratio 0.83
common_sense_ratio 1.09
information_ratio -0.03
alpha 0.31
beta 0.02
Worst Drawdown Periods net drawdown in % peak date valley date recovery date duration
0 36.22 2015-06-12 2015-09-02 2017-03-07 453
1 23.11 2017-03-29 2017-06-01 NaT NaN
2 8.87 2015-04-27 2015-05-07 2015-05-13 13
3 5.24 2015-01-28 2015-02-06 2015-02-16 14
4 4.97 2015-05-27 2015-05-28 2015-06-01 4
[-0.043 -0.095]
Stress Events mean min max
Fall2015 -0.69% -7.48% 6.73%
New Normal 0.13% -8.02% 6.92%
Top 10 long positions of all time max
Equity(193 [002306.SZA]) 4.02%
Equity(314 [600217.SHA]) 3.96%
Equity(608 [600202.SHA]) 3.82%
Equity(1908 [000629.SZA]) 3.64%
Equity(2897 [000711.SZA]) 3.61%
Equity(2812 [600023.SHA]) 3.59%
Equity(2513 [002246.SZA]) 3.59%
Equity(1003 [000760.SZA]) 3.58%
Equity(2936 [600160.SHA]) 3.54%
Equity(292 [002040.SZA]) 3.52%
Top 10 short positions of all time max
Top 10 positions of all time max
Equity(193 [002306.SZA]) 4.02%
Equity(314 [600217.SHA]) 3.96%
Equity(608 [600202.SHA]) 3.82%
Equity(1908 [000629.SZA]) 3.64%
Equity(2897 [000711.SZA]) 3.61%
Equity(2812 [600023.SHA]) 3.59%
Equity(2513 [002246.SZA]) 3.59%
Equity(1003 [000760.SZA]) 3.58%
Equity(2936 [600160.SHA]) 3.54%
Equity(292 [002040.SZA]) 3.52%
All positions ever held max
Equity(193 [002306.SZA]) 4.02%
Equity(314 [600217.SHA]) 3.96%
Equity(608 [600202.SHA]) 3.82%
Equity(1908 [000629.SZA]) 3.64%
Equity(2897 [000711.SZA]) 3.61%
Equity(2812 [600023.SHA]) 3.59%
Equity(2513 [002246.SZA]) 3.59%
Equity(1003 [000760.SZA]) 3.58%
Equity(2936 [600160.SHA]) 3.54%
Equity(292 [002040.SZA]) 3.52%
Equity(2103 [601939.SHA]) 3.50%
Equity(1592 [601390.SHA]) 3.49%
Equity(52 [002473.SZA]) 3.48%
Equity(2188 [600200.SHA]) 3.46%
Equity(1942 [300420.SZA]) 3.40%
Equity(1415 [601288.SHA]) 3.40%
Equity(492 [600190.SHA]) 3.40%
Equity(2733 [601005.SHA]) 3.35%
Equity(1020 [600220.SHA]) 3.34%
Equity(1172 [603918.SHA]) 3.34%
Equity(1619 [600020.SHA]) 3.28%
Equity(2261 [600433.SHA]) 3.25%
Equity(2672 [300310.SZA]) 3.25%
Equity(1024 [300280.SZA]) 3.25%
Equity(3133 [600186.SHA]) 3.24%
Equity(981 [002191.SZA]) 3.24%
Equity(135 [603778.SHA]) 3.23%
Equity(916 [000910.SZA]) 3.23%
Equity(1329 [002529.SZA]) 3.21%
Equity(2092 [002736.SZA]) 3.21%
... ...
Equity(65 [002159.SZA]) 2.44%
Equity(1640 [300174.SZA]) 2.44%
Equity(2403 [002076.SZA]) 2.44%
Equity(1660 [002797.SZA]) 2.43%
Equity(826 [002044.SZA]) 2.43%
Equity(3150 [603421.SHA]) 2.42%
Equity(2356 [600885.SHA]) 2.42%
Equity(1957 [300528.SZA]) 2.42%
Equity(1406 [002491.SZA]) 2.41%
Equity(2792 [300317.SZA]) 2.41%
Equity(586 [600175.SHA]) 2.41%
Equity(3016 [603766.SHA]) 2.40%
Equity(1948 [600706.SHA]) 2.40%
Equity(1504 [000517.SZA]) 2.40%
Equity(1776 [002747.SZA]) 2.40%
Equity(2442 [600180.SHA]) 2.40%
Equity(786 [603128.SHA]) 2.39%
Equity(1258 [300410.SZA]) 2.38%
Equity(861 [002811.SZA]) 2.38%
Equity(417 [002474.SZA]) 2.36%
Equity(1622 [600116.SHA]) 2.30%
Equity(1737 [600106.SHA]) 2.29%
Equity(1090 [002128.SZA]) 2.19%
Equity(1182 [601139.SHA]) 2.10%
Equity(2055 [002751.SZA]) 2.00%
Equity(1467 [601618.SHA]) 1.93%
Equity(2393 [600242.SHA]) 1.36%
Equity(2858 [300183.SZA]) 1.12%
Equity(1842 [600354.SHA]) 1.09%
Equity(181 [600439.SHA]) 0.85%

1335 rows × 1 columns