Coverage for evaluation/overfitting.py: 100%

48 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Overfitting tests beyond PBO and the deflated Sharpe (V6.6.5, #345): how long a record must be, and how much of a 

2Sharpe ratio survives the number of trials that produced it. 

3 

4- `minimum_track_record_length`: Bailey & López de Prado (2012), "The Sharpe Ratio Efficient Frontier", eq. for MinTRL. 

5- `haircut_sharpe`: Harvey & Liu (2015), "Backtesting", the Bonferroni, Holm and BHY adjustments of a Sharpe ratio's 

6 p-value, for a strategy that is the best of `num_trials` (rank 1; the other trials' p-values are not needed then). 

7- `pbo` is `evaluation.pbo.probability_of_backtest_overfitting` (CSCV), under a short name. 

8 

9Only the standard library and numpy: `statistics.NormalDist` gives the normal quantiles. 

10""" 

11 

12from __future__ import annotations 

13 

14import math 

15from statistics import NormalDist 

16from typing import TYPE_CHECKING, Literal 

17 

18import numpy as np 

19 

20from evaluation.pbo import probability_of_backtest_overfitting 

21 

22if TYPE_CHECKING: 

23 from numpy.typing import ArrayLike 

24 

25__all__ = ["minimum_track_record_length", "haircut_sharpe", "pbo"] 

26 

27pbo = probability_of_backtest_overfitting 

28_NORMAL = NormalDist() 

29 

30 

31def _clean(returns) -> np.ndarray: 

32 values = np.asarray(returns, dtype=float).ravel() 

33 return values[np.isfinite(values)] 

34 

35 

36def minimum_track_record_length(returns: ArrayLike, *, target_sharpe: float = 0.0, confidence: float = 0.95, periods_per_year: int = 252) -> float: 

37 """Observations needed before the observed Sharpe beats `target_sharpe` (annual) at `confidence`, given the series' 

38 skew and kurtosis: `1 + (1 - g3*SR + (g4-1)/4*SR^2) * (z / (SR - SR*))^2` with per-period SR and raw kurtosis g4. 

39 `inf` when the observed Sharpe does not exceed the target; `nan` for fewer than 3 finite observations or zero variance.""" 

40 values = _clean(returns) 

41 if len(values) < 3 or not 0.0 < float(confidence) < 1.0: 

42 return float("nan") 

43 sd = float(values.std(ddof=1)) 

44 if not math.isfinite(sd) or sd == 0.0: 

45 return float("nan") 

46 sr = float(values.mean()) / sd 

47 target = float(target_sharpe) / math.sqrt(float(periods_per_year)) 

48 if sr <= target: 

49 return float("inf") 

50 centred = values - values.mean() 

51 m2 = float(np.mean(centred**2)) 

52 skew = float(np.mean(centred**3)) / m2**1.5 

53 kurtosis = float(np.mean(centred**4)) / m2**2 

54 z = _NORMAL.inv_cdf(float(confidence)) 

55 return 1.0 + (1.0 - skew * sr + (kurtosis - 1.0) / 4.0 * sr**2) * (z / (sr - target)) ** 2 

56 

57 

58def haircut_sharpe(sharpe: float, n_obs: int, num_trials: int, *, method: Literal["bonferroni", "holm", "bhy"] = "bhy", 

59 periods_per_year: int = 252) -> dict[str, float]: 

60 """The annual Sharpe that survives `num_trials`: its t-statistic `SR * sqrt(n_obs / periods_per_year)`, the two-sided 

61 p-value, the p-value adjusted for multiple testing, and the Sharpe implied by the adjusted p-value. 

62 

63 At rank 1, Holm equals Bonferroni (`p * M`) and BHY multiplies by `M * c(M)` with `c(M) = sum(1/i)`. Returns 

64 `{"sharpe", "haircut_sharpe", "haircut", "t_stat", "p_value", "adjusted_p_value"}`; a non-positive Sharpe gets a 100% haircut.""" 

65 if method not in ("bonferroni", "holm", "bhy"): 

66 raise ValueError("method must be 'bonferroni', 'holm' or 'bhy'") 

67 trials = max(int(num_trials), 1) 

68 years = max(float(n_obs), 0.0) / float(periods_per_year) 

69 sr = float(sharpe) 

70 if not math.isfinite(sr) or years <= 0.0: 

71 return {"sharpe": sr, "haircut_sharpe": 0.0, "haircut": 1.0, "t_stat": 0.0, "p_value": 1.0, "adjusted_p_value": 1.0} 

72 t_stat = sr * math.sqrt(years) 

73 p_value = 2.0 * (1.0 - _NORMAL.cdf(abs(t_stat))) 

74 factor = float(trials) 

75 if method == "bhy": 

76 factor *= sum(1.0 / i for i in range(1, trials + 1)) 

77 adjusted = min(p_value * factor, 1.0) 

78 if sr <= 0.0 or adjusted >= 1.0: 

79 haircut_sr = 0.0 

80 else: 

81 haircut_sr = _NORMAL.inv_cdf(1.0 - adjusted / 2.0) / math.sqrt(years) 

82 haircut_sr = min(haircut_sr, sr) if sr > 0 else 0.0 

83 return { 

84 "sharpe": sr, "haircut_sharpe": haircut_sr, "haircut": 1.0 - haircut_sr / sr if sr > 0 else 1.0, 

85 "t_stat": t_stat, "p_value": p_value, "adjusted_p_value": adjusted, 

86 }