Coverage for evaluation/benchmark_comparison.py: 100%
91 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"""V5.4.3 - benchmark comparison: computes naive baseline strategies
2(momentum, mean-reversion, random-entry) on the same dataset/window as the
3rank-book simulation, so the model's edge can be stated relative to simple
4benchmarks rather than in isolation.
6V5.4.4 - `run_all_baselines()` aggregates these with
7`public_benchmarks.py`'s SP500/60-40 baselines into the single report dict
8`aq evaluate --benchmarks` persists (and the README section + webui panel
9render). Pure: pandas/numpy only."""
11from __future__ import annotations
13import numpy as np
14import pandas as pd
17def momentum_baseline(
18 close_pivot: pd.DataFrame,
19 *,
20 lookback: int = 20,
21 top_n: int = 6,
22 bottom_n: int = 6,
23 forward_return_column: str = "target_return_1d",
24 rebalance_every: int = 10,
25) -> dict:
26 """Buy the `top_n` assets with the HIGHEST past `lookback`-day return;
27 sell short the `bottom_n` with the LOWEST. Rebalances every
28 `rebalance_every` unique dates. Equal-weight within each leg."""
29 mom = close_pivot / close_pivot.shift(lookback) - 1.0
30 dates = close_pivot.index.tolist()
31 rebalance_indices = list(range(0, len(dates), rebalance_every))
33 daily_returns = []
34 held_weights = {}
35 for di, date in enumerate(dates):
36 if di in rebalance_indices and di >= lookback:
37 row = mom.loc[date].dropna()
38 if len(row) < top_n + bottom_n:
39 held_weights = {}
40 else:
41 sorted_vals = row.sort_values(ascending=False)
42 longs = sorted_vals.head(top_n).index.tolist()
43 shorts = sorted_vals.tail(bottom_n).index.tolist()
44 w = 1.0 / max(top_n, 1)
45 held_weights = dict.fromkeys(longs, w)
46 for t in shorts:
47 held_weights[t] = -w
49 # Compute portfolio return from next day's close-to-close
50 if di + 1 < len(dates):
51 port_ret = 0.0
52 for ticker, weight in held_weights.items():
53 if ticker in close_pivot.columns and date in close_pivot.index:
54 cur_idx = close_pivot.index.get_loc(date)
55 nxt_idx = cur_idx + 1
56 if nxt_idx < len(close_pivot.index):
57 nxt = close_pivot.index[nxt_idx]
58 c0 = close_pivot.loc[date, ticker] if date in close_pivot.index and not pd.isna(close_pivot.loc[date, ticker]) else np.nan
59 c1 = close_pivot.loc[nxt, ticker] if nxt in close_pivot.index and not pd.isna(close_pivot.loc[nxt, ticker]) else np.nan
60 if not (pd.isna(c0) or pd.isna(c1) or c0 == 0):
61 port_ret += weight * (c1 / c0 - 1.0)
62 daily_returns.append(port_ret)
63 else:
64 daily_returns.append(0.0)
66 arr = np.array(daily_returns)
67 sharpe = float(arr.mean() / max(np.std(arr, ddof=1), 1e-12) * np.sqrt(252)) if len(arr) > 1 else 0.0
68 total_return = float(np.prod(1 + arr) - 1)
69 return {"strategy": "momentum", "net_sharpe": round(sharpe, 4), "total_return_pct": round(total_return * 100, 2)}
72def mean_reversion_baseline(
73 close_pivot: pd.DataFrame,
74 *,
75 lookback: int = 5,
76 top_n: int = 6,
77 bottom_n: int = 6,
78 rebalance_every: int = 10,
79) -> dict:
80 """Buy bottom-N by recent `lookback`-day return (mean-reversion);
81 sell short the top-N. Rebalances every `rebalance_every` unique dates.
82 Equal-weight within each leg. Same next-day close-to-close return
83 accrual as momentum_baseline above - V5.4.4 fix: this baseline
84 previously accrued a hardcoded placeholder (`weight_sum * 0.001`)
85 instead of realized returns, so its Sharpe was structurally 0.0 and
86 the "benchmark" row it contributed to the comparison table was
87 meaningless."""
88 ret = close_pivot.pct_change(periods=lookback, fill_method=None)
89 dates = close_pivot.index.tolist()
90 rebalance_indices = set(range(lookback, len(dates), rebalance_every))
92 daily_returns = []
93 held_weights = {}
94 for di, date in enumerate(dates):
95 if di in rebalance_indices:
96 row = ret.loc[date].dropna() if date in ret.index else pd.Series(dtype=float)
97 if len(row) >= top_n + bottom_n:
98 sorted_vals = row.sort_values(ascending=True)
99 longs = sorted_vals.head(top_n).index.tolist()
100 shorts = sorted_vals.tail(bottom_n).index.tolist()
101 w = 1.0 / max(top_n, 1)
102 held_weights = dict.fromkeys(longs, w)
103 for t in shorts:
104 held_weights[t] = -w
105 # Accrue NEXT day's close-to-close return on the held book (same
106 # convention as momentum_baseline: decide on today's close, earn
107 # today-close -> next-close).
108 if di + 1 < len(dates):
109 next_date = dates[di + 1]
110 port_ret = 0.0
111 for ticker, weight in held_weights.items():
112 if ticker in close_pivot.columns:
113 c0 = close_pivot.loc[date, ticker] if date in close_pivot.index else np.nan
114 c1 = close_pivot.loc[next_date, ticker] if next_date in close_pivot.index else np.nan
115 if not (pd.isna(c0) or pd.isna(c1) or c0 == 0):
116 port_ret += weight * (c1 / c0 - 1.0)
117 daily_returns.append(port_ret)
118 else:
119 daily_returns.append(0.0)
121 arr = np.array(daily_returns)
122 sharpe = float(arr.mean() / max(np.std(arr, ddof=1), 1e-12) * np.sqrt(252)) if len(arr) > 1 else 0.0
123 total_return = float(np.prod(1 + arr) - 1)
124 return {"strategy": "mean_reversion", "net_sharpe": round(sharpe, 4), "total_return_pct": round(total_return * 100, 2)}
127def random_entry_baseline(
128 tickers: list[str],
129 *,
130 n_days: int = 500,
131 top_n: int = 6,
132 bottom_n: int = 6,
133 seed: int = 42,
134 daily_vol: float = 0.01,
135) -> dict:
136 """Random entry/exit on the same universe with the same book shape.
137 Expected Sharpe ≈ 0; serves as a statistical floor."""
138 rng = np.random.default_rng(seed)
139 n_names = max(top_n + bottom_n, 1)
140 daily_vol_per_name = daily_vol / np.sqrt(n_names)
141 daily_port_vol = daily_vol_per_name * np.sqrt(n_names)
142 returns = rng.normal(0, daily_port_vol, n_days)
143 arr = np.asarray(returns)
144 sharpe = float(arr.mean() / max(np.std(arr, ddof=1), 1e-12) * np.sqrt(252)) if len(arr) > 1 else 0.0
145 total_return = float(np.prod(1 + arr) - 1)
146 return {"strategy": "random_entry", "net_sharpe": round(sharpe, 4), "total_return_pct": round(total_return * 100, 2)}
149def close_pivot_from_frame(
150 frame: pd.DataFrame,
151 *,
152 date_column: str = "date",
153 ticker_column: str = "ticker",
154 close_column: str = "close",
155) -> pd.DataFrame:
156 """(dates × tickers) close-price pivot from the long-format
157 full_dataset frame - the single input every baseline (strategy and
158 public) consumes. Empty pivot when the frame has no `close` column
159 (callers then get per-baseline SKIPPED results, never a crash).
160 `aggfunc="last"` keeps a (rare) duplicated (date, ticker) row from
161 raising - same degrade-don't-raise convention as the rest of this
162 package; dates sorted ascending so every baseline's window logic sees
163 chronological order regardless of the CSV's row order."""
164 if close_column not in frame.columns:
165 return pd.DataFrame()
166 pivot = frame.pivot_table(index=date_column, columns=ticker_column, values=close_column, aggfunc="last")
167 return pivot.sort_index()
170def run_all_baselines(
171 close_pivot: pd.DataFrame,
172 *,
173 n_days: int = 500,
174 seed: int = 42,
175) -> dict:
176 """Runs ALL five baselines over one close pivot - the three strategy
177 baselines above plus public_benchmarks' SP500 buy-and-hold and
178 daily-rebalanced 60-40 - into the report dict `aq evaluate
179 --benchmarks` persists. Every entry carries the same
180 strategy/net_sharpe/total_return_pct keys (public ones add `status`),
181 so the README table and webui panel can render them uniformly; a
182 baseline that can't compute (missing SPY/TLT, thin universe) degrades
183 to SKIPPED/None metrics inside its own entry without affecting the
184 others."""
185 from evaluation.public_benchmarks import compute_60_40_baseline, compute_sp500_baseline
187 tickers = list(close_pivot.columns)
188 baselines = [
189 momentum_baseline(close_pivot),
190 mean_reversion_baseline(close_pivot),
191 random_entry_baseline(tickers, n_days=n_days, seed=seed),
192 compute_sp500_baseline(close_pivot),
193 compute_60_40_baseline(close_pivot),
194 ]
195 return {"baselines": baselines}