使用 Bootstrap 指标评估

自助法指标通过模拟广泛的潜在市场情形,对交易策略进行更全面的评估。与依赖单一历史路径不同,这种方法能够揭示你的优势有多稳健。

在上一篇文档中,我们实现并回测了一个交易策略。下面再次给出该实现:

[1]:
import pybroker
from pybroker import Strategy, StrategyConfig, YFinance

pybroker.enable_data_source_cache("my_strategy")


def buy_low(ctx):
    if ctx.long_pos():
        return
    if ctx.bars >= 2 and ctx.close[-1] < ctx.low[-2]:
        ctx.buy_shares = ctx.calc_target_shares(0.25)
        ctx.buy_limit_price = ctx.close[-1] - 0.01
        ctx.hold_bars = 3


def short_high(ctx):
    if ctx.short_pos():
        return
    if ctx.bars >= 2 and ctx.close[-1] > ctx.high[-2]:
        ctx.sell_shares = 100
        ctx.hold_bars = 2

与之前一样,我们使用给定的配置创建一个新的 Strategy 实例:

[2]:
config = StrategyConfig(initial_cash=500_000)
strategy = Strategy(YFinance(), "3/1/2017", "3/1/2022", config)
strategy.add_execution(buy_low, ["AAPL", "MSFT"])
strategy.add_execution(short_high, ["TSLA"])

接下来,我们运行启用了自助法指标的回测:

[3]:
result = strategy.backtest(calc_bootstrap=True)
result.metrics_df.head(20)
Backtesting: 2017-03-01 00:00:00 to 2022-03-01 00:00:00

Loaded cached bar data.

Test split: 2017-03-01 00:00:00 to 2022-02-28 00:00:00
100% (1259 of 1259) |####################| Elapsed Time: 0:00:00 Time:  0:00:00

Calculating bootstrap metrics: bars=1258, samples=10000...
Calculated bootstrap metrics: 0:00:03

Finished backtest: 0:00:03
[3]:
name value
0 trade_count 388
1 initial_market_value 500000.0
2 end_market_value 664961.55
3 total_pnl 165782.88
4 unrealized_pnl -821.33
5 total_return_pct 33.156576
6 total_profit 401998.21
7 total_loss -236215.33
8 total_fees 0.0
9 max_drawdown -31619.46
10 max_drawdown_pct -4.723114
11 max_drawdown_date 2021-03-08 00:00:00
12 win_rate 52.57732
13 loss_rate 47.42268
14 winning_trades 204
15 losing_trades 184
16 avg_pnl 427.275464
17 avg_return_pct 0.279691
18 avg_trade_bars 2.414948
19 avg_profit 1970.579461

尽管上面的 total_pnl 指标显示这是一个盈利的策略,但这些结果可能只是偶然所致。为了提高我们评估结果的可信度,我们可以使用 自助法 来计算指标。

自助法的原理是从回测的收益率中抽取数千个随机样本,对每个样本计算指标,然后取其平均值,从而获得更稳健、更准确的绩效估计。

置信区间

PyBroker 使用自助法为两个绩效指标计算 置信区间利润因子夏普比率

[4]:
result.bootstrap.conf_intervals
[4]:
lower upper
name conf
Profit Factor 97.5% 1.000563 1.729250
95% 1.047317 1.655710
90% 1.102600 1.577968
Sharpe Ratio 97.5% 0.002662 0.107693
95% 0.012395 0.100330
90% 0.022551 0.091530

PyBroker 使用 偏差校正加速(BCa)自助法 计算这些指标的置信区间。收益率按每根 K 线而非每笔交易抽样,以捕捉更精细的数据。

生成的表格显示了在指定置信水平下置信区间的下限,从而对策略表现给出更保守的估计。例如,我们可以有 97.5% 的把握认为夏普比率达到或超过给定值 x

在这个例子中,夏普比率的下界为负,利润因子的下界小于 1,这表明策略是不可靠的。

最大回撤

接下来,我们使用自助法评估策略的最大回撤。回撤不超过特定阈值(分别以现金和投资组合权益百分比表示)的概率如下所示:

[5]:
result.bootstrap.drawdown_conf
[5]:
amount percent
conf
99.9% -158296.67 -23.102260
99% -120473.80 -18.246816
95% -93497.76 -14.288488
90% -80211.20 -12.444896

这些置信水平是根据回测的样本外结果中的每根 K 线收益率获得的,类似于计算利润因子和夏普比率的方法。

我们可以观察到,在 99.9% 置信水平下,自助法得出的最大回撤为 -23.1%,比我们原始结果中看到的 -4.7% 更严重。这凸显了使用随机化测试来评估交易策略表现的重要性。

在下一篇文档中,我们将讨论如何在交易策略中结合多空信号排名