Coverage for notebooks/src/03_overfitting_tests.py: 100%

67 statements  

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

1# %% [markdown] 

2# # Overfitting tests: how much of a Sharpe ratio survives the search? 

3# 

4# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/leon1706-lol/Aether-quant/blob/main/notebooks/03_overfitting_tests.ipynb) 

5# 

6# Every backtest is the winner of some search. This notebook runs the project's checks on a 16-variant grid of the shipped trend rule: 

7# 

8# 1. **PBO by CSCV.** How often does the in-sample winner lose out of sample? 

9# 2. **Deflated Sharpe.** The best Sharpe is judged against the best expected from N trials. This shows how fast it falls as N grows. 

10# 3. **Minimum track record and the haircut Sharpe.** How long a record has to be, and what Sharpe is left after Bonferroni, Holm or BHY. 

11# 4. **A placebo test.** 

12# 5. **Holdout discipline.** A holdout read once, and a second read refused. 

13# 6. **Generations.** Capital moves from an old model to a new one by evidence, not all at once. 

14 

15# %% 

16import sys 

17from pathlib import Path 

18 

19if "google.colab" in sys.modules: # Colab: install the library (numpy and pandas come with it) 

20 get_ipython().run_line_magic("pip", 'install -q "aether-quant[notebooks]"') # noqa: F821 

21else: # a clone: run against the checkout's code 

22 for parent in (Path.cwd(), *Path.cwd().parents): 

23 if (parent / "aether_quant" / "__init__.py").is_file(): 

24 sys.path.insert(0, str(parent)) 

25 break 

26 

27# %% 

28from itertools import product 

29 

30import numpy as np 

31import pandas as pd 

32 

33from aether_quant import backtest, costs, hello, overfitting, samples 

34 

35closes = samples.load_sample_prices() 

36start, end = "2022-01-01", "2026-10-31" 

37window = closes.loc[start:end] 

38grid = {} 

39for lookback_a, lookback_c in product((10, 20, 30, 40), (90, 120, 150, 180)): 

40 weights = hello.rule_weights(closes, start=start, end=end, params={"lookback_a": lookback_a, "lookback_b": 60, "lookback_c": lookback_c}) 

41 run = backtest.backtest(weights.reindex(window.index), window, fill="close", cost_model=costs.coinbase_model(), periods_per_year=365, min_weight_change=0.002) 

42 grid[f"a{lookback_a}_c{lookback_c}"] = run.returns.iloc[1:] 

43returns = pd.DataFrame(grid) 

44sharpes = returns.apply(lambda column: backtest.summary_statistics(column, periods_per_year=365)["sharpe_ratio"]) 

45print(f"{returns.shape[1]} variants, {len(returns)} days; best Sharpe {sharpes.max():.2f} ({sharpes.idxmax()}), median {sharpes.median():.2f}") 

46 

47# %% [markdown] 

48# ## 1. PBO by combinatorially symmetric cross-validation 

49# 

50# The history is cut into blocks. For every way of choosing half the blocks as in-sample, the best in-sample variant is ranked out of sample. PBO is the share of splits where it lands below the median. 

51 

52# %% 

53usable = len(returns) - len(returns) % 8 

54result = overfitting.pbo(returns.to_numpy()[-usable:], blocks=8, periods_per_year=365) 

55print(f"PBO {result['pbo']:.2f}: the best-looking variant lands in the bottom half out of sample {result['pbo']:.0%} of the time") 

56pd.Series({key: value for key, value in result.items() if isinstance(value, (int, float))}).round(3) 

57 

58# %% [markdown] 

59# ## 2. The deflated Sharpe falls as the number of trials grows 

60# 

61# The same best variant, judged against the maximum Sharpe expected from N trials with this grid's spread of Sharpes. The project's own record, `RESEARCH_TRIALS`, is marked on the curve. 

62 

63# %% 

64import matplotlib.pyplot as plt 

65 

66from aether_quant.hello import RESEARCH_TRIALS 

67 

68best = returns[sharpes.idxmax()].to_numpy() 

69variance = float(np.var(sharpes, ddof=1)) 

70curve = pd.Series({n: overfitting.deflated_sharpe_from_inputs(best, num_trials=n, trial_variance=variance, annualization=365)["value"] for n in sorted({2, 5, 10, 16, 50, 100, 500, RESEARCH_TRIALS})}) 

71print(f"the project's own record: {RESEARCH_TRIALS} pre-registered trials") 

72print(f"PSR of the best variant against 0: {overfitting.probabilistic_sharpe_ratio(best, 0.0):.1%}") 

73axes = curve.plot(marker="o", logx=True, figsize=(7, 3.2), title="Deflated Sharpe of the best variant by number of trials") 

74axes.axhline(0.95, color="#d97706", linestyle="--", linewidth=0.8) 

75plt.show() 

76 

77# %% [markdown] 

78# ## 3. Minimum track record length and the haircut Sharpe 

79 

80# %% 

81rows = {} 

82for method in ("bonferroni", "holm", "bhy"): 

83 cut = overfitting.haircut_sharpe(float(sharpes.max()), len(best), RESEARCH_TRIALS, method=method, periods_per_year=365) 

84 rows[method] = {"Sharpe": cut["sharpe"], "haircut Sharpe": cut["haircut_sharpe"], "haircut": cut["haircut"], "adjusted p": cut["adjusted_p_value"]} 

85print(f"Minimum track record for Sharpe > 0 at 95%: {overfitting.minimum_track_record_length(best, periods_per_year=365) / 365:.1f} years (the sample has {len(best) / 365:.1f})") 

86pd.DataFrame(rows).T.round(3) 

87 

88# %% [markdown] 

89# ## 4. A placebo test 

90# 

91# Shift the decisions by a random number of days, many times. A real timing signal should beat most of its own shifted copies. The p-value counts the observation itself, so it is never exactly zero. 

92 

93# %% 

94rng = np.random.default_rng(7) 

95weights = hello.rule_weights(closes, start=start, end=end) 

96observed = backtest.backtest(weights.reindex(window.index), window, fill="close", cost_model=costs.coinbase_model(), periods_per_year=365).stats()["sharpe_ratio"] 

97placebos = [] 

98for _ in range(30): 

99 shift = int(rng.integers(30, 300)) 

100 shifted = weights.reindex(window.index).shift(shift) 

101 placebos.append(backtest.backtest(shifted, window, fill="close", cost_model=costs.coinbase_model(), periods_per_year=365).stats()["sharpe_ratio"]) 

102print(f"observed Sharpe {observed:.2f}; placebo p-value {overfitting.placebo_p_value(observed, placebos):.2f} over {len(placebos)} time shifts") 

103 

104# %% [markdown] 

105# ## 5. A holdout is read once 

106# 

107# The project's research rounds write every holdout read to a ledger before the read. A second read of the same cell is refused, so nobody can peek at the holdout and then try again. 

108 

109# %% 

110import tempfile 

111 

112from aether_quant import cycle 

113 

114ledger = Path(tempfile.mkdtemp()) / "holdout_ledger.jsonl" 

115cycle.record_holdout_read(ledger, candidate="my_signal", cells=("V1",), digest="abc", created_at="2026-11-08T12:00:00Z") 

116try: 

117 cycle.record_holdout_read(ledger, candidate="my_signal_v2", cells=("V1",), digest="def", created_at="2026-11-09T12:00:00Z") 

118except PermissionError as refused: 

119 print("refused:", refused) 

120 

121# %% [markdown] 

122# ## 6. Generations hand over by evidence 

123# 

124# A new model starts at a small share and gains capital on a fixed glide. A tripped guard takes its risk off at once. 

125 

126# %% 

127policy = cycle.GlidePolicy(glide_sessions=252, entry_share=0.30, retire_share=0.05) 

128shares, path = {"old": 1.0, "new": 0.0}, [] 

129for _session in range(300): 

130 shares = cycle.update_generation_shares(shares, {"old": "active", "new": "ramping"}, {}, {}, policy) 

131 path.append(dict(shares)) 

132axes = pd.DataFrame(path).plot(figsize=(7, 3), title="Capital share by session") 

133plt.show() 

134 

135# %% [markdown] 

136# *Nothing in this project has passed these tests yet: every pre-registered trial (`RESEARCH_TRIALS` of them) without a survivor, and the holdouts still unread. That is the point of running them.*