Coverage for evaluation/pbo.py: 100%
40 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Probability of backtest overfitting by combinatorially symmetric cross-validation (V6.4.3; Bailey, Borwein,
2López de Prado and Zhu, "The Probability of Backtest Overfitting", J. Computational Finance 2017).
4`returns` is T x N: the daily returns of N trials (variants scored on the same dates). The rows are cut into `blocks`
5contiguous blocks; for every way to pick half of them as in-sample, the trial with the best in-sample Sharpe is taken
6and its out-of-sample rank among the N trials recorded. PBO is the share of splits where that trial lands in the bottom
7half out of sample (logit of its relative rank <= 0). A selection process with real skill gives PBO well below 0.5;
8picking the best of N noise variants gives about 0.5. Pure numpy.
9"""
11from __future__ import annotations
13import itertools
14import math
15from typing import TYPE_CHECKING, Any
17import numpy as np
19if TYPE_CHECKING:
20 from numpy.typing import ArrayLike
23def _sharpe(block_sums: np.ndarray, block_sq: np.ndarray, block_n: np.ndarray, mask: np.ndarray, periods: int) -> np.ndarray:
24 n = block_n[mask].sum()
25 total = block_sums[mask].sum(axis=0)
26 total_sq = block_sq[mask].sum(axis=0)
27 mean = total / n
28 variance = np.maximum(total_sq / n - mean**2, 0.0) * n / max(n - 1, 1)
29 std = np.sqrt(variance)
30 with np.errstate(divide="ignore", invalid="ignore"):
31 sharpe = np.where(std > 0, mean / std * math.sqrt(periods), 0.0)
32 return sharpe
35def probability_of_backtest_overfitting(returns: ArrayLike, *, blocks: int = 16, periods_per_year: int = 252) -> dict[str, Any]:
36 """{"pbo", "num_combinations", "num_trials", "lambda_quantiles", "degradation_slope", "degradation_intercept",
37 "prob_oos_loss"}; `pbo` is None when there are fewer than 2 trials or fewer rows than blocks."""
38 matrix = np.asarray(returns, dtype=float)
39 if matrix.ndim != 2 or matrix.shape[1] < 2 or matrix.shape[0] < blocks or blocks < 2 or blocks % 2:
40 return {"pbo": None, "num_combinations": 0, "num_trials": int(matrix.shape[1]) if matrix.ndim == 2 else 0}
41 matrix = np.nan_to_num(matrix, nan=0.0)
42 num_rows, num_trials = matrix.shape
43 edges = np.linspace(0, num_rows, blocks + 1).astype(int)
44 block_sums = np.array([matrix[a:b].sum(axis=0) for a, b in itertools.pairwise(edges)])
45 block_sq = np.array([(matrix[a:b] ** 2).sum(axis=0) for a, b in itertools.pairwise(edges)])
46 block_n = np.array([b - a for a, b in itertools.pairwise(edges)], dtype=float)
48 lambdas, is_best, oos_of_best = [], [], []
49 for chosen in itertools.combinations(range(blocks), blocks // 2):
50 mask = np.zeros(blocks, dtype=bool)
51 mask[list(chosen)] = True
52 in_sample = _sharpe(block_sums, block_sq, block_n, mask, periods_per_year)
53 out_sample = _sharpe(block_sums, block_sq, block_n, ~mask, periods_per_year)
54 best = int(np.argmax(in_sample))
55 rank = float((out_sample < out_sample[best]).sum() + 0.5 * ((out_sample == out_sample[best]).sum() - 1) + 1)
56 omega = rank / (num_trials + 1)
57 lambdas.append(math.log(omega / (1.0 - omega)))
58 is_best.append(float(in_sample[best]))
59 oos_of_best.append(float(out_sample[best]))
60 lambdas_array = np.array(lambdas)
61 slope, intercept = (np.polyfit(is_best, oos_of_best, 1) if np.ptp(is_best) > 0 else (0.0, float(np.mean(oos_of_best))))
62 return {
63 "pbo": float((lambdas_array <= 0.0).mean()),
64 "num_combinations": len(lambdas),
65 "num_trials": num_trials,
66 "num_rows": num_rows,
67 "blocks": blocks,
68 "lambda_quantiles": {str(q): float(np.quantile(lambdas_array, q)) for q in (0.1, 0.25, 0.5, 0.75, 0.9)},
69 "degradation_slope": float(slope),
70 "degradation_intercept": float(intercept),
71 "prob_oos_loss": float((np.array(oos_of_best) < 0.0).mean()),
72 }