diff --git a/bench/BENCH_COEVOLUTION_GLM53_2025_2026.md b/bench/BENCH_COEVOLUTION_GLM53_2025_2026.md new file mode 100644 index 0000000..f1952ac --- /dev/null +++ b/bench/BENCH_COEVOLUTION_GLM53_2025_2026.md @@ -0,0 +1,140 @@ +# Bench: co-evolving harness and strategy on GLM 5.3's proposals (2025 search → 2026 test) + +One question: if you let the harness and the strategy hunt co-evolve at the same time, does +it find something that survives a regime change? Setup is deliberately clean — GLM 5.3 +proposes with retrieval off, everything is fitted inside 2025, and 2026 is only scored at the end. + +Reproduce with: + +```bash +python -m bench.coevolve_dual_ma --fetch --out bench/bench_coevolution_report.json +``` + +## Data and split + +Ten NASDAQ large caps — AAPL, MSFT, NVDA, AMZN, GOOGL, META, TSLA, AVGO, COST, NFLX — +daily adjusted OHLC from `yf.download(..., auto_adjust=True)`. + +| | Window | Bars | +| --- | --- | ---: | +| Search (pattern finding) | 2025-01-02 → 2025-12-31 | 250 | +| Test (never used for selection) | 2026-01-02 → 2026-12-01 | 231 | + +Search-window regime: mean return +21.5%, mean annualized vol 38.4%, median buy-and-hold +Sharpe 0.55, mean max drawdown −32.2%, 7 of 10 names above their 200-day SMA. High-vol names +with violent drawdowns — a fair trend-following test. + +## Proposer: GLM 5.3, no retrieval + +The harness cannot call a model in-process (`create_planner()` → `FallbackPlanner`, no +credentials, no GLM provider), so `zai-glm-5-3` acted as the proposer through a pinned +text-only session with web search disabled. It was given only the 2025 statistics and a fixed +grid, and replied: + +| Params | Confidence | +| --- | ---: | +| 20/50 | 0.80 | +| 15/30 | 0.70 | +| 30/80 | 0.65 | +| 10/20 | 0.50 | +| 40/100 | 0.40 | + +## Co-evolution + +Two coupled populations, both selected on 2025 only: + +- **Harness genome** (how we hunt): holding horizon ∈ {1,3,5}, SMA200 trend filter ∈ {off,on}, + drawdown gate ∈ {0.15,0.20,0.25}, selection rule ∈ {mean Sharpe, worst name, Sharpe-over-DD}. +- **Strategy genome** (what we hunt): the 31 fast/slow pairs from the grid, seeded with GLM's five. + +Harness fitness uses one common yardstick — the mean 2025 Sharpe of the strategy that harness +would actually pick — so selection rules are comparable; the rule decides *which* strategy a +harness picks, not how the harness is scored. 15 generations, 10 harnesses, 26 strategies. + +Result: converged to **50/80, 5-bar hold, DD gate 0.25, mean-Sharpe rule, search fitness +1.1164** — and that is *exactly* the brute-force optimum over the whole space, verified by +exhaustive enumeration. The co-evolution is a correct search; it is not an approximation. + +## The 2026 test + +2026 is never used by selection. Indicators are warmed on 2025 prices, so each strategy enters +2026 in the state it would really have had (an earlier version of this bench cold-started on +Jan 2 and flattered every number; see the commit history). Buy-and-hold uses the same Sharpe +function and positive-drawdown convention as the strategies. + +| Candidate | 2026 mean Sharpe | Mean max DD | Names ≥ 0.3 | +| --- | ---: | ---: | ---: | +| Co-evolved winner (50/80, H=5, gate 0.25) | **−0.589** | 28.1% | 1/10 | +| Control: same 50/80 under the fixed baseline harness (H=1) | −0.719 | 28.5% | 1/10 | +| GLM 5.3 top pick (20/50, H=1) | −0.356 | 23.9% | 1/10 | +| Buy and hold | **+0.278** | 30.8% | n/a | + +All five GLM proposals, scored under the fixed baseline harness (H=1, gate 0.25, mean-Sharpe): + +| Params | Confidence | 2026 mean Sharpe | Names ≥ 0.3 | +| --- | ---: | ---: | ---: | +| 10/20 | 0.50 | −0.030 | 4/10 | +| 15/30 | 0.70 | −0.173 | 2/10 | +| 20/50 | 0.80 | −0.356 | 1/10 | +| 30/80 | 0.65 | −0.510 | 2/10 | +| 40/100 | 0.40 | −0.682 | 2/10 | + +Every candidate loses to buy-and-hold on risk-adjusted terms. The co-evolved winner is *worse* +than GLM's top pick: the evolved harness did not add anything over the proposal, and the +strategy it chose (50/80) is the same one the fixed-harness control picks from 2025 alone. +Co-evolution therefore cannot be credited with any 2026 outcome; the control isolates that. + +## Why: the strategy family failed, not the proposer + +An oracle over 186 configurations (31 pairs × 3 horizons × trend filter on/off), scored *on 2026 +itself* (in-sample by construction, diagnostic only), finds only **6 of 186** with a positive +mean Sharpe; the best is **+0.077** (15/30, 3-bar hold, SMA200 filter on). So even with +hindsight and the trend filter no dual-MA configuration on this universe approaches +buy-and-hold (+0.278) in 2026. + +## Takeaways + +- **The search is exact but not the bottleneck.** The exhaustive search maximises the same + fitness over all feasible (harness, strategy) pairs, an upper bound on what co-evolution can + reach. Co-evolution reached it at seed 7 and at four more seeds (8-11), all at fitness + 1.1164. Five seeds on a 54×31 space is a sanity check, not a proof. +- **The evolved harness drifted toward looseness, and that is built in.** Harness fitness is + the best mean Sharpe among strategies the harness admits, so a looser drawdown gate admits a + superset and cannot score lower. The 0.25 gate is the guaranteed outcome of the gene + encoding, not evidence of anything about 2026. +- **GLM's confidence did not track transfer.** Its top-confidence pick was mid-table, the + lowest-confidence pick was worst, and the second-lowest (10/20 at 0.50) was best. +- **Buy-and-hold is the honest benchmark here.** On a 2025→2026 regime break, a long/cash + crossover on high-vol NASDAQ names lost risk-adjusted return in the test year. + +## Smoke test of the harness itself + +`agentquant run --ticker AAPL --start 2025-01-02 --end 2026-12-01` runs end to end: +`run_status: passed_quality_gate`, `costs.tool_calls: 0.0`, top pick 50/200 at Sharpe 1.042. +It spans both windows, so it leaks the test year and is a plumbing check only, not a result. + +## Caveats + +- GLM 5.3 is not callable over HTTP here; it proposed via a pinned session, and the harness ran + its own grid search through `FallbackPlanner`. This benches proposals plus this co-evolution + loop, not the model's agency inside the harness. +- Web search was off (`HarnessConfig.use_web_search` false; run manifest records + `tool_calls: 0.0`). Disabling retrieval does **not** remove memorised market knowledge, and + `zai-glm-5-3` is absent from `src/agent/knowledge_cutoffs.py`, so the harness's own + contamination check flags any 2026 evaluation window. +- The oracle table is in-sample and diagnostic — it is there to show the strategy family failed, + not as a candidate. +- The search space (31 pairs × 3 horizons × 2 filters × 3 gates × 3 rules) is small enough that + co-evolution is not needed; matching brute force is only a correctness check. +- One split, one test year, no multiplicity correction. Five seeds were run for the search + check. Nothing here is a validated score. +- The test window is scored many times (candidates, controls, and the 186-config oracle), so + it is now spent: do not reuse 2026 to pick anything. +- Strategy-side evolution is selection among a 26-member pool by best feasible fitness, plus + crossover; it is not independent of the harness. No random-search control at equal budget. +- Every one of the five proposals breached the 0.20 drawdown gate during the 2025 search + (21.5%–31.1% on the worst name), so none was admissible under the stricter gate; they only + became candidates once the evolved harness loosened it to 0.25. So the table above compares + proposals under a gate none of them satisfies. + +Full machine-readable report: `bench/bench_coevolution_report.json`. diff --git a/bench/bench_coevolution_report.json b/bench/bench_coevolution_report.json new file mode 100644 index 0000000..e11bea2 --- /dev/null +++ b/bench/bench_coevolution_report.json @@ -0,0 +1,937 @@ +{ + "web_search": false, + "search_window": [ + "2025-01-02", + "2025-12-31" + ], + "test_window": [ + "2026-01-02", + "2026-12-01" + ], + "universe": [ + "AAPL", + "MSFT", + "NVDA", + "AMZN", + "GOOGL", + "META", + "TSLA", + "AVGO", + "COST", + "NFLX" + ], + "glm_5_3_proposals": [ + { + "fast_window": 20, + "slow_window": 50, + "confidence": 0.8 + }, + { + "fast_window": 15, + "slow_window": 30, + "confidence": 0.7 + }, + { + "fast_window": 30, + "slow_window": 80, + "confidence": 0.65 + }, + { + "fast_window": 10, + "slow_window": 20, + "confidence": 0.5 + }, + { + "fast_window": 40, + "slow_window": 100, + "confidence": 0.4 + } + ], + "coevolution": { + "generations": 15, + "history": [ + { + "generation": 0, + "best_common_fitness": 1.0536, + "best_harness": { + "horizon": 3, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 1, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 2, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 3, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 4, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 5, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 6, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 7, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 8, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 9, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 10, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 11, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 12, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 13, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + }, + { + "generation": 14, + "best_common_fitness": 1.1164, + "best_harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "best_strategy": [ + 50, + 80 + ] + } + ], + "seed": 7, + "reached_exhaustive_optimum": true, + "seed_sweep": [ + { + "seed": 8, + "search_fitness": 1.1164, + "reached_exhaustive_optimum": true + }, + { + "seed": 9, + "search_fitness": 1.1164, + "reached_exhaustive_optimum": true + }, + { + "seed": 10, + "search_fitness": 1.1164, + "reached_exhaustive_optimum": true + }, + { + "seed": 11, + "search_fitness": 1.1164, + "reached_exhaustive_optimum": true + } + ], + "winner": { + "harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "fast": 50, + "slow": 80, + "search_fitness": 1.1164 + }, + "test_2026": { + "mean_sharpe": -0.5889, + "mean_max_drawdown": 0.281, + "names_clearing_0_3": 1, + "names": [ + { + "ticker": "AAPL", + "sharpe": 0.7513, + "max_drawdown": 0.1271 + }, + { + "ticker": "MSFT", + "sharpe": -0.4769, + "max_drawdown": 0.2338 + }, + { + "ticker": "NVDA", + "sharpe": -1.0933, + "max_drawdown": 0.357 + }, + { + "ticker": "AMZN", + "sharpe": -1.4937, + "max_drawdown": 0.3601 + }, + { + "ticker": "GOOGL", + "sharpe": -0.6494, + "max_drawdown": 0.3389 + }, + { + "ticker": "META", + "sharpe": 0.219, + "max_drawdown": 0.2787 + }, + { + "ticker": "TSLA", + "sharpe": -0.6704, + "max_drawdown": 0.3899 + }, + { + "ticker": "AVGO", + "sharpe": -0.1121, + "max_drawdown": 0.2503 + }, + { + "ticker": "COST", + "sharpe": -0.121, + "max_drawdown": 0.155 + }, + { + "ticker": "NFLX", + "sharpe": -2.243, + "max_drawdown": 0.3196 + } + ] + } + }, + "exhaustive_search_2025": { + "winner": { + "harness": { + "horizon": 5, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "fast": 50, + "slow": 80, + "search_fitness": 1.1164 + }, + "test_2026": { + "mean_sharpe": -0.5889, + "mean_max_drawdown": 0.281, + "names_clearing_0_3": 1, + "names": [ + { + "ticker": "AAPL", + "sharpe": 0.7513, + "max_drawdown": 0.1271 + }, + { + "ticker": "MSFT", + "sharpe": -0.4769, + "max_drawdown": 0.2338 + }, + { + "ticker": "NVDA", + "sharpe": -1.0933, + "max_drawdown": 0.357 + }, + { + "ticker": "AMZN", + "sharpe": -1.4937, + "max_drawdown": 0.3601 + }, + { + "ticker": "GOOGL", + "sharpe": -0.6494, + "max_drawdown": 0.3389 + }, + { + "ticker": "META", + "sharpe": 0.219, + "max_drawdown": 0.2787 + }, + { + "ticker": "TSLA", + "sharpe": -0.6704, + "max_drawdown": 0.3899 + }, + { + "ticker": "AVGO", + "sharpe": -0.1121, + "max_drawdown": 0.2503 + }, + { + "ticker": "COST", + "sharpe": -0.121, + "max_drawdown": 0.155 + }, + { + "ticker": "NFLX", + "sharpe": -2.243, + "max_drawdown": 0.3196 + } + ] + } + }, + "glm_top_pick": { + "harness_baseline": { + "horizon": 1, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "fast": 20, + "slow": 50, + "test_2026": { + "mean_sharpe": -0.3555, + "mean_max_drawdown": 0.239, + "names_clearing_0_3": 1, + "names": [ + { + "ticker": "AAPL", + "sharpe": 0.5251, + "max_drawdown": 0.1271 + }, + { + "ticker": "MSFT", + "sharpe": -0.5405, + "max_drawdown": 0.2143 + }, + { + "ticker": "NVDA", + "sharpe": -0.0988, + "max_drawdown": 0.2094 + }, + { + "ticker": "AMZN", + "sharpe": -0.7216, + "max_drawdown": 0.2579 + }, + { + "ticker": "GOOGL", + "sharpe": -0.3946, + "max_drawdown": 0.2303 + }, + { + "ticker": "META", + "sharpe": -0.9785, + "max_drawdown": 0.3456 + }, + { + "ticker": "TSLA", + "sharpe": 0.0778, + "max_drawdown": 0.2143 + }, + { + "ticker": "AVGO", + "sharpe": -0.6125, + "max_drawdown": 0.3243 + }, + { + "ticker": "COST", + "sharpe": 0.2678, + "max_drawdown": 0.1739 + }, + { + "ticker": "NFLX", + "sharpe": -1.079, + "max_drawdown": 0.2927 + } + ] + } + }, + "glm_proposals_test_2026": [ + { + "fast": 20, + "slow": 50, + "harness": { + "horizon": 1, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "test_2026": { + "mean_sharpe": -0.3555, + "mean_max_drawdown": 0.239, + "names_clearing_0_3": 1, + "names": [ + { + "ticker": "AAPL", + "sharpe": 0.5251, + "max_drawdown": 0.1271 + }, + { + "ticker": "MSFT", + "sharpe": -0.5405, + "max_drawdown": 0.2143 + }, + { + "ticker": "NVDA", + "sharpe": -0.0988, + "max_drawdown": 0.2094 + }, + { + "ticker": "AMZN", + "sharpe": -0.7216, + "max_drawdown": 0.2579 + }, + { + "ticker": "GOOGL", + "sharpe": -0.3946, + "max_drawdown": 0.2303 + }, + { + "ticker": "META", + "sharpe": -0.9785, + "max_drawdown": 0.3456 + }, + { + "ticker": "TSLA", + "sharpe": 0.0778, + "max_drawdown": 0.2143 + }, + { + "ticker": "AVGO", + "sharpe": -0.6125, + "max_drawdown": 0.3243 + }, + { + "ticker": "COST", + "sharpe": 0.2678, + "max_drawdown": 0.1739 + }, + { + "ticker": "NFLX", + "sharpe": -1.079, + "max_drawdown": 0.2927 + } + ] + } + }, + { + "fast": 15, + "slow": 30, + "harness": { + "horizon": 1, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "test_2026": { + "mean_sharpe": -0.1734, + "mean_max_drawdown": 0.2275, + "names_clearing_0_3": 2, + "names": [ + { + "ticker": "AAPL", + "sharpe": 0.7051, + "max_drawdown": 0.1233 + }, + { + "ticker": "MSFT", + "sharpe": 0.0677, + "max_drawdown": 0.2797 + }, + { + "ticker": "NVDA", + "sharpe": -0.1752, + "max_drawdown": 0.2204 + }, + { + "ticker": "AMZN", + "sharpe": -0.3915, + "max_drawdown": 0.2448 + }, + { + "ticker": "GOOGL", + "sharpe": -0.8733, + "max_drawdown": 0.2355 + }, + { + "ticker": "META", + "sharpe": -1.2795, + "max_drawdown": 0.3401 + }, + { + "ticker": "TSLA", + "sharpe": 0.2543, + "max_drawdown": 0.1565 + }, + { + "ticker": "AVGO", + "sharpe": -0.1465, + "max_drawdown": 0.3108 + }, + { + "ticker": "COST", + "sharpe": 1.0687, + "max_drawdown": 0.1386 + }, + { + "ticker": "NFLX", + "sharpe": -0.9635, + "max_drawdown": 0.2252 + } + ] + } + }, + { + "fast": 30, + "slow": 80, + "harness": { + "horizon": 1, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "test_2026": { + "mean_sharpe": -0.5102, + "mean_max_drawdown": 0.2563, + "names_clearing_0_3": 2, + "names": [ + { + "ticker": "AAPL", + "sharpe": 0.802, + "max_drawdown": 0.1271 + }, + { + "ticker": "MSFT", + "sharpe": -0.435, + "max_drawdown": 0.2338 + }, + { + "ticker": "NVDA", + "sharpe": -1.1226, + "max_drawdown": 0.3401 + }, + { + "ticker": "AMZN", + "sharpe": -1.5142, + "max_drawdown": 0.3096 + }, + { + "ticker": "GOOGL", + "sharpe": -1.1259, + "max_drawdown": 0.2699 + }, + { + "ticker": "META", + "sharpe": -1.1198, + "max_drawdown": 0.2984 + }, + { + "ticker": "TSLA", + "sharpe": -0.1928, + "max_drawdown": 0.2839 + }, + { + "ticker": "AVGO", + "sharpe": -0.3396, + "max_drawdown": 0.2503 + }, + { + "ticker": "COST", + "sharpe": 0.919, + "max_drawdown": 0.1444 + }, + { + "ticker": "NFLX", + "sharpe": -0.9732, + "max_drawdown": 0.3058 + } + ] + } + }, + { + "fast": 10, + "slow": 20, + "harness": { + "horizon": 1, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "test_2026": { + "mean_sharpe": -0.0297, + "mean_max_drawdown": 0.2324, + "names_clearing_0_3": 4, + "names": [ + { + "ticker": "AAPL", + "sharpe": 1.2416, + "max_drawdown": 0.1078 + }, + { + "ticker": "MSFT", + "sharpe": 0.5488, + "max_drawdown": 0.1593 + }, + { + "ticker": "NVDA", + "sharpe": -0.2234, + "max_drawdown": 0.1883 + }, + { + "ticker": "AMZN", + "sharpe": -0.1396, + "max_drawdown": 0.2455 + }, + { + "ticker": "GOOGL", + "sharpe": 0.0319, + "max_drawdown": 0.2016 + }, + { + "ticker": "META", + "sharpe": -0.9552, + "max_drawdown": 0.3383 + }, + { + "ticker": "TSLA", + "sharpe": 0.429, + "max_drawdown": 0.1894 + }, + { + "ticker": "AVGO", + "sharpe": -1.0051, + "max_drawdown": 0.4375 + }, + { + "ticker": "COST", + "sharpe": 1.1248, + "max_drawdown": 0.1897 + }, + { + "ticker": "NFLX", + "sharpe": -1.3501, + "max_drawdown": 0.2668 + } + ] + } + }, + { + "fast": 40, + "slow": 100, + "harness": { + "horizon": 1, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "test_2026": { + "mean_sharpe": -0.6819, + "mean_max_drawdown": 0.2747, + "names_clearing_0_3": 2, + "names": [ + { + "ticker": "AAPL", + "sharpe": 0.8197, + "max_drawdown": 0.1271 + }, + { + "ticker": "MSFT", + "sharpe": -0.8318, + "max_drawdown": 0.2005 + }, + { + "ticker": "NVDA", + "sharpe": -1.0487, + "max_drawdown": 0.3473 + }, + { + "ticker": "AMZN", + "sharpe": -0.9973, + "max_drawdown": 0.3628 + }, + { + "ticker": "GOOGL", + "sharpe": -0.9497, + "max_drawdown": 0.3375 + }, + { + "ticker": "META", + "sharpe": -1.347, + "max_drawdown": 0.366 + }, + { + "ticker": "TSLA", + "sharpe": -0.5629, + "max_drawdown": 0.3716 + }, + { + "ticker": "AVGO", + "sharpe": -0.2379, + "max_drawdown": 0.2503 + }, + { + "ticker": "COST", + "sharpe": 0.3149, + "max_drawdown": 0.139 + }, + { + "ticker": "NFLX", + "sharpe": -1.9786, + "max_drawdown": 0.2447 + } + ] + } + } + ], + "fixed_harness_strategy_only_control": { + "harness": { + "horizon": 1, + "trend_filter": false, + "dd_gate": 0.25, + "selection_rule": "mean_sharpe", + "use_web_search": false + }, + "fast": 50, + "slow": 80, + "test_2026": { + "mean_sharpe": -0.719, + "mean_max_drawdown": 0.2847, + "names_clearing_0_3": 1, + "names": [ + { + "ticker": "AAPL", + "sharpe": 1.0546, + "max_drawdown": 0.1271 + }, + { + "ticker": "MSFT", + "sharpe": -0.5359, + "max_drawdown": 0.2338 + }, + { + "ticker": "NVDA", + "sharpe": -1.4791, + "max_drawdown": 0.3892 + }, + { + "ticker": "AMZN", + "sharpe": -1.5952, + "max_drawdown": 0.3419 + }, + { + "ticker": "GOOGL", + "sharpe": -1.0115, + "max_drawdown": 0.3513 + }, + { + "ticker": "META", + "sharpe": -0.0477, + "max_drawdown": 0.2787 + }, + { + "ticker": "TSLA", + "sharpe": -0.6328, + "max_drawdown": 0.3869 + }, + { + "ticker": "AVGO", + "sharpe": -0.613, + "max_drawdown": 0.252 + }, + { + "ticker": "COST", + "sharpe": 0.0082, + "max_drawdown": 0.1578 + }, + { + "ticker": "NFLX", + "sharpe": -2.3375, + "max_drawdown": 0.3283 + } + ] + } + }, + "buy_and_hold_2026": { + "mean_sharpe": 0.278, + "mean_max_drawdown": 0.3081 + }, + "oracle_2026_diagnostic": { + "best": { + "fast": 15, + "slow": 30, + "horizon": 3, + "trend_filter": true, + "mean_sharpe": 0.0774 + }, + "positive_configs": 6, + "total_configs": 186 + } +} \ No newline at end of file diff --git a/bench/coevolve_dual_ma.py b/bench/coevolve_dual_ma.py new file mode 100644 index 0000000..fab578b --- /dev/null +++ b/bench/coevolve_dual_ma.py @@ -0,0 +1,357 @@ +"""Co-evolve the harness (how we hunt) and the strategies (what we hunt). + +Reproduces bench/BENCH_COEVOLUTION_GLM53_2025_2026.md. + +Discipline enforced here: + * fitness, selection, crossover and mutation all run inside the search window + 2025-01-02..2025-12-31; + * the test window 2026-01-02..2026-12-01 is never used by selection; it is only + scored at the end (the winner, the exhaustive winner, the GLM proposals, plus a + clearly labelled hindsight oracle that does scan it); + * indicators for the test window are warmed up on 2025 prices, so scoring starts + from live-like state instead of a cold start; + * web search is pinned off (no retrieval in this loop). + +Usage: + python -m bench.coevolve_dual_ma --fetch # download prices once + python -m bench.coevolve_dual_ma --out report.json +""" +from __future__ import annotations + +import argparse +import itertools +import json +import random +import statistics +from pathlib import Path + +import pandas as pd + +from src.backtest.simple_backtest import calculate_sharpe +from src.utils.backtest_utils import max_drawdown_from_equity + +UNIVERSE = ["AAPL", "MSFT", "NVDA", "AMZN", "GOOGL", "META", "TSLA", "AVGO", "COST", "NFLX"] +SEARCH = ("2025-01-02", "2025-12-31") +TEST = ("2026-01-02", "2026-12-01") +WEB_SEARCH = False + +FAST = [5, 10, 15, 20, 25, 30, 40, 50] +SLOW = [20, 30, 50, 80, 100] +GRID = [(f, s) for f in FAST for s in SLOW if f < s] + +# Proposals from zai-glm-5-3, text-only, no retrieval, via a pinned session. +GLM_SEEDS = [ + {"fast_window": 20, "slow_window": 50, "confidence": 0.80}, + {"fast_window": 15, "slow_window": 30, "confidence": 0.70}, + {"fast_window": 30, "slow_window": 80, "confidence": 0.65}, + {"fast_window": 10, "slow_window": 20, "confidence": 0.50}, + {"fast_window": 40, "slow_window": 100, "confidence": 0.40}, +] + + +def fetch_all(data_dir: Path) -> None: + import yfinance as yf + + data_dir.mkdir(parents=True, exist_ok=True) + for t in UNIVERSE: + df = yf.download(t, start="2025-01-01", end="2026-12-02", progress=False, auto_adjust=True) + if isinstance(df.columns, pd.MultiIndex): + df.columns = df.columns.get_level_values(0) + df.index.name = "Date" + df.to_parquet(data_dir / f"{t}.parquet") + + +def load(ticker: str, window, data_dir: Path, warmup: bool = False) -> pd.DataFrame: + """Prices for ``window``. With ``warmup`` the frame also carries earlier history + so indicators are warm; scoring is restricted to the window via ``score_from``.""" + df = pd.read_parquet(data_dir / f"{ticker}.parquet") + if isinstance(df.columns, pd.MultiIndex): + df.columns = df.columns.get_level_values(0) + lo = None if warmup else pd.Timestamp(window[0]) + out = df.loc[lo:pd.Timestamp(window[1])].copy() + if warmup: + out.attrs["score_from"] = pd.Timestamp(window[0]) + first_day = out.loc[pd.Timestamp(window[0]):].index + if len(first_day) == 0: + raise ValueError(f"{ticker}: no rows in test window {window}") + return out + + +def run_one(df, fast, slow, horizon, trend_filter): + close = df["Close"].astype(float).dropna() + if len(close) < slow + 5: + return None + sig = (close.rolling(fast, min_periods=1).mean() + > close.rolling(slow, min_periods=1).mean()).astype(int) + if trend_filter: + sig = sig & (close > close.rolling(200, min_periods=1).mean()).astype(int) + if horizon > 1: + sig = sig.iloc[::horizon].reindex(sig.index, method="ffill") + strat = close.pct_change().fillna(0) * sig.shift(1).fillna(0) + start = df.attrs.get("score_from") + if start is not None: + strat = strat.loc[start:] # score only the window; indicators were warm + return float(calculate_sharpe(strat)), float(max_drawdown_from_equity((1 + strat).cumprod())) + + +class Harness: + GENES = { + "horizon": [1, 3, 5], + "trend_filter": [False, True], + "dd_gate": [0.15, 0.20, 0.25], + "selection_rule": ["mean_sharpe", "worst_name", "sharpe_over_dd"], + } + + def __init__(self, horizon, trend_filter, dd_gate, selection_rule): + self.horizon, self.trend_filter = horizon, trend_filter + self.dd_gate, self.selection_rule = dd_gate, selection_rule + + def key(self): + return (self.horizon, self.trend_filter, self.dd_gate, self.selection_rule) + + def to_dict(self): + return {"horizon": self.horizon, "trend_filter": self.trend_filter, + "dd_gate": self.dd_gate, "selection_rule": self.selection_rule, + "use_web_search": WEB_SEARCH} + + def pick_rank(self, per_name): + """Rule-specific ranking used to CHOOSE a strategy, never to score a harness.""" + sh = [s for s, _ in per_name] + dd = [d for _, d in per_name] + if self.selection_rule == "mean_sharpe": + return statistics.mean(sh) + if self.selection_rule == "worst_name": + return min(sh) + return statistics.mean(sh) / (1.0 + statistics.mean(dd)) + + def feasible(self, per_name): + return all(d <= self.dd_gate for _, d in per_name) + + @staticmethod + def random_genome(rng): + return Harness(*[rng.choice(v) for v in Harness.GENES.values()]) + + def mutate(self, rng): + d = self.to_dict() + name = rng.choice(list(self.GENES)) + d[name] = rng.choice([c for c in self.GENES[name] if c != d[name]]) + return Harness(d["horizon"], d["trend_filter"], d["dd_gate"], d["selection_rule"]) + + +def per_name(strat, harness, data): + out = [] + for t in UNIVERSE: + r = run_one(data[t], strat[0], strat[1], harness.horizon, harness.trend_filter) + if r is None: + return None + out.append(r) + return out + + +def coevolve(seeds, data_search, generations=15, harness_pop=10, strat_pop=26, seed=7): + rng = random.Random(seed) + cache = {} + + def perf(h, strat): + k = (h.key(), strat) + if k not in cache: + cache[k] = per_name(strat, h, data_search) + return cache[k] + + harnesses = [Harness.random_genome(rng) for _ in range(harness_pop)] + seeds = list(dict.fromkeys(seeds)) + rest = [s for s in GRID if s not in seeds] + rng.shuffle(rest) + strategies = (seeds + rest)[:max(strat_pop, len(seeds))] # proposals always enter gen 0 + + history = [] + for gen in range(generations): + ranked = [] + for h in harnesses: + feas = [(h.pick_rank(p), s) for s in strategies if (p := perf(h, s)) and h.feasible(p)] + if not feas: + ranked.append((float("-inf"), h, None)) + continue + pick = max(feas, key=lambda x: x[0])[1] + ranked.append((statistics.mean(s for s, _ in perf(h, pick)), h, pick)) + ranked.sort(key=lambda x: x[0], reverse=True) + history.append({"generation": gen, + "best_common_fitness": round(ranked[0][0], 4) if ranked[0][2] else None, + "best_harness": ranked[0][1].to_dict(), + "best_strategy": list(ranked[0][2]) if ranked[0][2] else None}) + + elite = [h for _, h, _ in ranked[: max(2, harness_pop // 2)]] + harnesses = elite + [rng.choice(elite).mutate(rng) for _ in range(harness_pop - len(elite))] + + def strat_fitness(st): + fits = [statistics.mean(x for x, _ in p) for h in harnesses + if (p := perf(h, st)) and h.feasible(p)] + return max(fits) if fits else float("-inf") + + picks = [s for _, _, s in ranked[: max(2, harness_pop // 2)] if s] + pool = list(dict.fromkeys(picks + sorted(strategies, key=strat_fitness, reverse=True))) + strategies = pool[: strat_pop // 2] + while len(strategies) < strat_pop: + f, s = rng.choice(pool) + if rng.random() < 0.5: + f = rng.choice([x for x in FAST if x < s]) + else: + s = rng.choice([x for x in SLOW if x > f]) + if (f, s) not in strategies: + strategies.append((f, s)) + + final = [] + for h in harnesses: + feas = [(h.pick_rank(p), s) for s in strategies if (p := perf(h, s)) and h.feasible(p)] + if feas: + pick = max(feas, key=lambda x: x[0])[1] + final.append((statistics.mean(s for s, _ in perf(h, pick)), h, pick)) + if not final: + raise RuntimeError("no feasible (harness, strategy) pair in the final population; " + "relax dd_gate or widen the grid") + final.sort(key=lambda x: x[0], reverse=True) + return final[0], history + + +def exhaustive(data_search): + best = None + for g in itertools.product([1, 3, 5], [False, True], [0.15, 0.20, 0.25], + ["mean_sharpe", "worst_name", "sharpe_over_dd"]): + h = Harness(*g) + for strat in GRID: + p = per_name(strat, h, data_search) + if p is None or not h.feasible(p): + continue + m = statistics.mean(s for s, _ in p) + if best is None or m > best[0]: + best = (m, h, strat) + return best + + +def score(strat, harness, data): + rows = [] + for t in UNIVERSE: + res = run_one(data[t], strat[0], strat[1], harness.horizon, harness.trend_filter) + if res is None: + raise ValueError(f"{t}: window too short for slow={strat[1]}") + sh, dd = res + rows.append({"ticker": t, "sharpe": round(sh, 4), "max_drawdown": round(dd, 4)}) + shs = [r["sharpe"] for r in rows] + return {"mean_sharpe": round(statistics.mean(shs), 4), + "mean_max_drawdown": round(statistics.mean(r["max_drawdown"] for r in rows), 4), + "names_clearing_0_3": sum(1 for s in shs if s >= 0.3), + "names": rows} + + +def buy_and_hold(data): + sh, dd = [], [] + for t in UNIVERSE: + c = data[t]["Close"].astype(float).dropna() + r = c.pct_change().fillna(0) + start = data[t].attrs.get("score_from") + if start is not None: + r = r.loc[start:] + # same Sharpe function and positive-drawdown convention as the strategies + sh.append(float(calculate_sharpe(r))) + dd.append(float(max_drawdown_from_equity((1 + r).cumprod()))) + return {"mean_sharpe": round(statistics.mean(sh), 4), + "mean_max_drawdown": round(statistics.mean(dd), 4)} + + +def oracle_2026(data_test): + """Diagnostic: which config would have won 2026 with hindsight. In-sample by construction.""" + rows = [] + for f, s in GRID: + for h, tf in itertools.product((1, 3, 5), (False, True)): + per = [run_one(data_test[t], f, s, h, tf) for t in UNIVERSE] + rows.append((statistics.mean(p[0] for p in per), f, s, h, tf)) + rows.sort(reverse=True) + return {"best": {"fast": rows[0][1], "slow": rows[0][2], "horizon": rows[0][3], + "trend_filter": rows[0][4], "mean_sharpe": round(rows[0][0], 4)}, + "positive_configs": sum(1 for r in rows if r[0] > 0), + "total_configs": len(rows)} + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--data-dir", default=".agentquant/coevolve_data") + ap.add_argument("--fetch", action="store_true") + ap.add_argument("--out", default=None) + ap.add_argument("--seed", type=int, default=7) + ap.add_argument("--seed-sweep", type=int, default=0, + help="also run this many extra seeds and report how often the " + "co-evolution reaches the exhaustive search fitness") + args = ap.parse_args() + + data_dir = Path(args.data_dir) + if args.fetch or not (data_dir / f"{UNIVERSE[0]}.parquet").exists(): + fetch_all(data_dir) + + data_search = {t: load(t, SEARCH, data_dir) for t in UNIVERSE} + data_test = {t: load(t, TEST, data_dir, warmup=True) for t in UNIVERSE} + for t in UNIVERSE: + last = data_test[t].index[-1] + if last < pd.Timestamp(TEST[1]) - pd.Timedelta(days=4): + raise SystemExit(f"{t}: test data ends {last.date()}, before {TEST[1]}; " + "re-run with --fetch once the window is complete") + + seeds = [(p["fast_window"], p["slow_window"]) for p in GLM_SEEDS] + (fit, h_best, s_best), history = coevolve(seeds, data_search, seed=args.seed) + ex_fit, ex_h, ex_s = exhaustive(data_search) + base = Harness(1, False, 0.25, "mean_sharpe") + # controls: same fixed harness, strategy chosen by exhaustive 2025 search only + fixed = [(base.pick_rank(p), st) for st in GRID + if (p := per_name(st, base, data_search)) and base.feasible(p)] + fixed_pick = max(fixed)[1] if fixed else None + sweep = [] + for sd in range(args.seed + 1, args.seed + 1 + args.seed_sweep): + (f2, _, _), _ = coevolve(seeds, data_search, seed=sd) + sweep.append({"seed": sd, "search_fitness": round(f2, 4), + "reached_exhaustive_optimum": abs(f2 - ex_fit) < 1e-9}) + + report = { + "web_search": WEB_SEARCH, + "search_window": SEARCH, + "test_window": TEST, + "universe": UNIVERSE, + "glm_5_3_proposals": GLM_SEEDS, + "coevolution": { + "generations": len(history), + "history": history, + "seed": args.seed, + # exhaustive maximises mean Sharpe over all feasible pairs, an upper + # bound on the co-evolution fitness; equality means it hit the optimum + "reached_exhaustive_optimum": abs(fit - ex_fit) < 1e-9, + "seed_sweep": sweep, + "winner": {"harness": h_best.to_dict(), "fast": s_best[0], "slow": s_best[1], + "search_fitness": round(fit, 4)}, + "test_2026": score(s_best, h_best, data_test), + }, + "exhaustive_search_2025": { + "winner": {"harness": ex_h.to_dict(), "fast": ex_s[0], "slow": ex_s[1], + "search_fitness": round(ex_fit, 4)}, + "test_2026": score(ex_s, ex_h, data_test), + }, + "glm_top_pick": { + "harness_baseline": base.to_dict(), "fast": seeds[0][0], "slow": seeds[0][1], + "test_2026": score(seeds[0], base, data_test), + }, + "glm_proposals_test_2026": [ + {"fast": f, "slow": sl, "harness": base.to_dict(), "test_2026": score((f, sl), base, data_test)} + for f, sl in seeds + ], + "fixed_harness_strategy_only_control": ( + {"harness": base.to_dict(), "fast": fixed_pick[0], "slow": fixed_pick[1], + "test_2026": score(fixed_pick, base, data_test)} if fixed_pick else None), + "buy_and_hold_2026": buy_and_hold(data_test), + "oracle_2026_diagnostic": oracle_2026(data_test), + } + text = json.dumps(report, indent=1) + if args.out: + Path(args.out).write_text(text) + print(text) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())