"""backtest-overfitting-treasury-rules.py - the deflated Sharpe ratio and the probability of backtest overfitting on a real rule family: 200 moving-average rules that hold a 10-year Treasury note or 3-month bills. Inputs : datasets/backtest-overfitting-treasury-yields.csv (date, DGS10, DTB3 in percent, as downloaded from FRED on 2026-11-21; blank = no value that day). No network request. Returns: on dates where both yields exist, holding yesterday's 10-year par note (coupon = yesterday's yield, paid semiannually) for one row earns P(y_today) - 1 plus yesterday's yield x days/365 of accrued coupon, where P is the price of that note at today's yield (maturity shortening ignored). Bills earn yesterday's DTB3 x days/360. Excess return = note - bills. Rules : s in 1..20 by L in (30, 40, 50, 60, 80, 100, 120, 150, 200, 250): hold the note on day t when the s-row average of DGS10 through t-1 is below the L-row average through t-1, else hold bills. Rule return = position x excess return. 200 rules, no look-ahead. Split : in-sample = first evaluation day .. 1994-12-31, out-of-sample = 1995-01-01 .. last day. Output : Markdown tables and the figures quoted in the article. The design was fixed before the first run. Run : python code/backtest-overfitting-treasury-rules.py [path/to/backtest-overfitting-treasury-yields.csv] Needs : Python 3.13, numpy 2.3. """ import csv import itertools import math import sys from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent DATA = Path(sys.argv[1]) if len(sys.argv) > 1 else HERE.parent / "datasets" / "backtest-overfitting-treasury-yields.csv" SHORT = tuple(range(1, 21)) LONG = (30, 40, 50, 60, 80, 100, 120, 150, 200, 250) SPLIT = "1995-01-01" S = 16 GAMMA = 0.5772156649 def norm_cdf(x): return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0))) def norm_ppf(p): lo, hi = -10.0, 10.0 for _ in range(200): mid = (lo + hi) / 2 if norm_cdf(mid) < p: lo = mid else: hi = mid return (lo + hi) / 2 def expected_max_sr(n, var_sr): if n <= 1: return 0.0 return math.sqrt(var_sr) * ((1 - GAMMA) * norm_ppf(1 - 1 / n) + GAMMA * norm_ppf(1 - 1 / (n * math.e))) def dsr_z(sr_hat, sr0, t, skew, kurt): return (sr_hat - sr0) * math.sqrt(t - 1) / math.sqrt(1 - skew * sr_hat + (kurt - 1) / 4 * sr_hat ** 2) def dsr(sr_hat, sr0, t, skew, kurt): return norm_cdf(dsr_z(sr_hat, sr0, t, skew, kurt)) def moments(r): m, s = r.mean(), r.std(ddof=0) return float(((r - m) ** 3).mean() / s ** 3), float(((r - m) ** 4).mean() / s ** 4) def sharpe(x): """daily Sharpe of each column""" return x.mean(axis=0) / x.std(axis=0, ddof=1) def ranks(v): """ascending ranks 1..n, ties get their average rank""" return np.array([(v < x).sum() + ((v == x).sum() + 1) / 2 for x in v]) def load(): dates, y10, b3 = [], [], [] with DATA.open(encoding="utf-8", newline="") as f: for row in csv.DictReader(f): if row["DGS10"] and row["DTB3"]: dates.append(row["date"]) y10.append(float(row["DGS10"])) b3.append(float(row["DTB3"])) return np.array(dates), np.array(y10), np.array(b3) def main(): dates, y10, b3 = load() day = np.array([np.datetime64(d) for d in dates]) gap = (day[1:] - day[:-1]).astype(int) # calendar days held, row t-1 -> t c = y10[:-1] / 100 y = y10[1:] / 100 price = c / y * (1 - (1 + y / 2) ** -20) + (1 + y / 2) ** -20 note = price - 1 + c * gap / 365 bills = b3[:-1] / 100 * gap / 360 excess = note - bills # return of row t = 1..n-1 # moving averages through t-1, compared exactly: yields in basis points (integers), cumulative sums, and # "s-row average < L-row average" tested as sum_s * L < sum_L * s, so flat stretches never tie by rounding cs = np.concatenate([[0], np.cumsum(np.rint(y10 * 100).astype(np.int64))]) def below(s, L, upto): # s-row average of y10[..upto] < L-row average return (cs[upto + 1] - cs[upto + 1 - s]) * L < (cs[upto + 1] - cs[upto + 1 - L]) * s first = max(LONG) - 1 # y10 index of the first t-1 with a 250-row average prev = np.arange(first, len(y10) - 1) # t-1 indices; return index = prev (excess[prev] is row prev+1) rdates = dates[prev + 1] rules = list(itertools.product(SHORT, LONG)) X = np.empty((len(prev), len(rules))) for j, (s, L) in enumerate(rules): pos = below(s, L, prev).astype(float) X[:, j] = pos * excess[prev] hold = excess[prev] ins = rdates < SPLIT T_is, T_oos = int(ins.sum()), int((~ins).sum()) print(f"rows with both yields: {len(dates)} ({dates[0]} .. {dates[-1]}); evaluation rows {len(prev)} " f"({rdates[0]} .. {rdates[-1]}); in-sample {T_is} ({rdates[ins][0]} .. {rdates[ins][-1]}), " f"out-of-sample {T_oos} ({rdates[~ins][0]} .. {rdates[~ins][-1]})") A = math.sqrt(252) sr_is, sr_oos = sharpe(X[ins]), sharpe(X[~ins]) k = int(np.argmax(sr_is)) s_k, L_k = rules[k] sk, ku = moments(X[ins][:, k]) var_sr = float(sr_is.var(ddof=1)) corr = np.corrcoef(X[ins], rowvar=False) M = len(rules) rho = float((corr.sum() - M) / (M * (M - 1))) n_hat = rho + (1 - rho) * M sr0_200, sr0_hat = expected_max_sr(M, var_sr), expected_max_sr(n_hat, var_sr) oos_rank = int((sr_oos < sr_oos[k]).sum()) + 1 rho_s = float(np.corrcoef(ranks(sr_is), ranks(sr_oos))[0, 1]) pos_k = below(s_k, L_k, prev) print("\nin-sample selection") print(f" winner: s = {s_k}, L = {L_k}; in the note {100 * pos_k[ins].mean():.1f}% of in-sample days, " f"{100 * pos_k[~ins].mean():.1f}% out of sample") print(f" in-sample Sharpe: winner {sr_is[k]:.4f} daily ({sr_is[k] * A:.2f} annualised); median rule " f"{np.median(sr_is) * A:.2f}; worst {sr_is.min() * A:.2f}; always in the note {sharpe(hold[ins][:, None])[0] * A:.2f}") print(f" winner skew {sk:.3f}, kurtosis {ku:.3f}; variance of the 200 daily Sharpes {var_sr:.3e}") print(f" average correlation of the 200 in-sample return series {rho:.4f}; implied independent trials {n_hat:.1f}") print(f" SR0 (N = 200) {sr0_200:.4f} daily ({sr0_200 * A:.2f} annualised); DSR {dsr(sr_is[k], sr0_200, T_is, sk, ku):.3f}") print(f" SR0 (N = {n_hat:.1f}) {sr0_hat:.4f} daily ({sr0_hat * A:.2f} annualised); DSR {dsr(sr_is[k], sr0_hat, T_is, sk, ku):.3f}") print(f" z inside the DSR: N = 200 {dsr_z(sr_is[k], sr0_200, T_is, sk, ku):.2f}, N = {n_hat:.1f} " f"{dsr_z(sr_is[k], sr0_hat, T_is, sk, ku):.2f}, N = 1 {dsr_z(sr_is[k], 0.0, T_is, sk, ku):.2f}") print(f" naive p-value against zero {1 - norm_cdf(sr_is[k] * math.sqrt(T_is - 1)):.2e}; DSR with N = 1 " f"{dsr(sr_is[k], 0.0, T_is, sk, ku):.3f}") print("\nout of sample") print(f" winner {sr_oos[k] * A:.2f} annualised, rank {oos_rank} of {M} (1 = worst); median rule " f"{np.median(sr_oos) * A:.2f}; best {sr_oos.max() * A:.2f} (s = {rules[int(np.argmax(sr_oos))][0]}, " f"L = {rules[int(np.argmax(sr_oos))][1]}); always in the note {sharpe(hold[~ins][:, None])[0] * A:.2f}") print(f" in-sample: rules above SR0 (N = 200): {int((sr_is > sr0_200).sum())} of {M}; selection premium " f"(winner minus median, annualised) {(sr_is[k] - np.median(sr_is)) * A:.2f} in sample, " f"{(sr_oos[k] - np.median(sr_oos)) * A:.2f} out of sample") print(f" this split as one CSCV-style draw: rank {oos_rank} of {M}, logit {math.log(oos_rank / (M + 1 - oos_rank)):.2f}") print(f" rules with a higher out-of-sample Sharpe than in-sample: {int((sr_oos > sr_is).sum())} of {M}") print(f" Spearman rank correlation, in-sample vs out-of-sample Sharpe across the 200 rules: {rho_s:.3f}") print("\n| | in-sample (to 1994) | out of sample (1995 on) |") print("|---|---|---|") print(f"| winner, s = {s_k} / L = {L_k} | {sr_is[k] * A:.2f} | {sr_oos[k] * A:.2f} |") print(f"| median of the 200 rules | {np.median(sr_is) * A:.2f} | {np.median(sr_oos) * A:.2f} |") print(f"| always in the note | {sharpe(hold[ins][:, None])[0] * A:.2f} | {sharpe(hold[~ins][:, None])[0] * A:.2f} |") # CSCV n_rows = (len(prev) // S) * S Y = X[len(prev) - n_rows:] blk = Y.reshape(S, n_rows // S, M) bsum, bsq, m = blk.sum(axis=1), (blk ** 2).sum(axis=1), n_rows // S combos = list(itertools.combinations(range(S), S // 2)) logits, loss, ties, deg = [], 0, 0, [] for cmb in combos: tr = np.zeros(S, bool) tr[list(cmb)] = True out = [] for part in (tr, ~tr): n = m * S // 2 mu = bsum[part].sum(axis=0) / n var = (bsq[part].sum(axis=0) - n * mu ** 2) / (n - 1) out.append(mu / np.sqrt(var)) a_is, a_oos = out n_star = int(np.argmax(a_is)) r = int((a_oos < a_oos[n_star]).sum()) + 1 ties += int((a_oos == a_oos[n_star]).sum()) - 1 w = r / (M + 1) logits.append(math.log(w / (1 - w))) if cmb == tuple(range(S // 2)): fwd_star = (n_star, r) loss += a_oos[n_star] < 0 deg.append((a_is[n_star], a_oos[n_star])) logits = np.array(logits) # added after the first run: the one split whose training blocks all come before its test blocks fwd = combos.index(tuple(range(S // 2))) print(f"\nforward split (blocks 1-{S // 2} train, to {rdates[len(prev) - n_rows + m * S // 2 - 1]}; " f"blocks {S // 2 + 1}-{S} test): winner s = {rules[fwd_star[0]][0]}, L = {rules[fwd_star[0]][1]}, " f"test rank {fwd_star[1]} of {M}, logit {logits[fwd]:.2f}; splits with a lower logit " f"{int((logits < logits[fwd]).sum())} ({100 * (logits < logits[fwd]).mean():.1f}%)") d = np.array(deg) slope = float(np.polyfit(d[:, 0], d[:, 1], 1)[0]) print(f"\nCSCV: S = {S} blocks of {m} rows ({n_rows} rows from {rdates[len(prev) - n_rows]}; first " f"{len(prev) - n_rows} rows dropped); {len(combos)} splits; ties at the selected rule's test Sharpe: {ties}") print(f" PBO = {100 * (logits < 0).mean():.1f}% of splits; median logit {np.median(logits):.2f}; " f"probability of loss {100 * loss / len(combos):.1f}%") print(f" selected rule's test Sharpe: median {np.median(d[:, 1]) * A:.2f} annualised vs train median " f"{np.median(d[:, 0]) * A:.2f}; slope of test on train Sharpe {slope:.2f}") print(f" splits where the selected rule ranked in the top half of the test half: {int((logits > 0).sum())}") if __name__ == "__main__": main()