Coverage for evaluation/public_benchmarks.py: 100%

44 statements  

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

1"""V5.4.4 - public benchmark baselines computed from the universe's own 

2index/bond proxies (SPY, TLT), so the rank book's edge can be stated 

3against well-known public benchmarks - not just against the naive 

4strategy baselines in evaluation/benchmark_comparison.py. 

5 

6No external API and no new data dependencies: both functions accept the 

7exact same (dates × tickers) close-price pivot that 

8benchmark_comparison::momentum_baseline() already consumes - SPY/TLT are 

9ordinary columns of `ml/datasets/full_dataset.csv`'s wide close table. 

10 

11- compute_sp500_baseline(): buy-and-hold SPY, close-to-close daily 

12 returns over the pivot's own window. 

13- compute_60_40_baseline(): the classic 60% SPY / 40% TLT portfolio, 

14 DAILY rebalanced (weights reset to 60/40 every day, so the portfolio 

15 return is just the fixed-weight blend of the two legs' daily returns - 

16 no drift compounding of the weights themselves). 

17 

18Pure pandas/numpy, no I/O, no torch. Missing tickers degrade to a 

19SKIPPED status (None metrics) instead of raising - the same 

20"missing data never changes behavior, never crashes" convention the 

21rest of this package follows. Output keys mirror the existing baselines' 

22`{"strategy", "net_sharpe", "total_return_pct"}` shape, plus an 

23additive `status` field ("OK" / "SKIPPED: <reason>") since - unlike the 

24strategy baselines, which work on any universe - these two CAN be 

25uncomputable (a universe without SPY, or without TLT for the 60-40). 

26""" 

27 

28from __future__ import annotations 

29 

30import numpy as np 

31import pandas as pd 

32 

33SP500_PROXY_TICKER = "SPY" 

34BOND_PROXY_TICKER = "TLT" 

35SP500_WEIGHT = 0.60 

36BOND_WEIGHT = 0.40 

37 

38 

39def _daily_close_returns(close_pivot: pd.DataFrame, ticker: str) -> pd.Series: 

40 """Close-to-close daily returns for one ticker, non-finite/zero-close 

41 rows degraded to NaN and dropped (a 0 close would otherwise produce 

42 inf via division).""" 

43 if ticker not in close_pivot.columns: 

44 return pd.Series(dtype=float) 

45 closes = pd.to_numeric(close_pivot[ticker], errors="coerce") 

46 closes = closes.where(closes > 0.0) 

47 # fill_method=None (never pad): a NaN close must produce NaN returns 

48 # that drop out below, not silently extend the last real close across 

49 # a gap (which would fabricate flat 0.0% return days). 

50 returns = closes.pct_change(fill_method=None) 

51 return returns.replace([np.inf, -np.inf], np.nan).dropna() 

52 

53 

54def _sharpe(daily_returns: pd.Series) -> float: 

55 """Annualized Sharpe of a daily-return series - the identical formula 

56 every baseline in evaluation/benchmark_comparison.py uses 

57 (mean / std(ddof=1) * sqrt(252), 0.0 when fewer than 2 observations), 

58 so benchmark numbers produced by the two modules can never disagree 

59 on what "Sharpe" means.""" 

60 arr = np.asarray(daily_returns, dtype=float) 

61 if arr.size < 2: 

62 return 0.0 

63 std = float(np.std(arr, ddof=1)) 

64 if std <= 0.0: 

65 return 0.0 

66 return float(np.mean(arr) / std * np.sqrt(252.0)) 

67 

68 

69def _result(strategy: str, daily_returns: pd.Series) -> dict: 

70 sharpe = _sharpe(daily_returns) 

71 total_return = float(np.prod(1.0 + np.asarray(daily_returns, dtype=float)) - 1.0) if daily_returns.size else 0.0 

72 return { 

73 "strategy": strategy, 

74 "net_sharpe": round(sharpe, 4), 

75 "total_return_pct": round(total_return * 100.0, 2), 

76 "status": "OK", 

77 } 

78 

79 

80def _skipped(strategy: str, reason: str) -> dict: 

81 return { 

82 "strategy": strategy, 

83 "net_sharpe": None, 

84 "total_return_pct": None, 

85 "status": f"SKIPPED: {reason}", 

86 } 

87 

88 

89def compute_sp500_baseline(close_pivot: pd.DataFrame) -> dict: 

90 """Buy-and-hold SPY over close_pivot's own window: close-to-close 

91 daily returns, annualized Sharpe + cumulative total return. Same 

92 window, same Sharpe formula as the strategy baselines - the numbers 

93 are directly comparable by construction.""" 

94 returns = _daily_close_returns(close_pivot, SP500_PROXY_TICKER) 

95 if returns.empty: 

96 return _skipped("sp500", f"no usable {SP500_PROXY_TICKER} closes in close_pivot") 

97 return _result("sp500", returns) 

98 

99 

100def compute_60_40_baseline(close_pivot: pd.DataFrame) -> dict: 

101 """60% SPY + 40% TLT, daily rebalanced: each day's portfolio return is 

102 `0.6 * spy_ret + 0.4 * tlt_ret` (fixed-weight blend, weights reset 

103 every day - the textbook daily-rebalanced 60-40). Requires BOTH 

104 proxies present; either one missing skips the whole benchmark rather 

105 than silently computing a different allocation.""" 

106 spy_returns = _daily_close_returns(close_pivot, SP500_PROXY_TICKER) 

107 tlt_returns = _daily_close_returns(close_pivot, BOND_PROXY_TICKER) 

108 if spy_returns.empty or tlt_returns.empty: 

109 missing = SP500_PROXY_TICKER if spy_returns.empty else BOND_PROXY_TICKER 

110 return _skipped("60_40", f"no usable {missing} closes in close_pivot") 

111 aligned = pd.concat( 

112 {"spy": spy_returns, "tlt": tlt_returns}, axis=1, join="inner" 

113 ).dropna() 

114 if aligned.empty: 

115 return _skipped("60_40", f"no overlapping {SP500_PROXY_TICKER}/{BOND_PROXY_TICKER} return dates") 

116 portfolio_returns = SP500_WEIGHT * aligned["spy"] + BOND_WEIGHT * aligned["tlt"] 

117 return _result("60_40", portfolio_returns)