itouchz commited on
Commit
ff4becd
·
0 Parent(s):

Duplicate from macrolens/MacroLens

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +13 -0
  2. .gitignore +35 -0
  3. DATASHEET.md +224 -0
  4. LICENSE +154 -0
  5. README.md +232 -0
  6. code/assemble_benchmark.py +228 -0
  7. code/benchmark_loader.py +522 -0
  8. code/build_ontology.py +438 -0
  9. code/build_valuation_tasks.py +956 -0
  10. code/collect_filings.py +425 -0
  11. code/collect_fundamentals.py +164 -0
  12. code/collect_macro.py +233 -0
  13. code/collect_news.py +308 -0
  14. code/collect_prices.py +191 -0
  15. code/collect_real_estate.py +193 -0
  16. code/collect_universe.py +568 -0
  17. code/config.py +833 -0
  18. code/dataloader/__init__.py +36 -0
  19. code/dataloader/_ablation.py +240 -0
  20. code/dataloader/_provenance.py +44 -0
  21. code/dataloader/budgets.py +93 -0
  22. code/dataloader/canonical_indices.py +569 -0
  23. code/dataloader/load.py +684 -0
  24. code/enrich_benchmark.py +288 -0
  25. code/eval.py +1556 -0
  26. code/experiments/__init__.py +1 -0
  27. code/experiments/__main__.py +16 -0
  28. code/experiments/adapters/scout_qlora_smoke_20260519T062736Z/fitted_fields.json +3 -0
  29. code/experiments/adapters/scout_qlora_smoke_20260519T070504Z/fitted_fields.json +3 -0
  30. code/experiments/aggregate_results.py +586 -0
  31. code/experiments/analyses/__init__.py +1 -0
  32. code/experiments/analyses/post_hoc.py +469 -0
  33. code/experiments/analysis.py +356 -0
  34. code/experiments/build_paper_artifacts.py +236 -0
  35. code/experiments/gen_figures.py +463 -0
  36. code/experiments/gen_tables.py +730 -0
  37. code/experiments/panel.py +495 -0
  38. code/experiments/probes/__init__.py +7 -0
  39. code/experiments/probes/contamination.py +280 -0
  40. code/experiments/probes/lightgbm_ablation.py +294 -0
  41. code/experiments/probes/lightgbm_tuned.py +276 -0
  42. code/experiments/probes/llm_finetune_qwen.py +476 -0
  43. code/experiments/probes/scenario_validation.py +615 -0
  44. code/experiments/probes/scout_qlora_multitask.py +481 -0
  45. code/experiments/re_evaluate.py +71 -0
  46. code/experiments/result_schema.py +213 -0
  47. code/experiments/run_all.py +1041 -0
  48. code/experiments/run_experiments.sh +192 -0
  49. code/generate_scenarios.py +1746 -0
  50. code/macrolens/__init__.py +162 -0
.gitattributes ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.parquet filter=lfs diff=lfs merge=lfs -text
2
+ *.csv filter=lfs diff=lfs merge=lfs -text
3
+ *.json filter=lfs diff=lfs merge=lfs -text
4
+ *.pdf filter=lfs diff=lfs merge=lfs -text
5
+ *.tar filter=lfs diff=lfs merge=lfs -text
6
+ *.tar.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.tar.zst filter=lfs diff=lfs merge=lfs -text
8
+ *.zip filter=lfs diff=lfs merge=lfs -text
9
+ *.arrow filter=lfs diff=lfs merge=lfs -text
10
+ *.bin filter=lfs diff=lfs merge=lfs -text
11
+ *.h5 filter=lfs diff=lfs merge=lfs -text
12
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
13
+ *.feather filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python bytecode
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+
7
+ # Editor / OS
8
+ .DS_Store
9
+ .vscode/
10
+ .idea/
11
+ *.swp
12
+ *.swo
13
+
14
+ # Build / dist artifacts
15
+ *.egg-info/
16
+ build/
17
+ dist/
18
+ .eggs/
19
+
20
+ # Virtualenvs
21
+ .venv/
22
+ venv/
23
+ env/
24
+
25
+ # Test / coverage
26
+ .pytest_cache/
27
+ .coverage
28
+ .mypy_cache/
29
+ .ruff_cache/
30
+
31
+ # Notebook checkpoints
32
+ .ipynb_checkpoints/
33
+
34
+ # Logs
35
+ *.log
DATASHEET.md ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Datasheet for MacroLens
2
+
3
+ This datasheet follows the *Datasheets for Datasets* framework (Gebru et al., *Communications of the ACM*, 2021).
4
+
5
+ ---
6
+
7
+ ## 1. Motivation
8
+
9
+ **For what purpose was the dataset created?**
10
+ MacroLens evaluates forecasting and valuation models that must reason over numerical history *and* contextual information — macroeconomic state, scenarios, and firm text — in a financial setting. It addresses gaps in three existing benchmark families: generic time-series forecasting benchmarks drop text and valuation tasks; financial language benchmarks drop forecasting and event reasoning; recent context-rich forecasting datasets are non-financial or omit valuation.
11
+
12
+ **Who created the dataset and on behalf of which entity?**
13
+ Anonymous (NeurIPS 2026 Datasets & Benchmarks Track double-blind submission). Authors and affiliations to be disclosed after author notification.
14
+
15
+ **Who funded the creation of the dataset?**
16
+ Anonymous (will be disclosed after notification).
17
+
18
+ **Any other comments?**
19
+ The benchmark targets the *intersection* of contextual time-series forecasting, valuation, and scenario-conditioned event prediction, which prior public benchmarks have not covered jointly.
20
+
21
+ ---
22
+
23
+ ## 2. Composition
24
+
25
+ **What do the instances that comprise the dataset represent?**
26
+ A MacroLens instance is the tuple ⟨ticker $i$, timestamp $t$, granularity $g$, lookback panel $x_{i,t-L:t,g}$, static covariates $z_i$, optional scenario $s_t$, optional text $u_{i,\le t}$⟩, paired with a task-specific target $y_{i,t}$.
27
+
28
+ **How many instances are there in total?**
29
+ - 4,841,094 daily panel rows (3,219,018 train / 1,622,076 test) over 4,416 tickers and 1,313 trading days.
30
+ - 1,009,314 weekly panel rows.
31
+ - 232,483 monthly panel rows.
32
+ - 23,147 T2 valuation ground truths.
33
+ - 23,147 T5 private-valuation ground truths (same 1,324 holdout tickers, price-stripped).
34
+ - ~14,500 T3 (ticker, fiscal year, field) ground truth tuples (11-field curated dense panel).
35
+ - 4,072,843 T4 scenario-forecast ground-truth rows from 1,622,076 test panel rows × 1,130 events.
36
+ - 11,065 T6 generator-evaluation ground truths.
37
+ - 23,367 T7 real-estate ground truth rows over 23,190 unique addresses.
38
+ - 1,130 macroeconomic scenario events across 49 types.
39
+
40
+ **Does the dataset contain all possible instances or is it a sample (e.g., a sample of a larger set)?**
41
+ The 4,416-ticker universe is the union of: full Russell 2000 (1,923 IWM holdings), full S&P SmallCap 600 (72 IJR-only additions), iShares Micro-Cap (225 IWC additions), and the 2,196 small-cap NASDAQ/NYSE tickers outside all three indices, filtered to company market cap ≤ \$7.4B. This is **not** a sample — it is the complete enumeration of U.S. small/micro-cap equities meeting the universe spec on the trade dates 2021-01-04 through 2026-03-31.
42
+
43
+ **What data does each instance consist of?**
44
+ - **Numeric panel** (131 features per (ticker, date) coordinate): 6 OHLCV + 19 derived valuation ratios + 45 XBRL statement fields with TTM rolling-sum variants + 46 FRED macro + 7 EIA commodity + 1 days-since-filing + 7 index/membership flags.
45
+ - **Static covariates**: ticker metadata (sector, industry, exchange), security_type (operating / fund / SPAC), index memberships.
46
+ - **Scenario object** (optional, T4): event_type (49 categories), structured natural-language description, scenario_id.
47
+ - **Text** (optional): SEC filings (markdown + PDF), financial news articles.
48
+ - **Target**: per-task, see Section "Splits" below.
49
+
50
+ **Is there a label or target associated with each instance?**
51
+ Yes, per task (T1: horizon-length close trajectory; T2/T5: realized market cap; T3/T6: 11 canonical XBRL field values; T4: 63-day post-event return percentage; T7: rent + price).
52
+
53
+ **Is any information missing from individual instances?**
54
+ Yes, by point-in-time design. Quarterly XBRL facts apply a post-acceptance lag (so they appear in $x_{i,t,g}$ only after the publication timestamp). News articles enter only after publication. The 14 tickers without XBRL or yfinance fundamentals (5 FDIC-only banks + 9 SEC-empty stubs that yfinance also fails) are applicability-masked on T2/T3/T5/T6 (kept for T1, T4 with prices+filings only).
55
+
56
+ **Are relationships between individual instances made explicit?**
57
+ Yes. Tickers are linked to scenarios via dates and event_id. Real-estate addresses link to metros. Filings link to tickers via CIK. All keys are stored as identifier columns, not derived joins.
58
+
59
+ **Are there recommended data splits?**
60
+ - **T1, T4 (forecasting)**: chronological 70/30 split at **2024-09-03** (1,622,076 daily test rows).
61
+ - **T2, T3, T5, T6 (valuation + generation)**: 30% company-level holdout = **1,324 tickers, seed = 42**. Each ticker contributes its latest valid snapshot. T3, T6 add a per-ticker temporal split (latest fiscal year for test, prior years for train).
62
+ - **T7 (real-estate)**: 30% address-level holdout (random, seeded).
63
+
64
+ **Are there any errors, sources of noise, or redundancies in the dataset?**
65
+ - yfinance occasionally yields stale or misaligned quarter-close fundamentals; the loader applies a one-day lag for safety.
66
+ - The 14 fundamentals-empty tickers are applicability-masked, not excluded.
67
+ - T4 events with pre-event price below SEC penny-stock threshold ($0.50) are dropped at build time (~140 rows) because percentage-return arithmetic blows up at the noise floor.
68
+ - T7 has 854 duplicate-address rows in the train pool (53,804 unique vs 54,658 raw); deduplicated at canonical-index time.
69
+
70
+ **Is the dataset self-contained, or does it link to or otherwise rely on external resources?**
71
+ The Hugging Face release is bundled-self-contained for SEC EDGAR (filings + XBRL facts), FRED + EIA macro series, yfinance-derived prices + fundamentals, and the curated benchmark parquets — no user credentials needed for these. Two sources are **gated by external licensing** and ship as derived features + reconstruction scripts only:
72
+
73
+ | Source | Bundled in HF release? | User credentials required for raw re-fetch? |
74
+ |---|---|---|
75
+ | SEC EDGAR (filings, XBRL) | Yes (public domain) | No (free) |
76
+ | FRED, EIA (macro) | Yes (public domain) | No (free; FRED API key recommended for high rate) |
77
+ | yfinance (prices, fundamentals) | Yes (derived features) | No (free) |
78
+ | Macroeconomic event scenarios | Yes (curated by us, CC-BY-4.0) | No |
79
+ | **RentCast** (real estate raw) | **NO — derived features only** | **YES — user's own RentCast subscription** for `collect_real_estate.py` |
80
+ | **Financial news** (~215k articles) | **NO — derived counts only** | **YES — user's own news-API key** for `collect_news.py` |
81
+
82
+ **Does the dataset contain data that might be considered confidential?**
83
+ No. All sources are public regulatory filings (SEC EDGAR), public market data (yfinance), public macroeconomic series (FRED, EIA), and licensed real-estate listings (RentCast, used under their terms).
84
+
85
+ **Does the dataset contain data that, if viewed directly, might be offensive, insulting, threatening, or might otherwise cause anxiety?**
86
+ No, beyond standard financial-news content (corporate disputes, lawsuits, layoffs) which is part of public regulatory disclosure.
87
+
88
+ **Does the dataset relate to people?**
89
+ Indirectly — SEC filings name corporate officers and directors as part of public regulatory disclosure (the same information that appears on EDGAR). No private individuals; no PII beyond what is in public regulatory filings.
90
+
91
+ **Does the dataset identify any subpopulations?**
92
+ The dataset records `security_type` (operating, fund, SPAC) and Global Industry Classification Standard (GICS) sector for every ticker. No protected demographic categories.
93
+
94
+ ---
95
+
96
+ ## 3. Collection Process
97
+
98
+ **How was the data associated with each instance acquired?**
99
+ - **Universe**: iShares IWM/IJR/IWC ETF holdings + NASDAQ Trader symbol directory (filtered to market cap ≤ \$7.4B).
100
+ - **Prices**: Yahoo Finance.
101
+ - **Fundamentals**: yfinance (3.22M rows) + SEC EDGAR XBRL company-facts API (46.79M facts, 92.6% coverage).
102
+ - **Macro**: FRED + EIA via the publicly documented APIs.
103
+ - **Filings**: SEC EDGAR (10-K, 10-Q, 8-K, 20-F, 6-K, N-CSR, N-CSRS).
104
+ - **News**: provider feed + entity linking.
105
+ - **Real estate**: RentCast API (100 U.S. metros, 139,855 properties × 544 RentCast variants).
106
+
107
+ **What mechanisms or procedures were used to collect the data?**
108
+ Custom Python scripts (`collect_*.py`) using each source's official documented API. Rate limits were honored. All scripts are included in the release.
109
+
110
+ **If the dataset is a sample from a larger set, what was the sampling strategy?**
111
+ Not a sample — full enumeration of the universe spec over 2021-01-04 → 2026-03-31. Within that, the 30% company-level valuation holdout uses **stratified sampling** on (sector, market-cap quartile) at fixed seed = 42.
112
+
113
+ **Who was involved in the data collection process?**
114
+ Anonymous authors. No human annotators (the dataset uses programmatic API queries).
115
+
116
+ **Over what timeframe was the data collected?**
117
+ Source data was published over 2021-01-04 — 2026-03-31. Collection scripts were run in 2025-2026 to assemble the panel.
118
+
119
+ **Were any ethical review processes conducted?**
120
+ N/A — public-records data only.
121
+
122
+ ---
123
+
124
+ ## 4. Preprocessing / Cleaning / Labeling
125
+
126
+ **Was any preprocessing/cleaning/labeling of the data done?**
127
+ Yes:
128
+ - **Point-in-time alignment**: every observation aligns to publication timestamp (filings post-acceptance lag, quarterly XBRL post-acceptance, news post-publication).
129
+ - **Algebraic-leakage scrubbing for T2/T5**: every input column is auto-tested against $\log y$; any column with $|\text{Pearson}| > 0.99$ to the target is excluded. Largest residual T2 correlation post-scrub is shares-outstanding at $\rho = 0.30$, a legitimate size proxy.
130
+ - **APE clipping at 10×** (1,000%) on all valuation tasks to prevent a single mispredicted outlier from dominating MAPE-style metrics.
131
+ - **Outlier cleanup at source for T4**: rows with pre-event price below SEC penny-stock threshold (\$0.50) dropped at build time.
132
+ - **Address deduplication for T7** at canonical-index time (854 duplicates in train pool, 177 in eval pool removed).
133
+ - **TTM rolling-sum variants** computed for flow-style XBRL fields (revenue, net income, etc.).
134
+
135
+ **Was the "raw" data saved in addition to the preprocessed/cleaned/labeled data?**
136
+ Yes. The release bundles raw XBRL facts (`xbrl/`), raw prices (`prices/`), raw fundamentals (`fundamentals/`) alongside the curated `benchmark/` parquets so downstream researchers can re-derive features.
137
+
138
+ **Is the software that was used to preprocess/clean/label the data available?**
139
+ Yes — `preprocess.py`, `assemble_benchmark.py`, `build_ontology.py`, `enrich_benchmark.py`, `generate_scenarios.py`, `build_valuation_tasks.py`, `validate_all.py`. All under MIT.
140
+
141
+ ---
142
+
143
+ ## 5. Uses
144
+
145
+ **Has the dataset been used for any tasks already?**
146
+ Yes — the accompanying paper reports a 17-method baseline panel across 7 families on T1–T7.
147
+
148
+ **Is there a repository that links to any or all papers or systems that use the dataset?**
149
+ The HF dataset card (this README) will track citations. Currently: the accompanying NeurIPS 2026 D&B paper.
150
+
151
+ **What (other) tasks could the dataset be used for?**
152
+ - Multi-modal time-series forecasting research.
153
+ - Macroeconomic-event impact studies.
154
+ - LLM evaluation under domain-specific (financial) tasks.
155
+ - Private-market valuation modeling.
156
+ - Cross-domain transfer (real-estate vs equity valuation).
157
+ - Scenario reasoning + counterfactual forecasting.
158
+
159
+ **Is there anything about the composition of the dataset or the way it was collected that might impact future uses?**
160
+ - U.S.-only and English-only — international generalizability not supported.
161
+ - Survivorship bias is partially mitigated by including delisted tickers, but pre-2021 history is not covered.
162
+ - The 30% company-level holdout for T2/T3/T5/T6 evaluates OOD-ticker generalization but not OOD-sector or OOD-industry by construction.
163
+
164
+ **Are there tasks for which the dataset should not be used?**
165
+ - **Trading decisions**: the dataset is a research benchmark; metrics do not include transaction costs, slippage, or execution modeling. Direct trading use is **not recommended**.
166
+ - **International generalizability claims**: U.S. equities only.
167
+ - **Deployment safety**: no adversarial-robustness testing.
168
+
169
+ ---
170
+
171
+ ## 6. Distribution
172
+
173
+ **Will the dataset be distributed to third parties outside of the entity on behalf of which the dataset was created?**
174
+ Yes — Hugging Face Datasets, public.
175
+
176
+ **How will the dataset be distributed?**
177
+ - Primary: `huggingface.co/datasets/macrolens/MacroLens` (Croissant-validated, NeurIPS-D&B compliant).
178
+ - Code: same repo.
179
+ - Reconstruction scripts: same repo (raw filings + news re-fetched from official sources).
180
+
181
+ **When will the dataset be distributed?**
182
+ Public at time of NeurIPS 2026 D&B-track submission.
183
+
184
+ **Will the dataset be distributed under a copyright or other intellectual property license, and/or under applicable terms of use (ToU)?**
185
+ - Derived features + curated panel: **CC-BY-4.0**.
186
+ - Code: **MIT**.
187
+ - Vendored libraries (under `methods/_vendored/`): TSLib (MIT), ModernTCN (Apache 2.0).
188
+ - Reconstruction scripts: MIT.
189
+
190
+ **Have any third parties imposed IP-based or other restrictions on the data associated with the instances?**
191
+ - yfinance, FRED, EIA, RentCast: each has its own ToU; the release ships derived features and reconstruction scripts.
192
+ - SEC EDGAR: public domain.
193
+
194
+ **Do any export controls or other regulatory restrictions apply to the dataset or to individual instances?**
195
+ No.
196
+
197
+ ---
198
+
199
+ ## 7. Maintenance
200
+
201
+ **Who is supporting/hosting/maintaining the dataset?**
202
+ Anonymous (NeurIPS 2026 D&B submission). Maintainer-of-record will be disclosed after author notification.
203
+
204
+ **How can the owner / curator / manager of the dataset be contacted?**
205
+ Through the Hugging Face dataset discussions tab (`huggingface.co/datasets/macrolens/MacroLens/discussions`) or via the corresponding-author email (post-notification).
206
+
207
+ **Is there an erratum?**
208
+ None at submission. Errata will be tracked in the dataset card's `Changelog` section.
209
+
210
+ **Will the dataset be updated?**
211
+ Yes — minor versioned updates planned to extend the time window and refresh upstream sources. Versioning follows semver; each release tags a Git-style snapshot in the HF repo.
212
+
213
+ **If the dataset relates to people, are there applicable limits on the retention of the data associated with the instances?**
214
+ N/A — public regulatory filings only.
215
+
216
+ **Will older versions of the dataset continue to be supported/hosted/maintained?**
217
+ Yes — older revisions remain accessible via HF dataset revision tags (commit SHAs).
218
+
219
+ **If others want to extend/augment/build on/contribute to the dataset, is there a mechanism for them to do so?**
220
+ Yes — pull requests via the HF dataset repo or the GitHub mirror. Contributions are reviewed for license compatibility (CC-BY-4.0 compatible only) and benchmark protocol consistency.
221
+
222
+ ---
223
+
224
+ *This datasheet was prepared at the time of NeurIPS 2026 D&B-track submission. The Croissant metadata file (auto-generated by Hugging Face) at `https://huggingface.co/api/datasets/macrolens/MacroLens/croissant` is the machine-readable counterpart to this human-readable datasheet.*
LICENSE ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MacroLens License
2
+
3
+ This MacroLens release is distributed under a dual-license:
4
+
5
+ * Curated data artifacts under CC-BY-4.0 (Creative Commons Attribution 4.0)
6
+ * Code under the MIT License
7
+ * Vendored third-party libraries retain their upstream licenses (see
8
+ "Vendored Library Acknowledgements" below)
9
+
10
+ ================================================================================
11
+ DATA LICENSE
12
+ Creative Commons Attribution 4.0
13
+ (CC-BY-4.0)
14
+ ================================================================================
15
+
16
+ The following directories distribute curated data artifacts under
17
+ Creative Commons Attribution 4.0 International (CC-BY-4.0):
18
+
19
+ data/{daily,weekly,monthly}/ curated panel + ground-truth parquets
20
+ data/real_estate/ RentCast-derived address features
21
+ data/xbrl/ standardized XBRL facts
22
+ data/fundamentals/ yfinance-derived quarterly statements
23
+ data/macro/ FRED + EIA series
24
+ data/prices/ yfinance-derived OHLCV
25
+ data/processed/ derived features (TTM, ratios, scenarios)
26
+
27
+ Use of these data artifacts is permitted for any purpose (research, commercial,
28
+ modification, redistribution) provided that the user gives appropriate credit
29
+ to MacroLens and indicates changes made.
30
+
31
+ Full CC-BY-4.0 text: https://creativecommons.org/licenses/by/4.0/legalcode
32
+
33
+ ================================================================================
34
+ CODE LICENSE
35
+ (MIT License)
36
+ ================================================================================
37
+
38
+ Copyright (c) 2026 The MacroLens Authors
39
+
40
+ Permission is hereby granted, free of charge, to any person obtaining a copy
41
+ of this software and associated documentation files (the "Software"), to deal
42
+ in the Software without restriction, including without limitation the rights
43
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
44
+ copies of the Software, and to permit persons to whom the Software is
45
+ furnished to do so, subject to the following conditions:
46
+
47
+ The above copyright notice and this permission notice shall be included in all
48
+ copies or substantial portions of the Software.
49
+
50
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
51
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
52
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
53
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
54
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
55
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
56
+ SOFTWARE.
57
+
58
+ The MIT License applies to the following code directories and files:
59
+
60
+ macrolens/ public unified API (load, score, methods, _types)
61
+ dataloader/ canonical loaders + provenance + ablation feature filter
62
+ methods/ registered method classes (excluding _vendored/)
63
+ experiments/ runner + aggregator + re_evaluate
64
+ tools/ provenance + environment verification
65
+ notebooks/ demonstration notebooks
66
+ eval.py per-task scoring functions (T1-T7)
67
+ config.py paths and constants
68
+ benchmark_loader.py
69
+ collect_*.py reconstruction scripts (universe, fundamentals, prices,
70
+ filings, news, real_estate, macro)
71
+ preprocess.py, build_ontology.py, assemble_benchmark.py,
72
+ generate_scenarios.py, enrich_benchmark.py, build_valuation_tasks.py,
73
+ validate_all.py, run_pipeline.py
74
+
75
+ ================================================================================
76
+ VENDORED LIBRARY ACKNOWLEDGEMENTS
77
+ ================================================================================
78
+
79
+ The following libraries are vendored (verbatim or with documented patches)
80
+ under methods/_vendored/. Each retains its upstream copyright notice and
81
+ license. Local patches are documented in methods/_vendored/CHANGES.md.
82
+
83
+ --------------------------------------------------------------------------------
84
+ methods/_vendored/tslib/ DLinear, iTransformer source
85
+ --------------------------------------------------------------------------------
86
+
87
+ Original: https://github.com/thuml/Time-Series-Library
88
+ License: MIT License
89
+
90
+ Copyright (c) 2022 THUML
91
+
92
+ Permission is hereby granted, free of charge, to any person obtaining a copy
93
+ of this software and associated documentation files (the "Software"), to
94
+ deal in the Software without restriction, including without limitation the
95
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
96
+ sell copies of the Software, and to permit persons to whom the Software is
97
+ furnished to do so, subject to the following conditions:
98
+
99
+ The above copyright notice and this permission notice shall be included in
100
+ all copies or substantial portions of the Software.
101
+
102
+ --------------------------------------------------------------------------------
103
+ methods/_vendored/moderntcn/ ModernTCN source
104
+ --------------------------------------------------------------------------------
105
+
106
+ Original: https://github.com/luodhhh/ModernTCN
107
+ License: Apache License, Version 2.0
108
+
109
+ Copyright 2024 Luo Donghao and Wang Xue
110
+
111
+ Licensed under the Apache License, Version 2.0 (the "License");
112
+ you may not use this file except in compliance with the License.
113
+ You may obtain a copy of the License at
114
+
115
+ http://www.apache.org/licenses/LICENSE-2.0
116
+
117
+ Unless required by applicable law or agreed to in writing, software
118
+ distributed under the License is distributed on an "AS IS" BASIS,
119
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
120
+ See the License for the specific language governing permissions and
121
+ limitations under the License.
122
+
123
+ ================================================================================
124
+ UPSTREAM-DATA-PROVIDER NOTICES
125
+ ================================================================================
126
+
127
+ Reconstruction scripts re-fetch from sources whose terms apply to redistribution
128
+ of *raw* artifacts. The MacroLens release ships only derived / curated features:
129
+
130
+ * SEC EDGAR: public domain (US government work). Filings (markdown + PDF,
131
+ 295,860 documents) and XBRL company facts (46.8M) are bundled in the
132
+ HF release. `collect_filings.py` and `collect_fundamentals.py` provided
133
+ for re-fetch.
134
+ * FRED (Federal Reserve Bank of St. Louis): public domain. 46 series
135
+ bundled. `collect_macro.py` provided.
136
+ * EIA (U.S. Energy Information Administration): public domain. 7 series
137
+ bundled. `collect_macro.py` provided.
138
+ * Yahoo Finance (yfinance): non-commercial ToU. The release ships derived
139
+ features (OHLCV + adjusted close + quarterly fundamentals). Users
140
+ redistributing further should respect yfinance ToU. `collect_prices.py`
141
+ + `collect_fundamentals.py` provided for re-fetch.
142
+ * RentCast: GATED — proprietary. Raw listings NOT redistributable; the
143
+ release ships derived address-level features (rent + price targets,
144
+ property attributes) only. To re-fetch raw, users must obtain their own
145
+ RentCast subscription and run `collect_real_estate.py`.
146
+ * Financial-news provider: GATED — provider ToU prohibits redistribution.
147
+ The release ships derived counts (`filing_8k_count_30d`, `news_count_7d`,
148
+ `has_press_release_7d`) only. To re-fetch raw articles, users must
149
+ provide their own news-API key and run `collect_news.py`.
150
+
151
+ ================================================================================
152
+
153
+ By using MacroLens, you agree to honor the upstream-data-provider terms above
154
+ in addition to the CC-BY-4.0 / MIT licenses for the curated artifacts.
README.md ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - time-series-forecasting
5
+ - tabular-regression
6
+ - text-generation
7
+ - question-answering
8
+ language:
9
+ - en
10
+ size_categories:
11
+ - 1M<n<10M
12
+ tags:
13
+ - finance
14
+ - macroeconomic
15
+ - multimodal
16
+ - benchmark
17
+ - sec-edgar
18
+ - xbrl
19
+ - rentcast
20
+ - small-cap
21
+ - russell-2000
22
+ - private-valuation
23
+ - scenario-conditioned-forecasting
24
+ pretty_name: MacroLens
25
+ configs:
26
+ - config_name: panel_daily
27
+ data_files:
28
+ - split: train
29
+ path: data/daily/panel_train.parquet
30
+ - split: test
31
+ path: data/daily/panel_test.parquet
32
+ - config_name: panel_weekly
33
+ data_files:
34
+ - split: train
35
+ path: data/weekly/panel_train.parquet
36
+ - split: test
37
+ path: data/weekly/panel_test.parquet
38
+ - config_name: panel_monthly
39
+ data_files:
40
+ - split: train
41
+ path: data/monthly/panel_train.parquet
42
+ - split: test
43
+ path: data/monthly/panel_test.parquet
44
+ - config_name: scenarios_daily
45
+ data_files: data/daily/scenarios.parquet
46
+ - config_name: valuation_inputs_daily
47
+ data_files: data/daily/valuation_inputs.parquet
48
+ - config_name: private_valuation_inputs_daily
49
+ data_files: data/daily/private_valuation_inputs.parquet
50
+ - config_name: generation_inputs_daily
51
+ data_files: data/daily/generation_inputs.parquet
52
+ - config_name: generation_ground_truth_daily
53
+ data_files: data/daily/generation_ground_truth.parquet
54
+ - config_name: generator_eval_inputs_daily
55
+ data_files: data/daily/generator_eval_inputs.parquet
56
+ - config_name: generator_eval_ground_truth_daily
57
+ data_files: data/daily/generator_eval_ground_truth.parquet
58
+ - config_name: scenario_forecast_ground_truth_daily
59
+ data_files: data/daily/scenario_forecast_ground_truth.parquet
60
+ - config_name: real_estate_train
61
+ data_files: data/real_estate/re_train_properties.parquet
62
+ - config_name: real_estate_eval
63
+ data_files: data/real_estate/re_eval_inputs.parquet
64
+ ---
65
+
66
+ # MacroLens
67
+
68
+ A benchmarking corpus for **contextual financial reasoning under macroeconomic scenarios** across **4,416 U.S. small- and micro-cap equities (2021-01-04 — 2026-03-31)**. MacroLens unifies seven tasks over a single point-in-time panel: contextual time-series forecasting, public valuation, financial-statement generation, scenario-conditioned return forecasting, private-company valuation, generator evaluation from natural-language descriptions, and real-estate valuation.
69
+
70
+ ![visual_summary](https://cdn-uploads.huggingface.co/production/uploads/65dff6bdd546250b182edb86/KXknSZ-_zv23FYNLDkZnu.png)
71
+
72
+ | Task | Type | Output |
73
+ |---|---|---|
74
+ | **T1** Contextual Forecasting | Time-series | Horizon-length close trajectory |
75
+ | **T2** Public Valuation | Tabular regression | Equity market cap |
76
+ | **T3** Financial Statement Generation | Structured generation | 11 canonical XBRL fields per (ticker, fiscal year) |
77
+ | **T4** Scenario-Conditioned Return | Event forecasting | 63-day post-event return percentage |
78
+ | **T5** Private-Company Valuation | Tabular regression (price-stripped) | Equity value w/o market data |
79
+ | **T6** Generator Evaluation | NL→ structured | Same 11 fields from a natural-language company description |
80
+ | **T7** Real-Estate Valuation | Cross-domain regression | Rent + price per RentCast address |
81
+
82
+ Every instance carries a 131-numeric / 141-column point-in-time panel (prices, 46.8M XBRL accounting facts, 53 macroeconomic series, filing recency, derived ratios), an optional macroeconomic scenario object (1,130 events across 49 types), and optional SEC filings + financial-news context. Temporal alignment is strictly point-in-time: every observation visible at prediction timestamp $t$ was publicly available by $t$.
83
+
84
+ ## Quickstart
85
+
86
+ ```python
87
+ import macrolens as ml
88
+
89
+ # 1. Load (X, y, meta) — identical schema across train/test
90
+ X_train, y_train, meta_train = ml.load("T1", "train", granularity="daily")
91
+ X_test, y_test, meta_test = ml.load("T1", "test")
92
+
93
+ # 2. Fit + Predict
94
+ model = ml.methods.LightGBMRegressor(task="T1")
95
+ model.fit(X_train, y_train, seed=42)
96
+ y_pred = model.predict(X_test)
97
+
98
+ # 3. Score (cluster-bootstrap CIs by ticker for T1; adaptive n_boot)
99
+ metrics = ml.score("T1", y_test, y_pred)
100
+ print(metrics["mse"]["value"], metrics["mse"]["ci_lo"], metrics["mse"]["ci_hi"])
101
+ ```
102
+
103
+ 10 lines per task; swap the model class to compare methods.
104
+ ## Dataset structure
105
+
106
+ ```
107
+ data/
108
+ ├── daily/ # primary granularity (4.84M panel rows)
109
+ │ ├── panel_train.parquet # T1, T4 train side
110
+ │ ├── panel_test.parquet # T1, T4 eval side
111
+ │ ├── scenarios.parquet # 1,130 macroeconomic events
112
+ │ ├── valuation_inputs.parquet # T2 features
113
+ │ ├── valuation_ground_truth.parquet # T2 ground truth (market cap)
114
+ │ ├── private_valuation_inputs.parquet # T5 features (price-stripped)
115
+ │ ├── private_valuation_ground_truth.parquet # T5 ground truth
116
+ │ ├── generation_inputs.parquet # T3 fundamentals snapshot
117
+ │ ├── generation_ground_truth.parquet # T3 long-form (ticker, FY, field, value)
118
+ │ ├── generator_eval_inputs.parquet # T6 NL company descriptions
119
+ │ ├── generator_eval_ground_truth.parquet # T6 long-form
120
+ │ └── scenario_forecast_ground_truth.parquet # T4 ground truth
121
+ ├── weekly/ # Friday-close resampled (1.01M rows) — same file set as daily/
122
+ ├── monthly/ # Last-trading-day resampled (232k rows) — same file set as daily/
123
+ ├── real_estate/
124
+ │ ├── re_train_properties.parquet # T7 train (53,804 unique addresses)
125
+ │ ├── re_eval_inputs.parquet # T7 eval (23,190 unique addresses)
126
+ │ └── re_eval_ground_truth.parquet # T7 ground truth (rent + price)
127
+ ├── xbrl/ # 46.8M standardized XBRL facts, 92.6% ticker coverage
128
+ ├── filings/ # 295,860 SEC filings (10-K, 10-Q, 8-K, 20-F, 6-K, N-CSR, N-CSRS) — markdown + PDF
129
+ ├── prices/ # OHLCV + adjusted close (yfinance)
130
+ ├── fundamentals/ # README placeholder only; raw CSVs reproducible via code/collect_fundamentals.py (see note below)
131
+ └── macro/ # 46 FRED + 6 EIA series
132
+
133
+ manifest.json # SHA-256 over every parquet (provenance)
134
+ ```
135
+
136
+ > **Note on `data/fundamentals/`**: Raw per-ticker fundamentals CSVs (~12,000 files: `{TICKER}_balance.csv`, `{TICKER}_income.csv`, `{TICKER}_cashflow.csv`) are **not shipped directly** here because HF enforces a hard cap of 10,000 files per directory. They are reproducible end-to-end via the released pipeline:
137
+ >
138
+ > ```bash
139
+ > python code/collect_fundamentals.py
140
+ > ```
141
+ >
142
+ > The aggregated/processed versions used by the benchmark API (e.g. `valuation_inputs.parquet`, `private_valuation_inputs.parquet`, `generation_inputs.parquet`) are shipped directly under `data/daily/`, `data/weekly/`, `data/monthly/`, and `data/real_estate/`.
143
+
144
+ ## Data sources & access requirements
145
+
146
+ **What's bundled in this HF release** (no user credentials required):
147
+
148
+ | Source | Bundled artifact | License |
149
+ |---|---|---|
150
+ | SEC EDGAR | `filings/` (295k docs), `xbrl/` (46.8M facts) | Public domain (US gov) |
151
+ | FRED | 46 macroeconomic series | Public domain |
152
+ | EIA | 7 commodity series | Public domain |
153
+ | yfinance | `prices/` (OHLCV), `fundamentals/` (quarterly) — derived features | Non-commercial (yfinance ToU) |
154
+ | RentCast | `real_estate/` (address-level derived features only — rent + price targets, property attributes) | RentCast ToU — derived only |
155
+ | Macroeconomic events | `scenarios.parquet` (1,130 events × 49 types) | Curated by us, CC-BY-4.0 |
156
+
157
+ **What's NOT bundled** (gated — user credentials required for raw re-fetch via `collect_*.py`):
158
+
159
+ | Source | Status | User-side requirement |
160
+ |---|---|---|
161
+ | **Financial-news provider** | **Excluded** — provider ToU prohibits redistribution. The release ships derived counts (`filing_8k_count_30d`, `news_count_7d`, `has_press_release_7d`) only. | **User's own news-API key required** for `collect_news.py` |
162
+ | **RentCast raw listings** | **Excluded raw** — proprietary. Derived features bundled. | **User's own RentCast subscription** required for `collect_real_estate.py` raw mode |
163
+
164
+ ## Universe
165
+
166
+ The 4,416-ticker universe combines: full Russell 2000 (1,923 IWM holdings), full S&P SmallCap 600 (72 IJR-only additions), iShares Micro-Cap (225 IWC additions), and 2,196 small-cap NASDAQ/NYSE tickers outside all three indices. The split is **3,857 operating companies + 333 funds + 226 SPACs**, with `security_type` recorded for applicability-aware stratification.
167
+
168
+ ## Splits
169
+
170
+ - **Forecasting (T1, T4)**: chronological 70/30 split at **2024-09-03**.
171
+ - **Valuation + generation (T2, T3, T5, T6)**: **30% company-level holdout = 1,324 tickers** (seed = 42), each contributing its latest valid snapshot.
172
+ - **Real-estate (T7)**: 30% address-level holdout (random, seeded), with per-property time-axis features.
173
+
174
+ Cluster-bootstrap 95% CIs are computed per task: by `ticker` (T1/T2/T3/T5/T6), `scenario_id` (T4), or `address` (T7). Number of bootstrap resamples is adaptive in [1k, 10k] until `(ci_hi - ci_lo) / |mean| < 0.05`.
175
+
176
+ ## Methods (panel)
177
+
178
+ The release ships a 18-method baseline panel across 7 families: 4 naive, 2 classical, 3 deep sequence, 3 zero-shot TSFM, 2 LLM-adapted multi-task systems, 3 zero-shot frontier LLMs (gpt-oss-120b, gpt-5.1, gemini-3-flash + qwen35). Every method registers via `@register(name=…, family=…, tasks=…)` and exposes the sklearn-style `(fit, predict, save, load)` contract.
179
+
180
+ ```python
181
+ ml.list_methods() # all registered methods
182
+ ml.list_methods(task="T1") # methods that support T1
183
+ ml.list_methods(family="naive") # naive baselines
184
+ ```
185
+
186
+ ## License
187
+
188
+ - **Data**: CC-BY-4.0 (derived features + curated panel)
189
+ - **Code**: MIT (`code/macrolens/`, `code/dataloader/`, `code/methods/`, `code/eval.py`, `code/experiments/`)
190
+ - **Vendored libraries** (under `code/methods/_vendored/`):
191
+ - `tslib/` — MIT (DLinear, iTransformer source)
192
+ - `moderntcn/` — Apache 2.0 (ModernTCN source)
193
+ - **Reconstruction scripts** (`collect_*.py`) provided for sources with redistribution restrictions: SEC filings (re-fetch from EDGAR), financial news (re-fetch from provider), real-estate (re-fetch from RentCast).
194
+
195
+ ## Citation
196
+
197
+ ```bibtex
198
+ @inproceedings{macrolens2026,
199
+ title = {{MacroLens}: A Multi-Task Benchmark for Contextual Financial Reasoning under Macroeconomic Scenarios},
200
+ author = {<authors>},
201
+ booktitle = {NeurIPS 2026 Evaluations & Datasets Track submission},
202
+ year = {2026}
203
+ }
204
+ ```
205
+
206
+ ## Reproducibility
207
+
208
+ When `code/experiments/run_all.py` is executed, each method run produces a `RunRecord` JSON under `code/experiments/results/` recording: `git_sha`, `lib_versions`, `hardware`, `artifact_sha256` (SHA-256 of every parquet read), `timestamp`, and `deterministic_mode`. Predictions are also persisted at `code/experiments/predictions/<method>_<task>_seed<seed>.pkl` so eval logic can be re-applied via `code/experiments/re_evaluate.py` without re-running the models. These output directories are not shipped on Hugging Face — reviewers reproduce them by running the released code.
209
+
210
+ ## Reconstruction (raw filings + news)
211
+
212
+ The release ships derived features and reconstruction scripts; raw artifacts subject to redistribution restrictions remain re-fetchable:
213
+
214
+ ```bash
215
+ python collect_universe.py # iShares ETF holdings + NASDAQ Trader directory
216
+ python collect_filings.py # SEC EDGAR (10-K, 10-Q, 8-K, 20-F, 6-K, N-CSR, N-CSRS)
217
+ python collect_fundamentals.py # XBRL company facts via SEC EDGAR
218
+ python collect_prices.py # yfinance OHLCV + adjusted close
219
+ python collect_news.py # provider-specific (~215k articles)
220
+ python collect_real_estate.py # RentCast (100 metros, 139,855 properties)
221
+ python collect_macro.py # FRED + EIA series
222
+ python preprocess.py
223
+ python assemble_benchmark.py
224
+ python generate_scenarios.py
225
+ python enrich_benchmark.py
226
+ python build_valuation_tasks.py
227
+ python validate_all.py
228
+ ```
229
+
230
+ ## Authors / Contact
231
+
232
+ Anonymous (NeurIPS 2026 Evaluations & Datasets Track submission). Contact at `<email>` after author notification.
code/assemble_benchmark.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer 3 – Step 8: Assemble benchmark artifacts from the processed panel.
2
+
3
+ Reads ``data/processed/{granularity}/panel.parquet`` and produces:
4
+
5
+ data/benchmark/{granularity}/panel_train.parquet
6
+ data/benchmark/{granularity}/panel_test.parquet
7
+ data/benchmark/{granularity}/panel_full.csv (CSV compatibility)
8
+ data/benchmark/{granularity}/task_definition.json
9
+ data/benchmark/{granularity}/filing_corpus.parquet
10
+ data/benchmark/{granularity}/metadata.json
11
+
12
+ Does NOT re-process raw data. All heavy lifting happened in
13
+ ``preprocess.py`` (Layer 2).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import logging
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ from . import config
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ # ------------------------------------------------------------------
31
+ # Filing corpus
32
+ # ------------------------------------------------------------------
33
+
34
+ def _build_filing_corpus() -> pd.DataFrame:
35
+ """Build a filing corpus index from ``data/filings/{TICKER}/*.md``.
36
+
37
+ Stores only **metadata** (ticker, filing_type, filing_date, filing_path)
38
+ -- NOT the full text -- to avoid OOM with thousands of large filings.
39
+ Text is loaded on-demand by ``benchmark_loader.py`` using ``filing_path``.
40
+
41
+ Columns: ticker, filing_type, filing_date, filing_path, text_length.
42
+ """
43
+ import re as _re
44
+
45
+ rows: list[dict] = []
46
+ if not config.FILINGS_DIR.is_dir():
47
+ logger.warning("Filings directory does not exist: %s", config.FILINGS_DIR)
48
+ return pd.DataFrame(columns=["ticker", "filing_type", "filing_date", "filing_path", "text_length"])
49
+
50
+ for ticker_dir in sorted(config.FILINGS_DIR.iterdir()):
51
+ if not ticker_dir.is_dir():
52
+ continue
53
+ ticker = ticker_dir.name
54
+ for md_file in sorted(ticker_dir.glob("*.md")):
55
+ ftype = "10-K" if "10-K" in md_file.name else "10-Q" if "10-Q" in md_file.name else "8-K" if "8-K" in md_file.name else "other"
56
+ match = _re.search(r"(\d{4}-\d{2}-\d{2})", md_file.name)
57
+ fdate = match.group(1) if match else None
58
+ # Only measure length (not load entire text into memory)
59
+ try:
60
+ text_len = md_file.stat().st_size
61
+ except Exception:
62
+ text_len = 0
63
+ rows.append({
64
+ "ticker": ticker,
65
+ "filing_type": ftype,
66
+ "filing_date": fdate,
67
+ "filing_path": str(md_file.relative_to(config.DATA_DIR)),
68
+ "text_length": text_len,
69
+ })
70
+
71
+ df = pd.DataFrame(rows)
72
+ if not df.empty and "filing_date" in df.columns:
73
+ df["filing_date"] = pd.to_datetime(df["filing_date"], errors="coerce")
74
+ logger.info("Filing corpus index: %d documents across %d tickers.",
75
+ len(df), df["ticker"].nunique() if not df.empty else 0)
76
+ return df
77
+
78
+
79
+ # ------------------------------------------------------------------
80
+ # Task definition
81
+ # ------------------------------------------------------------------
82
+
83
+ def _build_task_definition(panel: pd.DataFrame, granularity: str) -> dict:
84
+ """Create the formal forecasting-task contract."""
85
+ # Read column roles from the processed output
86
+ col_roles_path = config.DATA_DIR / "processed" / granularity / "columns.json"
87
+ if col_roles_path.exists():
88
+ column_roles = json.loads(col_roles_path.read_text())
89
+ else:
90
+ column_roles = {}
91
+
92
+ return {
93
+ "benchmark_name": "MacroLens",
94
+ "version": "1.0",
95
+ "granularity": granularity,
96
+ "targets": {
97
+ "primary": "close",
98
+ "secondary": "volume",
99
+ },
100
+ "horizons": config.get_horizons(granularity),
101
+ "lookback_windows": config.get_lookback_windows(granularity),
102
+ "column_roles": column_roles,
103
+ "context_taxonomy": {
104
+ "historical": "10-K / 10-Q filing text (nearest filing as-of each date)",
105
+ "covariate": "FRED / EIA macro indicators (exogenous_macro + exogenous_commodity)",
106
+ "causal": "Fundamental ratios derived from statements + price (exogenous_fundamental)",
107
+ "future_scenario": "Natural experiment events detected from macro data (scenarios.parquet)",
108
+ "intemporal": "Sector / industry knowledge (metadata columns)",
109
+ },
110
+ "evaluation": {
111
+ "metrics": ["MSE", "MAE", "RMSE", "directional_accuracy"],
112
+ "baseline": "naive_last_value",
113
+ "primary_metric": "MSE",
114
+ },
115
+ "scenario_method": "natural_experiments",
116
+ }
117
+
118
+
119
+ # ------------------------------------------------------------------
120
+ # Public API
121
+ # ------------------------------------------------------------------
122
+
123
+ def run(granularity: str | None = None) -> None:
124
+ """Execute Layer 3 benchmark assembly."""
125
+ if granularity is None:
126
+ granularity = config.GRANULARITY
127
+
128
+ panel_path = config.DATA_DIR / "processed" / granularity / "panel.parquet"
129
+ if not panel_path.exists():
130
+ raise FileNotFoundError(f"Run Step 7 (preprocess) first: {panel_path}")
131
+
132
+ out_dir = config.DATA_DIR / "benchmark" / granularity
133
+ out_dir.mkdir(parents=True, exist_ok=True)
134
+
135
+ # ---- Load processed panel ------------------------------------------------
136
+ panel = pd.read_parquet(panel_path)
137
+ logger.info("Loaded processed panel: %d rows, %d tickers, %d columns.",
138
+ len(panel), panel["ticker"].nunique(), len(panel.columns))
139
+
140
+ # ---- Temporal split ------------------------------------------------------
141
+ if config.TEMPORAL_SPLIT_DATE is not None:
142
+ split_date = pd.Timestamp(config.TEMPORAL_SPLIT_DATE)
143
+ else:
144
+ unique_dates = np.sort(panel["date"].unique())
145
+ split_idx = int(len(unique_dates) * config.TEMPORAL_SPLIT_RATIO)
146
+ split_idx = max(1, min(split_idx, len(unique_dates) - 1))
147
+ split_date = pd.Timestamp(unique_dates[split_idx])
148
+ logger.info("Ratio-based split (%.0f:%.0f): split date = %s (%d/%d unique dates)",
149
+ config.TEMPORAL_SPLIT_RATIO * 100,
150
+ (1 - config.TEMPORAL_SPLIT_RATIO) * 100,
151
+ split_date.date(), split_idx, len(unique_dates))
152
+
153
+ panel["split"] = np.where(panel["date"] < split_date, "train", "test")
154
+ train = panel[panel["split"] == "train"]
155
+ test = panel[panel["split"] == "test"]
156
+
157
+ # Cold-start tickers: IPOs that appear only in the test period.
158
+ # Kept intentionally — tests model generalisation to unseen companies.
159
+ train_tickers = set(train["ticker"].unique())
160
+ test_only = set(test["ticker"].unique()) - train_tickers
161
+ if test_only:
162
+ logger.info("%d cold-start tickers in test (IPOs).", len(test_only))
163
+
164
+ train.to_parquet(out_dir / "panel_train.parquet", index=False)
165
+ test.to_parquet(out_dir / "panel_test.parquet", index=False)
166
+ panel.to_csv(out_dir / "panel_full.csv", index=False)
167
+ logger.info("Saved train (%d rows) + test (%d rows) + CSV.", len(train), len(test))
168
+
169
+ # ---- Task definition -----------------------------------------------------
170
+ task_def = _build_task_definition(panel, granularity)
171
+ (out_dir / "task_definition.json").write_text(json.dumps(task_def, indent=2, default=str))
172
+ logger.info("Saved task_definition.json.")
173
+
174
+ # ---- Filing corpus -------------------------------------------------------
175
+ corpus = _build_filing_corpus()
176
+ if not corpus.empty:
177
+ corpus.to_parquet(out_dir / "filing_corpus.parquet", index=False)
178
+ logger.info("Saved filing_corpus.parquet (%d documents).", len(corpus))
179
+
180
+ # ---- Metadata ------------------------------------------------------------
181
+ metadata = {
182
+ "format": "panel_data",
183
+ "granularity": granularity,
184
+ "primary_key": ["ticker", "date"],
185
+ "total_rows": len(panel),
186
+ "total_tickers": int(panel["ticker"].nunique()),
187
+ "date_range": {
188
+ "start": str(panel["date"].min().date()),
189
+ "end": str(panel["date"].max().date()),
190
+ },
191
+ "temporal_split": {
192
+ "split_date": str(split_date.date()),
193
+ "split_method": (
194
+ "fixed_date" if config.TEMPORAL_SPLIT_DATE
195
+ else f"ratio_{config.TEMPORAL_SPLIT_RATIO}"
196
+ ),
197
+ "train_rows": len(train),
198
+ "test_rows": len(test),
199
+ "train_date_range": {
200
+ "start": str(train["date"].min().date()) if len(train) > 0 else None,
201
+ "end": str(train["date"].max().date()) if len(train) > 0 else None,
202
+ },
203
+ "test_date_range": {
204
+ "start": str(test["date"].min().date()) if len(test) > 0 else None,
205
+ "end": str(test["date"].max().date()) if len(test) > 0 else None,
206
+ },
207
+ },
208
+ "label_distribution": panel["label"].value_counts().to_dict() if "label" in panel.columns else {},
209
+ "columns": list(panel.columns),
210
+ "column_count": len(panel.columns),
211
+ "column_roles": task_def.get("column_roles", {}),
212
+ "filing_corpus_stats": {
213
+ "total_documents": len(corpus),
214
+ "tickers_with_filings": int(corpus["ticker"].nunique()) if not corpus.empty else 0,
215
+ },
216
+ "evaluation_protocol": task_def.get("evaluation", {}),
217
+ }
218
+ (out_dir / "metadata.json").write_text(json.dumps(metadata, indent=2, default=str))
219
+ logger.info("Saved metadata.json. Base benchmark assembly complete -> %s", out_dir)
220
+
221
+ # ---- Valuation benchmark (Tasks A–F) ---------------------------------
222
+ try:
223
+ from .build_valuation_tasks import build_valuation_benchmark
224
+ logger.info("Building valuation benchmark artifacts (%s) …", granularity)
225
+ val_summary = build_valuation_benchmark(granularity=granularity)
226
+ logger.info("Valuation benchmark: %s", val_summary)
227
+ except Exception:
228
+ logger.warning("Valuation benchmark build skipped or failed", exc_info=True)
code/benchmark_loader.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Runtime: Hybrid DataLoader for the MacroLens benchmark.
2
+
3
+ Provides ``WhatIfTSFDataset`` -- a lightweight, on-the-fly instance
4
+ generator that reads from pre-built benchmark artifacts
5
+ (``panel_train.parquet`` / ``panel_test.parquet``, ``scenarios.parquet``,
6
+ ``filing_corpus.parquet``).
7
+
8
+ One "instance" = a tuple of:
9
+ (lookback_window, forecast_target, context_dict)
10
+
11
+ where ``context_dict`` holds metadata, filing text, macro, and any scenario
12
+ information that falls within the instance's time window.
13
+
14
+ Usage example
15
+ -------------
16
+ .. code-block:: python
17
+
18
+ from whatif_bench.benchmark_loader import WhatIfTSFDataset
19
+
20
+ # Defaults to granularity-appropriate lookback/horizon from config
21
+ ds = WhatIfTSFDataset(split="train")
22
+ print(len(ds)) # total number of sliding-window instances
23
+ sample = ds[0] # dict with 'lookback', 'target', 'context'
24
+
25
+ # Each scenario in context["scenarios"] has a "scenario_role" field:
26
+ # "observed" = already happened (in lookback window)
27
+ # "hypothetical" = in forecast horizon (the "what-if" condition)
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ import logging
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+ import numpy as np
38
+ import pandas as pd
39
+
40
+ from . import config
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+
45
+ class WhatIfTSFDataset:
46
+ """Sliding-window dataset over the MacroLens benchmark panel.
47
+
48
+ Parameters
49
+ ----------
50
+ split : str
51
+ ``"train"`` or ``"test"``.
52
+ lookback : int, optional
53
+ Number of past time-steps visible to the model (in panel periods).
54
+ Defaults to the first entry of ``config.LOOKBACK_WINDOWS_BY_GRANULARITY``
55
+ for the chosen granularity (63 for daily, 13 for weekly, 3 for monthly).
56
+ horizon : int, optional
57
+ Number of future time-steps to predict (in panel periods).
58
+ Defaults to the first entry of ``config.HORIZONS_BY_GRANULARITY``
59
+ for the chosen granularity (5 for daily, 4 for weekly, 1 for monthly).
60
+ granularity : str, optional
61
+ Defaults to ``config.GRANULARITY``.
62
+ target_col : str
63
+ Column name of the prediction target. Default: ``"close"``.
64
+ load_text : bool
65
+ If True, load ``filing_corpus.parquet`` and attach filing text to
66
+ context. Set to False for fast iteration.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ split: str = "train",
72
+ lookback: int | None = None,
73
+ horizon: int | None = None,
74
+ granularity: str | None = None,
75
+ target_col: str = "close",
76
+ load_text: bool = True,
77
+ ) -> None:
78
+ if granularity is None:
79
+ granularity = config.GRANULARITY
80
+ self.granularity = granularity
81
+ self.split = split
82
+
83
+ # Granularity-aware defaults from config
84
+ if lookback is None:
85
+ lookback = config.get_lookback_windows(granularity)[0]
86
+ if horizon is None:
87
+ horizon = config.get_horizons(granularity)[0]
88
+ self.lookback = lookback
89
+ self.horizon = horizon
90
+ self.target_col = target_col
91
+
92
+ bench_dir = config.DATA_DIR / "benchmark" / granularity
93
+
94
+ # ---- Load panel split ------------------------------------------------
95
+ panel_path = bench_dir / f"panel_{split}.parquet"
96
+ if not panel_path.exists():
97
+ raise FileNotFoundError(f"Benchmark not assembled: {panel_path}")
98
+ self._panel = pd.read_parquet(panel_path)
99
+ self._panel["date"] = pd.to_datetime(self._panel["date"])
100
+ self._panel = self._panel.sort_values(["ticker", "date"]).reset_index(drop=True)
101
+
102
+ # ---- Validate target column exists -----------------------------------
103
+ if target_col not in self._panel.columns:
104
+ available = [c for c in self._panel.columns if self._panel[c].dtype.kind in "fiub"]
105
+ raise ValueError(
106
+ f"target_col={target_col!r} not in panel columns. "
107
+ f"Available numeric columns: {available}"
108
+ )
109
+
110
+ # ---- Build instance index (ticker, start_idx, end_idx) ---------------
111
+ self._instances: list[tuple[str, int, int]] = []
112
+ required_len = lookback + horizon
113
+ for ticker, grp in self._panel.groupby("ticker"):
114
+ n = len(grp)
115
+ if n < required_len:
116
+ continue
117
+ start_positions = range(n - required_len + 1)
118
+ grp_idx = grp.index.tolist()
119
+ for s in start_positions:
120
+ self._instances.append((ticker, grp_idx[s], grp_idx[s + required_len - 1]))
121
+
122
+ # ---- Scenarios -------------------------------------------------------
123
+ scenarios_path = bench_dir / "scenarios.parquet"
124
+ if scenarios_path.exists():
125
+ self._scenarios = pd.read_parquet(scenarios_path)
126
+ self._scenarios["event_date"] = pd.to_datetime(self._scenarios["event_date"])
127
+ else:
128
+ self._scenarios = pd.DataFrame()
129
+
130
+ # ---- Filing corpus index (optional, text loaded on-demand) -----------
131
+ self._corpus: pd.DataFrame | None = None
132
+ self._corpus_by_ticker: dict[str, pd.DataFrame] = {}
133
+ if load_text:
134
+ corpus_path = bench_dir / "filing_corpus.parquet"
135
+ if corpus_path.exists():
136
+ self._corpus = pd.read_parquet(corpus_path)
137
+ self._corpus["filing_date"] = pd.to_datetime(
138
+ self._corpus["filing_date"], errors="coerce",
139
+ )
140
+ self._corpus = self._corpus.sort_values("filing_date")
141
+ # Pre-build per-ticker index for O(1) lookup
142
+ for ticker, grp in self._corpus.groupby("ticker"):
143
+ self._corpus_by_ticker[str(ticker)] = grp
144
+
145
+ # ---- Task definition -------------------------------------------------
146
+ task_path = bench_dir / "task_definition.json"
147
+ self.task_definition: dict = {}
148
+ if task_path.exists():
149
+ self.task_definition = json.loads(task_path.read_text())
150
+
151
+ n_tickers = self._panel["ticker"].nunique()
152
+ logger.info(
153
+ "WhatIfTSFDataset(%s/%s, lookback=%d, horizon=%d): %d instances from %d tickers.",
154
+ split, granularity, lookback, horizon, len(self._instances), n_tickers,
155
+ )
156
+ if len(self._instances) == 0 and n_tickers > 0:
157
+ max_len = self._panel.groupby("ticker").size().max()
158
+ logger.warning(
159
+ "ZERO instances generated! lookback(%d) + horizon(%d) = %d periods required, "
160
+ "but longest ticker has only %d periods. "
161
+ "Consider using smaller lookback/horizon values for %s granularity. "
162
+ "Suggested defaults: lookback=%d, horizon=%d.",
163
+ lookback, horizon, lookback + horizon, max_len, granularity,
164
+ config.get_lookback_windows(granularity)[0],
165
+ config.get_horizons(granularity)[0],
166
+ )
167
+
168
+ # ------------------------------------------------------------------
169
+ # Sequence protocol
170
+ # ------------------------------------------------------------------
171
+
172
+ def __len__(self) -> int:
173
+ return len(self._instances)
174
+
175
+ def canonical_indices(self, task: str = "T1") -> list[int]:
176
+ """Return the dataset-instance indices matching the canonical
177
+ ``(ticker, anchor_date)`` pairs from
178
+ ``dataloader.canonical_indices.get_canonical_indices(task)``.
179
+
180
+ For T1, ``anchor_date`` is the lookback-end date (i.e. the latest
181
+ date in the window). Every T1 baseline must iterate exactly these
182
+ indices so cross-method comparison is on identical instances.
183
+ """
184
+ from .dataloader.canonical_indices import get_canonical_indices
185
+
186
+ canonical = get_canonical_indices(
187
+ task, "eval", granularity=self.granularity,
188
+ )
189
+ canonical_set = {
190
+ (str(t), pd.Timestamp(a))
191
+ for t, a in zip(
192
+ canonical["ticker"].astype(str),
193
+ pd.to_datetime(canonical["anchor_date"]),
194
+ )
195
+ }
196
+ out: list[int] = []
197
+ for i, (ticker, row_start, _row_end) in enumerate(self._instances):
198
+ lookback_end_date = pd.Timestamp(
199
+ self._panel.loc[row_start + self.lookback - 1, "date"]
200
+ )
201
+ if (str(ticker), lookback_end_date) in canonical_set:
202
+ out.append(i)
203
+ return out
204
+
205
+ def __getitem__(self, idx: int) -> dict[str, Any]:
206
+ if idx < 0 or idx >= len(self._instances):
207
+ raise IndexError(f"Index {idx} out of range [0, {len(self._instances)})")
208
+ ticker, row_start, row_end = self._instances[idx]
209
+
210
+ window = self._panel.loc[row_start: row_end].copy()
211
+ lookback_df = window.iloc[: self.lookback]
212
+ target_df = window.iloc[self.lookback:]
213
+
214
+ date_start = lookback_df["date"].iloc[0]
215
+ date_end = target_df["date"].iloc[-1]
216
+
217
+ # Numeric feature columns
218
+ exclude = {"ticker", "date", "label", "split",
219
+ "nearest_filing_type", "nearest_filing_date", "nearest_filing_path"}
220
+ feat_cols = [c for c in lookback_df.columns if c not in exclude and lookback_df[c].dtype.kind in "fiub"]
221
+
222
+ # Context
223
+ context: dict[str, Any] = {
224
+ "ticker": ticker,
225
+ "date_start": str(date_start.date()),
226
+ "date_end": str(date_end.date()),
227
+ "sector": lookback_df.get("sector", pd.Series()).iloc[0] if "sector" in lookback_df.columns else None,
228
+ "industry": lookback_df.get("industry", pd.Series()).iloc[0] if "industry" in lookback_df.columns else None,
229
+ "label": lookback_df["label"].iloc[0] if "label" in lookback_df.columns else None,
230
+ }
231
+
232
+ # Macro state summary for LLM agents -- human-readable snapshot of the
233
+ # latest macro values at the lookback end.
234
+ _MACRO_LABELS = {
235
+ "fred_FEDFUNDS": "Fed Funds Rate",
236
+ "fred_DGS2": "2Y Treasury",
237
+ "fred_DGS10": "10Y Treasury",
238
+ "fred_VIXCLS": "VIX",
239
+ "fred_SP500": "S&P 500",
240
+ "fred_NASDAQCOM": "NASDAQ",
241
+ "fred_DTWEXBGS": "USD Index",
242
+ "eia_crude_spot": "WTI Crude ($/bbl)",
243
+ "eia_ng_spot": "Nat Gas ($/MMBtu)",
244
+ }
245
+ macro_snapshot: dict[str, float | str] = {}
246
+ last_row = lookback_df.iloc[-1]
247
+ for col, label in _MACRO_LABELS.items():
248
+ if col in lookback_df.columns:
249
+ val = last_row[col]
250
+ if pd.notna(val):
251
+ macro_snapshot[label] = round(float(val), 2)
252
+ if macro_snapshot:
253
+ context["macro_state"] = macro_snapshot
254
+
255
+ # Filing text (nearest 10-K/10-Q as-of the lookback end) -- O(1) dict lookup
256
+ if self._corpus_by_ticker:
257
+ lookback_end = lookback_df["date"].iloc[-1]
258
+ ticker_filings = self._corpus_by_ticker.get(ticker)
259
+ if ticker_filings is not None:
260
+ valid = ticker_filings[ticker_filings["filing_date"] <= lookback_end]
261
+ if not valid.empty:
262
+ # Nearest 10-K/10-Q for primary filing context
263
+ annual_q = valid[valid["filing_type"].isin(["10-K", "10-Q"])]
264
+ if not annual_q.empty:
265
+ latest = annual_q.iloc[-1]
266
+ context["filing_type"] = latest.get("filing_type", "")
267
+ context["filing_date"] = str(latest.get("filing_date", ""))
268
+ filing_path = latest.get("filing_path", "")
269
+ if filing_path:
270
+ full_path = config.DATA_DIR / filing_path
271
+ try:
272
+ context["filing_text"] = full_path.read_text(
273
+ encoding="utf-8", errors="replace"
274
+ )
275
+ except Exception:
276
+ context["filing_text"] = ""
277
+ else:
278
+ context["filing_text"] = ""
279
+
280
+ # 8-K filings within the lookback window
281
+ lookback_start = lookback_df["date"].iloc[0]
282
+ eightk = valid[
283
+ (valid["filing_type"] == "8-K")
284
+ & (valid["filing_date"] >= lookback_start)
285
+ ]
286
+ if not eightk.empty:
287
+ eightk_texts = []
288
+ for _, row in eightk.iterrows():
289
+ fp = row.get("filing_path", "")
290
+ if fp:
291
+ full_path = config.DATA_DIR / fp
292
+ try:
293
+ eightk_texts.append(full_path.read_text(
294
+ encoding="utf-8", errors="replace"
295
+ ))
296
+ except Exception:
297
+ pass
298
+ if eightk_texts:
299
+ context["filing_8k_texts"] = eightk_texts
300
+
301
+ # Recent news from yfinance per-ticker JSON
302
+ news_path = config.NEWS_DIR / "tickers" / f"{ticker}.json"
303
+ if news_path.exists():
304
+ try:
305
+ all_news = json.loads(news_path.read_text(encoding="utf-8"))
306
+ lookback_end_dt = lookback_df["date"].iloc[-1]
307
+ lookback_start_dt = lookback_df["date"].iloc[0]
308
+ recent = []
309
+ for art in all_news:
310
+ pub = art.get("pubDate") or art.get("pub_date") or art.get("providerPublishTime")
311
+ if pub is None:
312
+ continue
313
+ try:
314
+ ts = pd.Timestamp(pub)
315
+ except Exception:
316
+ continue
317
+ if lookback_start_dt <= ts <= lookback_end_dt:
318
+ recent.append(art)
319
+ if recent:
320
+ context["recent_news"] = recent
321
+ except Exception:
322
+ pass
323
+
324
+ # Scenario overlay -- label each as "observed" (in lookback) or
325
+ # "hypothetical" (in forecast horizon), which is the core semantic
326
+ # distinction for what-if evaluation.
327
+ if not self._scenarios.empty:
328
+ lookback_end = lookback_df["date"].iloc[-1]
329
+ overlapping = self._scenarios[
330
+ (self._scenarios["event_date"] >= date_start)
331
+ & (self._scenarios["event_date"] <= date_end)
332
+ ].copy()
333
+ if not overlapping.empty:
334
+ overlapping["scenario_role"] = np.where(
335
+ overlapping["event_date"] <= lookback_end,
336
+ "observed", # Already happened -- model should know this
337
+ "hypothetical", # In forecast window -- the "what-if" condition
338
+ )
339
+ sc_cols = [
340
+ "scenario_id", "event_type", "event_date",
341
+ "event_description", "scenario_role",
342
+ ]
343
+ # Include news_context if available
344
+ if "news_context" in self._scenarios.columns:
345
+ sc_cols.append("news_context")
346
+ context["scenarios"] = overlapping[
347
+ [c for c in sc_cols if c in overlapping.columns]
348
+ ].to_dict("records")
349
+
350
+ return {
351
+ "lookback": lookback_df[feat_cols].values.astype(np.float32),
352
+ "lookback_dates": lookback_df["date"].dt.strftime("%Y-%m-%d").tolist(),
353
+ "target": target_df[self.target_col].values.astype(np.float32),
354
+ "target_dates": target_df["date"].dt.strftime("%Y-%m-%d").tolist(),
355
+ "context": context,
356
+ "feature_names": feat_cols,
357
+ }
358
+
359
+ # ------------------------------------------------------------------
360
+ # Convenience
361
+ # ------------------------------------------------------------------
362
+
363
+ def summary(self) -> dict[str, Any]:
364
+ """Quick dataset summary statistics."""
365
+ return {
366
+ "split": self.split,
367
+ "granularity": self.granularity,
368
+ "lookback": self.lookback,
369
+ "horizon": self.horizon,
370
+ "num_instances": len(self._instances),
371
+ "num_tickers": self._panel["ticker"].nunique(),
372
+ "date_range": [
373
+ str(self._panel["date"].min().date()),
374
+ str(self._panel["date"].max().date()),
375
+ ],
376
+ "num_scenarios": len(self._scenarios),
377
+ "corpus_loaded": self._corpus is not None and not self._corpus.empty,
378
+ }
379
+
380
+
381
+ # ===================================================================
382
+ # ValuationDataset: point-in-time valuation benchmark loader
383
+ # ===================================================================
384
+
385
+ class ValuationDataset:
386
+ """Dataset for valuation benchmark tasks (A–F).
387
+
388
+ Each instance is a point-in-time snapshot suitable for:
389
+ Task A: estimate equity value given observable financials (public company)
390
+ Task B: generate financial statements given company profile
391
+ Task C: forecast scenario impact given pre-event data
392
+ Task D: estimate equity value given only financials + sector (PE simulation)
393
+ Task E: generate financial statements for unseen companies (Generator eval)
394
+ Task F: estimate rent/price for properties (RE valuation)
395
+
396
+ Parameters
397
+ ----------
398
+ task : str
399
+ ``"A"``–``"F"`` (or full name like ``"valuation_accuracy"``).
400
+ granularity : str
401
+ Defaults to ``config.GRANULARITY``.
402
+ """
403
+
404
+ _TASK_MAP = {
405
+ "A": "A_valuation_accuracy",
406
+ "B": "B_statement_generation",
407
+ "C": "C_scenario_forecast",
408
+ "D": "D_private_valuation",
409
+ "E": "E_generator_evaluation",
410
+ "F": "F_real_estate_valuation",
411
+ "valuation_accuracy": "A_valuation_accuracy",
412
+ "statement_generation": "B_statement_generation",
413
+ "scenario_forecast": "C_scenario_forecast",
414
+ "private_valuation": "D_private_valuation",
415
+ "generator_evaluation": "E_generator_evaluation",
416
+ "real_estate_valuation": "F_real_estate_valuation",
417
+ }
418
+
419
+ def __init__(
420
+ self,
421
+ task: str = "A",
422
+ granularity: str | None = None,
423
+ ) -> None:
424
+ if granularity is None:
425
+ granularity = config.GRANULARITY
426
+ self.granularity = granularity
427
+ self.task = self._TASK_MAP.get(task, task)
428
+
429
+ bench_dir = config.DATA_DIR / "benchmark" / granularity
430
+
431
+ # Load task definitions
432
+ task_path = bench_dir / "valuation_tasks.json"
433
+ if task_path.exists():
434
+ self.task_definitions = json.loads(task_path.read_text())
435
+ else:
436
+ self.task_definitions = {}
437
+
438
+ task_def = self.task_definitions.get("tasks", {}).get(self.task, {})
439
+ input_file = task_def.get("input")
440
+ gt_file = task_def.get("ground_truth")
441
+
442
+ # Load inputs
443
+ self._inputs = pd.DataFrame()
444
+ if input_file:
445
+ p = bench_dir / input_file
446
+ if p.exists():
447
+ self._inputs = pd.read_parquet(p) if p.suffix == ".parquet" else pd.read_csv(p)
448
+
449
+ # Load ground truth
450
+ self._ground_truth = pd.DataFrame()
451
+ if gt_file:
452
+ p = bench_dir / gt_file
453
+ if p.exists():
454
+ self._ground_truth = pd.read_parquet(p) if p.suffix == ".parquet" else pd.read_csv(p)
455
+
456
+ # Holdout tickers
457
+ self.holdout_tickers = self.task_definitions.get("holdout_tickers", [])
458
+
459
+ logger.info(
460
+ "ValuationDataset(task=%s, gran=%s): %d inputs, %d ground_truth rows",
461
+ self.task, granularity, len(self._inputs), len(self._ground_truth),
462
+ )
463
+
464
+ @property
465
+ def inputs(self) -> pd.DataFrame:
466
+ return self._inputs
467
+
468
+ @property
469
+ def ground_truth(self) -> pd.DataFrame:
470
+ return self._ground_truth
471
+
472
+ def __len__(self) -> int:
473
+ return len(self._inputs)
474
+
475
+ def __getitem__(self, idx: int) -> dict[str, Any]:
476
+ if idx < 0 or idx >= len(self._inputs):
477
+ raise IndexError(f"Index {idx} out of range [0, {len(self._inputs)})")
478
+
479
+ row = self._inputs.iloc[idx]
480
+ item: dict[str, Any] = {"input": row.to_dict()}
481
+
482
+ # Attach ground truth if available
483
+ if not self._ground_truth.empty:
484
+ if self.task in ("A_valuation_accuracy", "D_private_valuation"):
485
+ tk = row.get("ticker")
486
+ dt = row.get("date")
487
+ match = self._ground_truth[
488
+ (self._ground_truth["ticker"] == tk)
489
+ & (self._ground_truth["date"] == dt)
490
+ ]
491
+ if not match.empty:
492
+ item["ground_truth"] = match.iloc[0].to_dict()
493
+ elif self.task in ("B_statement_generation", "E_generator_evaluation"):
494
+ tk = row.get("ticker")
495
+ match = self._ground_truth[self._ground_truth["ticker"] == tk]
496
+ if not match.empty:
497
+ item["ground_truth"] = match.to_dict("records")
498
+ elif self.task == "C_scenario_forecast":
499
+ sid = row.get("scenario_id")
500
+ if sid:
501
+ match = self._ground_truth[self._ground_truth["scenario_id"] == sid]
502
+ if not match.empty:
503
+ item["ground_truth"] = match.to_dict("records")
504
+ elif self.task == "F_real_estate_valuation":
505
+ # Match by index position (inputs and GT are aligned)
506
+ if idx < len(self._ground_truth):
507
+ item["ground_truth"] = self._ground_truth.iloc[idx].to_dict()
508
+
509
+ return item
510
+
511
+ def summary(self) -> dict[str, Any]:
512
+ """Quick dataset summary."""
513
+ s: dict[str, Any] = {
514
+ "task": self.task,
515
+ "granularity": self.granularity,
516
+ "n_inputs": len(self._inputs),
517
+ "n_ground_truth": len(self._ground_truth),
518
+ "n_holdout_tickers": len(self.holdout_tickers),
519
+ }
520
+ if not self._inputs.empty and "ticker" in self._inputs.columns:
521
+ s["n_tickers"] = self._inputs["ticker"].nunique()
522
+ return s
code/build_ontology.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build industry-level XBRL ontology + company-level extracted fields.
2
+
3
+ Reads raw XBRL company facts (``data/xbrl/raw/{TICKER}.json``) and the
4
+ universe file to:
5
+
6
+ 1. **Parse** all 10-K / 10-Q facts into a normalised table.
7
+ 2. **Group** by sector and industry (from ``company_info.csv``).
8
+ 3. **Classify** each tag per industry:
9
+ - **core** – appears in ≥70 % of companies in the industry
10
+ - **common** – appears in ≥30 %
11
+ - **extension** – appears in <30 % (often company-specific XBRL extensions)
12
+ 4. **Output**:
13
+ - ``data/xbrl/parsed/company_facts.parquet`` – all extracted facts
14
+ - ``data/xbrl/parsed/company_tags.parquet`` – per-company tag list (latest value)
15
+ - ``data/xbrl/ontology/industry_ontology.json`` – per-industry tag classification
16
+ - ``data/xbrl/ontology/tag_catalog.parquet`` – master tag catalog with labels
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import logging
23
+ from collections import defaultdict
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ from . import config
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ _RAW_DIR = config.XBRL_DIR / "raw"
34
+ _PARSED_DIR = config.XBRL_DIR / "parsed"
35
+ _ONTOLOGY_DIR = config.XBRL_DIR / "ontology"
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Step 1: Parse raw company facts into a flat table
40
+ # ---------------------------------------------------------------------------
41
+
42
+ def _parse_single_company(
43
+ ticker: str,
44
+ path: Path,
45
+ allowed_forms: set[str],
46
+ ) -> tuple[list[dict], dict[str, dict]]:
47
+ """Parse one company's raw XBRL JSON.
48
+
49
+ Returns
50
+ -------
51
+ facts : list[dict]
52
+ Flat rows of (ticker, taxonomy, tag, label, unit, period_start,
53
+ period_end, value, form, fiscal_year, fiscal_period, filed).
54
+ tag_meta : dict[str, dict]
55
+ ``{taxonomy:tag: {label, description, taxonomy}}``
56
+ """
57
+ try:
58
+ raw = json.loads(path.read_text(encoding="utf-8"))
59
+ except (json.JSONDecodeError, UnicodeDecodeError):
60
+ logger.warning("Corrupt JSON for %s, skipping", ticker)
61
+ return [], {}
62
+
63
+ if raw.get("_no_xbrl"):
64
+ return [], {}
65
+
66
+ facts_root = raw.get("facts", {})
67
+ rows: list[dict] = []
68
+ tag_meta: dict[str, dict] = {}
69
+
70
+ for taxonomy, tags in facts_root.items():
71
+ for tag_name, tag_data in tags.items():
72
+ label = tag_data.get("label") or tag_name
73
+ description = tag_data.get("description") or ""
74
+
75
+ meta_key = f"{taxonomy}:{tag_name}"
76
+ if meta_key not in tag_meta:
77
+ tag_meta[meta_key] = {
78
+ "taxonomy": taxonomy,
79
+ "tag": tag_name,
80
+ "label": label,
81
+ "description": str(description),
82
+ }
83
+
84
+ units = tag_data.get("units", {})
85
+ for unit_name, entries in units.items():
86
+ for entry in entries:
87
+ form = entry.get("form", "")
88
+ if form not in allowed_forms:
89
+ continue
90
+
91
+ rows.append({
92
+ "ticker": ticker,
93
+ "taxonomy": taxonomy,
94
+ "tag": tag_name,
95
+ "label": label,
96
+ "unit": unit_name,
97
+ "period_start": entry.get("start"),
98
+ "period_end": entry.get("end"),
99
+ "value": entry.get("val"),
100
+ "form": form,
101
+ "fiscal_year": entry.get("fy"),
102
+ "fiscal_period": entry.get("fp"),
103
+ "filed": entry.get("filed"),
104
+ "accession": entry.get("accn", ""),
105
+ })
106
+
107
+ return rows, tag_meta
108
+
109
+
110
+ def _parse_all_companies() -> tuple[pd.DataFrame, pd.DataFrame]:
111
+ """Parse all raw XBRL JSON files.
112
+
113
+ Returns ``(facts_df, tag_catalog_df)``
114
+ """
115
+ if not _RAW_DIR.exists():
116
+ raise FileNotFoundError(
117
+ f"XBRL raw directory not found: {_RAW_DIR}. Run collect_filings first (Step 4)."
118
+ )
119
+
120
+ json_files = sorted(_RAW_DIR.glob("*.json"))
121
+ if not json_files:
122
+ raise FileNotFoundError("No XBRL JSON files found in " + str(_RAW_DIR))
123
+
124
+ allowed_forms = set(config.XBRL_FORMS)
125
+ all_rows: list[dict] = []
126
+ all_meta: dict[str, dict] = {}
127
+
128
+ for i, path in enumerate(json_files):
129
+ ticker = path.stem
130
+ rows, meta = _parse_single_company(ticker, path, allowed_forms)
131
+ all_rows.extend(rows)
132
+ all_meta.update(meta)
133
+
134
+ if (i + 1) % 500 == 0:
135
+ logger.info(" Parsed %d / %d companies (%d facts so far)",
136
+ i + 1, len(json_files), len(all_rows))
137
+
138
+ logger.info(
139
+ "Parsed %d companies → %d facts, %d unique tags",
140
+ len(json_files), len(all_rows), len(all_meta),
141
+ )
142
+
143
+ facts_df = pd.DataFrame(all_rows)
144
+ if not facts_df.empty:
145
+ for col in ("period_start", "period_end", "filed"):
146
+ facts_df[col] = pd.to_datetime(facts_df[col], errors="coerce")
147
+
148
+ tag_catalog = pd.DataFrame(list(all_meta.values()))
149
+ return facts_df, tag_catalog
150
+
151
+
152
+ # ---------------------------------------------------------------------------
153
+ # Step 2: Build per-industry ontology
154
+ # ---------------------------------------------------------------------------
155
+
156
+ def _load_industry_map() -> dict[str, tuple[str, str]]:
157
+ """Load ticker → (sector, industry) from company_info.csv."""
158
+ ci_path = config.FUNDAMENTALS_DIR / "company_info.csv"
159
+ if not ci_path.exists():
160
+ logger.warning("company_info.csv not found; falling back to universe sectors")
161
+ u_path = config.UNIVERSE_DIR / "benchmark_universe.csv"
162
+ if not u_path.exists():
163
+ return {}
164
+ u = pd.read_csv(u_path)
165
+ return {
166
+ row["ticker"]: (str(row.get("sector", "Unknown")), "Unknown")
167
+ for _, row in u.iterrows()
168
+ }
169
+
170
+ ci = pd.read_csv(ci_path)
171
+ return {
172
+ row["ticker"]: (
173
+ str(row.get("sector", "Unknown")),
174
+ str(row.get("industry", "Unknown")),
175
+ )
176
+ for _, row in ci.iterrows()
177
+ }
178
+
179
+
180
+ def _build_ontology(
181
+ facts_df: pd.DataFrame,
182
+ industry_map: dict[str, tuple[str, str]],
183
+ ) -> dict:
184
+ """Build the industry-level ontology.
185
+
186
+ Returns a nested dict::
187
+
188
+ {
189
+ "by_sector": {
190
+ "Healthcare": {
191
+ "company_count": 515,
192
+ "tag_count": 1234,
193
+ "tags": {
194
+ "us-gaap:Revenue": {
195
+ "label": "Revenue",
196
+ "coverage": 0.95,
197
+ "classification": "core",
198
+ "median_value": 123456789,
199
+ "industries": ["Biotechnology", "Medical Devices", ...]
200
+ },
201
+ ...
202
+ }
203
+ },
204
+ ...
205
+ },
206
+ "by_industry": {
207
+ "Biotechnology": {
208
+ "sector": "Healthcare",
209
+ "company_count": 238,
210
+ "tag_count": 567,
211
+ "tags": { ... }
212
+ },
213
+ ...
214
+ }
215
+ }
216
+ """
217
+ if facts_df.empty:
218
+ return {"by_sector": {}, "by_industry": {}}
219
+
220
+ # Attach sector/industry
221
+ facts_df = facts_df.copy()
222
+ facts_df["sector"] = facts_df["ticker"].map(
223
+ lambda t: industry_map.get(t, ("Unknown", "Unknown"))[0]
224
+ )
225
+ facts_df["industry"] = facts_df["ticker"].map(
226
+ lambda t: industry_map.get(t, ("Unknown", "Unknown"))[1]
227
+ )
228
+
229
+ # Build a full tag key
230
+ facts_df["tag_key"] = facts_df["taxonomy"] + ":" + facts_df["tag"]
231
+
232
+ core_thresh = config.XBRL_CORE_THRESHOLD
233
+ common_thresh = config.XBRL_COMMON_THRESHOLD
234
+
235
+ def _classify_tags(
236
+ group_facts: pd.DataFrame,
237
+ group_name: str,
238
+ ) -> dict:
239
+ """Classify tags within a group (sector or industry)."""
240
+ company_count = group_facts["ticker"].nunique()
241
+ if company_count == 0:
242
+ return {
243
+ "company_count": 0,
244
+ "tag_count": 0,
245
+ "tags": {},
246
+ }
247
+
248
+ # For each tag: how many companies have reported it
249
+ tag_company_counts = (
250
+ group_facts.groupby("tag_key")["ticker"]
251
+ .nunique()
252
+ .to_dict()
253
+ )
254
+ # Tag labels (modal) — via value_counts + idxmax (vectorized)
255
+ lab_vc = group_facts.groupby(["tag_key", "label"]).size().reset_index(name="n")
256
+ lab_idx = lab_vc.groupby("tag_key")["n"].idxmax()
257
+ tag_labels = dict(
258
+ zip(lab_vc.loc[lab_idx, "tag_key"].values, lab_vc.loc[lab_idx, "label"].values)
259
+ )
260
+ # Median value per (tag, latest fiscal year) — single vectorized groupby
261
+ val_numeric = pd.to_numeric(group_facts["value"], errors="coerce")
262
+ gf = group_facts.assign(_vn=val_numeric).dropna(subset=["_vn"])
263
+ median_values: dict = {}
264
+ if not gf.empty:
265
+ med_by_fy = gf.groupby(["tag_key", "fiscal_year"])["_vn"].median()
266
+ latest_fy_series = gf.groupby("tag_key")["fiscal_year"].max()
267
+ for tk, fy in latest_fy_series.items():
268
+ if (tk, fy) in med_by_fy.index:
269
+ median_values[tk] = float(med_by_fy.loc[(tk, fy)])
270
+
271
+ tags: dict[str, dict] = {}
272
+ for tag_key, n_companies in tag_company_counts.items():
273
+ coverage = n_companies / company_count
274
+ if coverage >= core_thresh:
275
+ classification = "core"
276
+ elif coverage >= common_thresh:
277
+ classification = "common"
278
+ else:
279
+ classification = "extension"
280
+
281
+ tags[tag_key] = {
282
+ "label": tag_labels.get(tag_key, ""),
283
+ "company_count": int(n_companies),
284
+ "coverage": round(coverage, 4),
285
+ "classification": classification,
286
+ "median_value": median_values.get(tag_key),
287
+ }
288
+
289
+ return {
290
+ "company_count": int(company_count),
291
+ "tag_count": len(tags),
292
+ "tags": dict(sorted(
293
+ tags.items(),
294
+ key=lambda x: (-x[1]["coverage"], x[0]),
295
+ )),
296
+ }
297
+
298
+ # By sector
299
+ ontology_by_sector: dict = {}
300
+ for sector, sector_facts in facts_df.groupby("sector"):
301
+ logger.info(" Building ontology for sector: %s", sector)
302
+ ontology_by_sector[sector] = _classify_tags(sector_facts, sector)
303
+
304
+ # By industry
305
+ ontology_by_industry: dict = {}
306
+ for industry, ind_facts in facts_df.groupby("industry"):
307
+ sector = ind_facts["sector"].mode()
308
+ sector_name = sector.iloc[0] if len(sector) > 0 else "Unknown"
309
+ result = _classify_tags(ind_facts, industry)
310
+ result["sector"] = sector_name
311
+ ontology_by_industry[industry] = result
312
+
313
+ return {
314
+ "by_sector": ontology_by_sector,
315
+ "by_industry": ontology_by_industry,
316
+ }
317
+
318
+
319
+ # ---------------------------------------------------------------------------
320
+ # Step 3: Extract company-level tag summaries
321
+ # ---------------------------------------------------------------------------
322
+
323
+ def _build_company_tags(facts_df: pd.DataFrame) -> pd.DataFrame:
324
+ """For each company, extract the latest value per tag.
325
+
326
+ Returns a DataFrame with columns:
327
+ ticker, taxonomy, tag, label, unit, value, fiscal_year, fiscal_period, filed
328
+ """
329
+ if facts_df.empty:
330
+ return pd.DataFrame()
331
+
332
+ # Keep only the latest filing per ticker × tag × unit
333
+ idx = facts_df.groupby(["ticker", "taxonomy", "tag", "unit"])["filed"].idxmax()
334
+ latest = facts_df.loc[idx].copy()
335
+ latest = latest.sort_values(["ticker", "taxonomy", "tag"])
336
+ return latest[
337
+ ["ticker", "taxonomy", "tag", "label", "unit", "value",
338
+ "fiscal_year", "fiscal_period", "filed"]
339
+ ].reset_index(drop=True)
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # Public API
344
+ # ---------------------------------------------------------------------------
345
+
346
+ def run() -> dict[str, int]:
347
+ """Build XBRL ontology from collected company facts.
348
+
349
+ Returns summary dict with counts.
350
+ """
351
+ _PARSED_DIR.mkdir(parents=True, exist_ok=True)
352
+ _ONTOLOGY_DIR.mkdir(parents=True, exist_ok=True)
353
+
354
+ # Skip if already built (resume-safe). The ontology only needs rebuilding
355
+ # if the raw XBRL files change, which only happens after collect_filings.
356
+ ontology_path = _ONTOLOGY_DIR / "industry_ontology.json"
357
+ facts_path = _PARSED_DIR / "company_facts.parquet"
358
+ if ontology_path.exists() and ontology_path.stat().st_size > 1000 and facts_path.exists() and facts_path.stat().st_size > 1000:
359
+ ont = json.loads(ontology_path.read_text())
360
+ # The ontology JSON has top-level keys {by_sector, by_industry}; sector
361
+ # and industry counts are the lengths of THOSE inner dicts, not of the
362
+ # top-level dict itself.
363
+ if isinstance(ont, dict):
364
+ n_sectors = len(ont.get("by_sector", {}))
365
+ n_industries = len(ont.get("by_industry", {}))
366
+ else:
367
+ n_sectors = 0
368
+ n_industries = 0
369
+ logger.info("Ontology already exists (%d sectors, %d industries). Skipping rebuild.",
370
+ n_sectors, n_industries)
371
+ tags = pd.read_parquet(_ONTOLOGY_DIR / "tag_catalog.parquet") if (_ONTOLOGY_DIR / "tag_catalog.parquet").exists() else pd.DataFrame()
372
+ facts = pd.read_parquet(facts_path)
373
+ return {
374
+ "facts": len(facts),
375
+ "unique_tags": len(tags),
376
+ "companies": facts["ticker"].nunique() if "ticker" in facts.columns else 0,
377
+ "sectors": n_sectors,
378
+ "industries": n_industries,
379
+ }
380
+
381
+ # ── Step 1: Parse raw JSON ──────────────────────────────────────────
382
+ logger.info("Parsing raw XBRL company facts…")
383
+ facts_df, tag_catalog = _parse_all_companies()
384
+
385
+ # Save parsed facts
386
+ facts_path = _PARSED_DIR / "company_facts.parquet"
387
+ if not facts_df.empty:
388
+ facts_df.to_parquet(facts_path, index=False)
389
+ logger.info("Saved %d facts to %s", len(facts_df), facts_path)
390
+ else:
391
+ logger.warning("No facts parsed — empty output")
392
+ return {"facts": 0, "tags": 0, "sectors": 0, "industries": 0}
393
+
394
+ # Save tag catalog
395
+ catalog_path = _ONTOLOGY_DIR / "tag_catalog.parquet"
396
+ tag_catalog.to_parquet(catalog_path, index=False)
397
+ logger.info("Saved %d unique tags to %s", len(tag_catalog), catalog_path)
398
+
399
+ # ── Step 2: Build industry ontology ─────────────────────────────────
400
+ logger.info("Building industry ontology…")
401
+ industry_map = _load_industry_map()
402
+ ontology = _build_ontology(facts_df, industry_map)
403
+
404
+ ontology_path = _ONTOLOGY_DIR / "industry_ontology.json"
405
+ with open(ontology_path, "w", encoding="utf-8") as fh:
406
+ json.dump(ontology, fh, indent=2, ensure_ascii=False, default=str)
407
+ logger.info("Saved ontology to %s", ontology_path)
408
+
409
+ # ── Step 3: Company-level tag summary ───────────────────────────────
410
+ logger.info("Building company-level tag summaries…")
411
+ company_tags = _build_company_tags(facts_df)
412
+ company_tags_path = _PARSED_DIR / "company_tags.parquet"
413
+ company_tags.to_parquet(company_tags_path, index=False)
414
+ logger.info("Saved %d company-tag rows to %s", len(company_tags), company_tags_path)
415
+
416
+ n_sectors = len(ontology.get("by_sector", {}))
417
+ n_industries = len(ontology.get("by_industry", {}))
418
+
419
+ summary = {
420
+ "facts": len(facts_df),
421
+ "unique_tags": len(tag_catalog),
422
+ "companies": facts_df["ticker"].nunique(),
423
+ "sectors": n_sectors,
424
+ "industries": n_industries,
425
+ }
426
+ logger.info("Ontology build complete: %s", summary)
427
+
428
+ # Print top-level ontology summary
429
+ for sector, data in sorted(ontology.get("by_sector", {}).items()):
430
+ core = sum(1 for t in data["tags"].values() if t["classification"] == "core")
431
+ common = sum(1 for t in data["tags"].values() if t["classification"] == "common")
432
+ ext = sum(1 for t in data["tags"].values() if t["classification"] == "extension")
433
+ logger.info(
434
+ " %s: %d companies, %d tags (core=%d, common=%d, extension=%d)",
435
+ sector, data["company_count"], data["tag_count"], core, common, ext,
436
+ )
437
+
438
+ return summary
code/build_valuation_tasks.py ADDED
@@ -0,0 +1,956 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Valuation benchmark: task definitions and ground-truth construction.
2
+
3
+ Produces the artifacts required for the benchmark tasks T2-T7:
4
+ T2 - Company Valuation Accuracy (public company, all observables)
5
+ T3 - Financial Statement Generation Quality
6
+ T4 - Scenario-Conditioned Forecasting (ground truth only; scenarios
7
+ themselves are produced by `generate_scenarios.py`)
8
+ T5 - Private Company Valuation (PE simulation, financials + sector only)
9
+ T6 - Generator Evaluation (NL description -> XBRL fields)
10
+ T7 - Real Estate Valuation
11
+
12
+ Called from `assemble_benchmark.py` as the final Layer-3 build step.
13
+
14
+ Lives at the top level of `whatif_bench/` -- a peer of the other
15
+ benchmark builders (`assemble_benchmark.py`, `generate_scenarios.py`,
16
+ `enrich_benchmark.py`, `build_ontology.py`). NOT under `agents/`:
17
+ agents USE the benchmark, they don't BUILD it.
18
+
19
+ Usage:
20
+ from projects.agent_builder.scripts.whatif_bench.build_valuation_tasks import (
21
+ build_valuation_benchmark,
22
+ )
23
+ summary = build_valuation_benchmark(granularity="daily")
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import logging
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ import numpy as np
34
+ import pandas as pd
35
+
36
+ from . import config
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+
41
+ # Columns that are algebraically equivalent to (or directly reveal)
42
+ # market capitalisation. These MUST be excluded from any valuation-task
43
+ # input whose target is actual_market_cap, otherwise the task degenerates
44
+ # into trivial recovery. Used by Task A (and Task D's broader strip).
45
+ # derived_pe = market_cap / earnings
46
+ # derived_ev = market_cap + debt - cash
47
+ # derived_ev_to_revenue = ev / revenue (reveals mcap)
48
+ # derived_ev_to_ebitda = ev / ebitda (reveals mcap)
49
+ # derived_pb = market_cap / book_equity
50
+ # derived_price_to_book = alias for derived_pb
51
+ # derived_fcf_yield = fcf / market_cap
52
+ _MARKET_CAP_LEAKAGE_COLS: frozenset[str] = frozenset({
53
+ "derived_market_cap",
54
+ "derived_pe",
55
+ "derived_ev",
56
+ "derived_ev_to_revenue",
57
+ "derived_ev_to_ebitda",
58
+ "derived_pb",
59
+ "derived_price_to_book",
60
+ "derived_fcf_yield",
61
+ })
62
+
63
+
64
+ # ===================================================================
65
+ # Task A: Company Valuation Ground Truth
66
+ # ===================================================================
67
+
68
+ def _build_task_a(
69
+ panel: pd.DataFrame,
70
+ company_info: pd.DataFrame,
71
+ holdout_tickers: list[str],
72
+ output_dir: Path,
73
+ ) -> dict[str, Any]:
74
+ """Build Task A: estimate intrinsic value of public companies.
75
+
76
+ For each quarterly boundary × ticker, create:
77
+ - input: company description, sector, industry, recent financials
78
+ - target: actual market cap (hidden)
79
+ """
80
+ # Quarterly boundaries (resample to quarter-end dates)
81
+ if "derived_market_cap" not in panel.columns:
82
+ logger.warning("derived_market_cap not in panel; skipping Task A")
83
+ return {"error": "No market cap data"}
84
+
85
+ # Use panel data at quarterly frequency
86
+ quarterly = panel.copy()
87
+ quarterly["date"] = pd.to_datetime(quarterly["date"])
88
+ quarterly["quarter"] = quarterly["date"].dt.to_period("Q")
89
+
90
+ # Take last observation per ticker × quarter
91
+ quarterly = quarterly.sort_values("date").drop_duplicates(
92
+ subset=["ticker", "quarter"], keep="last",
93
+ )
94
+
95
+ # Split: holdout tickers = evaluation, rest = context
96
+ eval_mask = quarterly["ticker"].isin(holdout_tickers)
97
+ eval_df = quarterly[eval_mask].copy()
98
+
99
+ if eval_df.empty:
100
+ return {"error": "No holdout tickers found in panel"}
101
+
102
+ # Build inputs (observable data). derived_* columns that are
103
+ # algebraic functions of market_cap are excluded -- they would let any
104
+ # model recover the target trivially. See _MARKET_CAP_LEAKAGE_COLS
105
+ # at the top of this module for the rationale per column.
106
+ input_cols = ["ticker", "date", "sector", "industry"]
107
+ for c in quarterly.columns:
108
+ if c in _MARKET_CAP_LEAKAGE_COLS:
109
+ continue
110
+ if c.startswith("derived_") or c.startswith("stmt_"):
111
+ input_cols.append(c)
112
+ input_cols = [c for c in input_cols if c in eval_df.columns]
113
+ inputs = eval_df[input_cols].copy()
114
+
115
+ # Build ground truth (hidden)
116
+ gt = eval_df[["ticker", "date", "derived_market_cap"]].copy()
117
+ gt = gt.rename(columns={"derived_market_cap": "actual_market_cap"})
118
+ gt = gt.dropna(subset=["actual_market_cap"])
119
+
120
+ # Save
121
+ inputs.to_parquet(output_dir / "valuation_inputs.parquet", index=False)
122
+ gt.to_parquet(output_dir / "valuation_ground_truth.parquet", index=False)
123
+
124
+ return {
125
+ "n_tickers": gt["ticker"].nunique(),
126
+ "n_instances": len(gt),
127
+ "date_range": [str(gt["date"].min()), str(gt["date"].max())],
128
+ }
129
+
130
+
131
+ # ===================================================================
132
+ # Task B: Financial Statement Generation Ground Truth
133
+ # ===================================================================
134
+
135
+ def _build_task_b(
136
+ company_info: pd.DataFrame,
137
+ holdout_tickers: list[str],
138
+ output_dir: Path,
139
+ ) -> dict[str, Any]:
140
+ """Build Task B: generate plausible financial statements.
141
+
142
+ For holdout tickers, the latest XBRL filings serve as ground truth.
143
+ Input: company profile (sector, industry, size description).
144
+ Target: actual XBRL financial statements.
145
+ """
146
+ # Load XBRL company tags (latest values)
147
+ tags_path = config.XBRL_DIR / "parsed" / "company_tags.parquet"
148
+ if not tags_path.exists():
149
+ logger.warning("XBRL company_tags not found; skipping Task B")
150
+ return {"error": "No XBRL data"}
151
+
152
+ tags = pd.read_parquet(tags_path)
153
+ holdout_tags = tags[tags["ticker"].isin(holdout_tickers)]
154
+
155
+ if holdout_tags.empty:
156
+ return {"error": "No XBRL tags for holdout tickers"}
157
+
158
+ # Input: company descriptions
159
+ inputs = company_info[company_info["ticker"].isin(holdout_tickers)].copy()
160
+ if inputs.empty:
161
+ inputs = pd.DataFrame({"ticker": holdout_tickers})
162
+
163
+ # Ground truth: XBRL tags (field/value pairs)
164
+ gt_rows = []
165
+ for _, row in holdout_tags.iterrows():
166
+ gt_rows.append({
167
+ "ticker": row["ticker"],
168
+ "field": row["tag"],
169
+ "value": row["value"],
170
+ "taxonomy": row.get("taxonomy", ""),
171
+ "unit": row.get("unit", ""),
172
+ "fiscal_year": row.get("fiscal_year"),
173
+ })
174
+
175
+ gt = pd.DataFrame(gt_rows)
176
+
177
+ # Save
178
+ inputs.to_parquet(output_dir / "generation_inputs.parquet", index=False)
179
+ gt.to_parquet(output_dir / "generation_ground_truth.parquet", index=False)
180
+
181
+ return {
182
+ "n_tickers": gt["ticker"].nunique(),
183
+ "n_fields": gt["field"].nunique(),
184
+ "n_instances": len(gt),
185
+ }
186
+
187
+
188
+ # ===================================================================
189
+ # Task C: Scenario-Conditioned Forecasting Ground Truth
190
+ # ===================================================================
191
+
192
+ def _build_task_c(
193
+ panel: pd.DataFrame,
194
+ scenarios: pd.DataFrame,
195
+ output_dir: Path,
196
+ ) -> dict[str, Any]:
197
+ """Build Task C: forecast financial impact of what-if scenarios.
198
+
199
+ Extends existing scenarios with actual post-event changes in:
200
+ - price return (already in scenarios)
201
+ - revenue change (from panel statements)
202
+ - market cap change
203
+
204
+ Vectorised: pre-groups panel by ticker, then uses numpy searchsorted
205
+ to avoid O(scenarios × tickers × rows) repeated DataFrame filtering.
206
+ """
207
+ if scenarios.empty:
208
+ return {"error": "No scenarios"}
209
+
210
+ panel = panel.copy()
211
+ panel["date"] = pd.to_datetime(panel["date"])
212
+ has_mcap = "derived_market_cap" in panel.columns
213
+
214
+ # Pre-group: store sorted arrays per ticker (avoids repeated filtering)
215
+ ticker_arrays: dict[str, dict] = {}
216
+ for ticker, grp in panel.groupby("ticker", sort=False):
217
+ grp = grp.sort_values("date")
218
+ td = {
219
+ "dates": grp["date"].values.astype("int64"),
220
+ "close": grp["close"].values,
221
+ }
222
+ if has_mcap:
223
+ td["mcap"] = grp["derived_market_cap"].values
224
+ ticker_arrays[ticker] = td
225
+
226
+ # Pre-extract scenario arrays
227
+ n_sc = len(scenarios)
228
+ sc_ids = scenarios["scenario_id"].values
229
+ sc_types = scenarios["event_type"].values if "event_type" in scenarios.columns else [""] * n_sc
230
+ sc_event_dates = pd.to_datetime(scenarios["event_date"]).values.astype("int64")
231
+ sc_pre_starts = pd.to_datetime(
232
+ scenarios.get("pre_window_start", scenarios["event_date"])
233
+ ).values.astype("int64")
234
+ sc_post_ends = pd.to_datetime(
235
+ scenarios.get("post_window_end", scenarios["event_date"])
236
+ ).values.astype("int64")
237
+
238
+ gt_rows = []
239
+ for ticker, td in ticker_arrays.items():
240
+ dates = td["dates"]
241
+ close = td["close"]
242
+ mcap = td.get("mcap")
243
+
244
+ for i in range(n_sc):
245
+ ev_ns = sc_event_dates[i]
246
+ pre_ns = sc_pre_starts[i]
247
+ post_ns = sc_post_ends[i]
248
+
249
+ # Pre: last index where pre_start <= date < event_date
250
+ pre_lo = np.searchsorted(dates, pre_ns, side="left")
251
+ pre_hi = np.searchsorted(dates, ev_ns, side="left")
252
+ if pre_hi <= pre_lo:
253
+ continue
254
+ pre_idx = pre_hi - 1
255
+
256
+ # Post: last index where event_date < date <= post_end
257
+ post_lo = np.searchsorted(dates, ev_ns, side="right")
258
+ post_hi = np.searchsorted(dates, post_ns, side="right")
259
+ if post_hi <= post_lo:
260
+ continue
261
+ post_idx = post_hi - 1
262
+
263
+ pre_price = float(close[pre_idx])
264
+ post_price = float(close[post_idx])
265
+ # Exclude penny-stock data points (pre-event price < $0.50): a
266
+ # one-cent move at $0.001 produces a 1000% "return" that's
267
+ # float noise rather than scenario response. The cutoff matches
268
+ # the SEC's penny-stock threshold and removes ~145 of 4.1M rows
269
+ # that account for all returns >|10000%|.
270
+ if pre_price < 0.50:
271
+ continue
272
+ price_return = (post_price / pre_price - 1) * 100
273
+
274
+ mcap_return = np.nan
275
+ if mcap is not None:
276
+ pre_m = float(mcap[pre_idx])
277
+ post_m = float(mcap[post_idx])
278
+ if not np.isnan(pre_m) and pre_m > 0:
279
+ mcap_return = (post_m / pre_m - 1) * 100
280
+
281
+ gt_rows.append({
282
+ "scenario_id": sc_ids[i],
283
+ "event_type": sc_types[i],
284
+ "event_date": str(pd.Timestamp(ev_ns).date()),
285
+ "ticker": ticker,
286
+ "actual_return_pct": round(price_return, 3) if not np.isnan(price_return) else None,
287
+ "actual_mcap_change_pct": round(mcap_return, 3) if not np.isnan(mcap_return) else None,
288
+ "pre_price": round(pre_price, 2),
289
+ "post_price": round(post_price, 2),
290
+ })
291
+
292
+ if not gt_rows:
293
+ return {"error": "No scenario × ticker pairs with data"}
294
+
295
+ gt = pd.DataFrame(gt_rows)
296
+ gt.to_parquet(output_dir / "scenario_forecast_ground_truth.parquet", index=False)
297
+
298
+ return {
299
+ "n_scenarios": gt["scenario_id"].nunique(),
300
+ "n_tickers": gt["ticker"].nunique(),
301
+ "n_instances": len(gt),
302
+ "event_types": gt["event_type"].value_counts().to_dict(),
303
+ }
304
+
305
+
306
+ # ===================================================================
307
+ # Task E: Generator Evaluation (Financial Generation Quality)
308
+ # ===================================================================
309
+
310
+ # Maps Generator output columns to XBRL ground-truth tag names.
311
+ # The Generator produces columns like "revenue", "net_income", etc.
312
+ # while XBRL ground truth uses US-GAAP tag names like "Revenues",
313
+ # "NetIncomeLoss", etc. This mapping bridges the two.
314
+ _GENERATOR_TO_XBRL: dict[str, list[str]] = {
315
+ "revenue": ["Revenues", "RevenueFromContractWithCustomerExcludingAssessedTax", "SalesRevenueNet"],
316
+ "net_income": ["NetIncomeLoss"],
317
+ "gross_profit": ["GrossProfit"],
318
+ "operating_income": ["OperatingIncomeLoss"],
319
+ "total_assets": ["Assets"],
320
+ "total_equity": ["StockholdersEquity", "StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest"],
321
+ "total_debt": ["LongTermDebt", "LongTermDebtNoncurrent"],
322
+ "cash_and_equivalents": ["CashAndCashEquivalentsAtCarryingValue", "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents"],
323
+ "operating_cash_flow": ["NetCashProvidedByUsedInOperatingActivities"],
324
+ "capital_expenditure": ["PaymentsToAcquirePropertyPlantAndEquipment"],
325
+ "interest_expense": ["InterestExpense"],
326
+ "ebitda": ["EBITDA"], # often not a direct XBRL tag; may need derivation
327
+ }
328
+
329
+
330
+ def _build_task_e(
331
+ company_info: pd.DataFrame,
332
+ holdout_tickers: list[str],
333
+ output_dir: Path,
334
+ ) -> dict[str, Any]:
335
+ """Build Task E: evaluate financial generation quality.
336
+
337
+ For each holdout ticker, the task is: given only the company's sector,
338
+ industry, and a text description → generate plausible financial
339
+ statements. Ground truth comes from actual XBRL filings.
340
+
341
+ This task evaluates the Generator agent's ability to produce realistic
342
+ financials for an unseen company, measured by per-field MAPE against
343
+ the latest actual filings.
344
+
345
+ The difference from Task B: Task B evaluates any model's field-level
346
+ predictions using raw XBRL tags. Task E specifically provides inputs
347
+ in the format the Generator agent expects (company description, sector)
348
+ and maps its output columns to XBRL ground truth, so the Generator
349
+ agent can be directly evaluated.
350
+ """
351
+ # Load XBRL company tags (latest values)
352
+ tags_path = config.XBRL_DIR / "parsed" / "company_tags.parquet"
353
+ if not tags_path.exists():
354
+ logger.warning("XBRL company_tags not found; skipping Task E")
355
+ return {"error": "No XBRL data"}
356
+
357
+ tags = pd.read_parquet(tags_path)
358
+ holdout_tags = tags[tags["ticker"].isin(holdout_tickers)]
359
+
360
+ if holdout_tags.empty:
361
+ return {"error": "No XBRL tags for holdout tickers"}
362
+
363
+ # Build inputs: company profile in Generator-compatible format
364
+ input_rows = []
365
+ for ticker in holdout_tickers:
366
+ info_row = company_info[company_info["ticker"] == ticker]
367
+ if info_row.empty:
368
+ sector = "Unknown"
369
+ industry = "Unknown"
370
+ description = f"A company with ticker {ticker}"
371
+ else:
372
+ r = info_row.iloc[0]
373
+ sector = str(r.get("sector", "Unknown"))
374
+ industry = str(r.get("industry", "Unknown"))
375
+ employees = r.get("fullTimeEmployees", "")
376
+ description = (
377
+ f"A {sector} company in the {industry} industry"
378
+ + (f" with approximately {int(employees)} employees" if employees and not pd.isna(employees) else "")
379
+ )
380
+
381
+ input_rows.append({
382
+ "ticker": ticker,
383
+ "sector": sector,
384
+ "industry": industry,
385
+ "company_description": description,
386
+ })
387
+
388
+ inputs = pd.DataFrame(input_rows)
389
+
390
+ # Build ground truth: map XBRL tags to Generator column names
391
+ gt_rows = []
392
+ for ticker in holdout_tickers:
393
+ tk_tags = holdout_tags[holdout_tags["ticker"] == ticker]
394
+ if tk_tags.empty:
395
+ continue
396
+ for gen_col, xbrl_tags in _GENERATOR_TO_XBRL.items():
397
+ for xbrl_tag in xbrl_tags:
398
+ match = tk_tags[tk_tags["tag"] == xbrl_tag]
399
+ if not match.empty:
400
+ # Take the latest value
401
+ latest = match.sort_values("fiscal_year", ascending=False).iloc[0]
402
+ gt_rows.append({
403
+ "ticker": ticker,
404
+ "generator_field": gen_col,
405
+ "xbrl_tag": xbrl_tag,
406
+ "value": latest["value"],
407
+ "fiscal_year": latest.get("fiscal_year"),
408
+ "unit": latest.get("unit", ""),
409
+ })
410
+ break # take first matching XBRL tag (priority order)
411
+
412
+ if not gt_rows:
413
+ return {"error": "No matching XBRL tags for Generator fields"}
414
+
415
+ gt = pd.DataFrame(gt_rows)
416
+
417
+ # Save
418
+ inputs.to_parquet(output_dir / "generator_eval_inputs.parquet", index=False)
419
+ gt.to_parquet(output_dir / "generator_eval_ground_truth.parquet", index=False)
420
+
421
+ logger.info(
422
+ "Task E (Generator Eval): %d tickers, %d field-value pairs, %d unique fields",
423
+ gt["ticker"].nunique(), len(gt), gt["generator_field"].nunique(),
424
+ )
425
+
426
+ return {
427
+ "n_tickers": gt["ticker"].nunique(),
428
+ "n_field_value_pairs": len(gt),
429
+ "n_unique_fields": gt["generator_field"].nunique(),
430
+ "fields": gt["generator_field"].value_counts().to_dict(),
431
+ }
432
+
433
+
434
+ # ===================================================================
435
+ # Task F: Real Estate Valuation (Rent/Price Estimation)
436
+ # ===================================================================
437
+
438
+ def _normalise_address(addr: str) -> str:
439
+ """Normalise an address string for matching: lowercase, strip whitespace."""
440
+ if not isinstance(addr, str):
441
+ return ""
442
+ return " ".join(addr.lower().strip().split())
443
+
444
+
445
+ def _merge_rentals(
446
+ props: pd.DataFrame,
447
+ rentals: pd.DataFrame,
448
+ ) -> pd.DataFrame:
449
+ """Merge rental data into properties by normalised address or lat/lon proximity.
450
+
451
+ For each property row, attempt to find a matching rental listing.
452
+ Match strategy:
453
+ 1. Exact normalised address match.
454
+ 2. Lat/lon proximity (< 0.0005 degrees, roughly 50 m) for unmatched rows
455
+ that share the same zip code.
456
+
457
+ Returns the properties DataFrame with an added ``rent`` column.
458
+ """
459
+ # --- Prepare normalised keys ---
460
+ props = props.copy()
461
+ rentals = rentals.copy()
462
+
463
+ # Identify the address column in each DataFrame
464
+ for col in ("formatted_address", "addressLine1", "addressFull", "address"):
465
+ if col in props.columns:
466
+ props["_norm_addr"] = props[col].apply(_normalise_address)
467
+ break
468
+ else:
469
+ props["_norm_addr"] = ""
470
+
471
+ for col in ("formatted_address", "addressLine1", "addressFull", "address"):
472
+ if col in rentals.columns:
473
+ rentals["_norm_addr"] = rentals[col].apply(_normalise_address)
474
+ break
475
+ else:
476
+ rentals["_norm_addr"] = ""
477
+
478
+ # Rename the rentals price column to rent
479
+ rent_price_col = "price" # rentals.csv uses "price" for monthly rent
480
+ if rent_price_col not in rentals.columns:
481
+ logger.warning("rentals.csv has no 'price' column; no rent data to merge")
482
+ props["rent"] = np.nan
483
+ props.drop(columns=["_norm_addr"], inplace=True)
484
+ return props
485
+
486
+ rentals["rent"] = pd.to_numeric(rentals[rent_price_col], errors="coerce")
487
+
488
+ # De-duplicate rentals: keep first (latest listing) per normalised address
489
+ rentals_dedup = (
490
+ rentals[rentals["_norm_addr"] != ""]
491
+ .drop_duplicates(subset=["_norm_addr"], keep="first")
492
+ )
493
+
494
+ # --- Strategy 1: exact normalised address merge ---
495
+ rent_lookup = rentals_dedup.set_index("_norm_addr")["rent"]
496
+ props["rent"] = props["_norm_addr"].map(rent_lookup)
497
+
498
+ n_addr_matched = props["rent"].notna().sum()
499
+ logger.info("Task F rent merge: %d/%d matched by address", n_addr_matched, len(props))
500
+
501
+ # --- Strategy 2: lat/lon proximity for unmatched rows ---
502
+ unmatched_mask = props["rent"].isna()
503
+ has_coords_props = (
504
+ unmatched_mask
505
+ & props.get("latitude", pd.Series(dtype=float)).notna()
506
+ & props.get("longitude", pd.Series(dtype=float)).notna()
507
+ )
508
+
509
+ if has_coords_props.any() and "latitude" in rentals.columns and "longitude" in rentals.columns:
510
+ # Build a lookup of rentals by zip for faster spatial matching
511
+ zip_col_r = "zip_code" if "zip_code" in rentals.columns else None
512
+ zip_col_p = "zip_code" if "zip_code" in props.columns else None
513
+
514
+ rentals_with_coords = rentals[
515
+ rentals["latitude"].notna() & rentals["longitude"].notna() & rentals["rent"].notna()
516
+ ].copy()
517
+
518
+ if not rentals_with_coords.empty and zip_col_r and zip_col_p:
519
+ rental_groups = {
520
+ z: grp[["latitude", "longitude", "rent"]].values
521
+ for z, grp in rentals_with_coords.groupby(zip_col_r)
522
+ }
523
+
524
+ proximity_threshold = 0.0005 # ~50 m
525
+
526
+ for idx in props.index[has_coords_props]:
527
+ z = props.at[idx, zip_col_p] if zip_col_p else None
528
+ if z not in rental_groups:
529
+ continue
530
+ candidates = rental_groups[z] # shape (N, 3): lat, lon, rent
531
+ dlat = candidates[:, 0] - props.at[idx, "latitude"]
532
+ dlon = candidates[:, 1] - props.at[idx, "longitude"]
533
+ dist = np.sqrt(dlat ** 2 + dlon ** 2)
534
+ best = np.argmin(dist)
535
+ if dist[best] < proximity_threshold:
536
+ props.at[idx, "rent"] = candidates[best, 2]
537
+
538
+ n_geo_matched = props["rent"].notna().sum() - n_addr_matched
539
+ logger.info("Task F rent merge: %d additional matched by lat/lon proximity", n_geo_matched)
540
+
541
+ props.drop(columns=["_norm_addr"], inplace=True)
542
+ return props
543
+
544
+
545
+ def _build_task_f(
546
+ output_dir: Path,
547
+ ) -> dict[str, Any]:
548
+ """Build Task F: evaluate real estate rent and price estimation.
549
+
550
+ Uses collected RentCast data as ground truth. Loads both
551
+ ``properties.csv`` (sale prices) and ``rentals.csv`` (monthly rents),
552
+ merges them by normalised address (with lat/lon proximity fallback),
553
+ and produces a combined dataset with both ``price`` and ``rent``
554
+ target columns.
555
+
556
+ For each property the task is: given location (metro), property type,
557
+ size (sqft, beds, baths), and year built, predict rent and/or price.
558
+
559
+ The holdout is a random 30 % of combined properties (seeded).
560
+ Training properties serve as the comps database.
561
+ """
562
+ properties_path = config.REAL_ESTATE_DIR / "properties.csv"
563
+ rentals_path = config.REAL_ESTATE_DIR / "rentals.csv"
564
+
565
+ if not properties_path.exists() and not rentals_path.exists():
566
+ logger.warning("Neither properties.csv nor rentals.csv found; skipping Task F")
567
+ return {"error": "No real estate data"}
568
+
569
+ # ------------------------------------------------------------------
570
+ # 1. Load and standardise properties (sale price data)
571
+ # ------------------------------------------------------------------
572
+ if properties_path.exists():
573
+ props = pd.read_csv(properties_path)
574
+ else:
575
+ props = pd.DataFrame()
576
+
577
+ _rename_priority = [
578
+ ("square_footage", "sqft"),
579
+ ("squareFootage", "sqft"),
580
+ ("propertyType", "property_type"),
581
+ ("yearBuilt", "year_built"),
582
+ ("last_sale_price", "price"),
583
+ ("lastSalePrice", "price"),
584
+ ("zipCode", "zip_code"),
585
+ ("lotSize", "lot_size"),
586
+ # Address: prefer formatted_address > addressLine1
587
+ ("formatted_address", "address"),
588
+ ("addressLine1", "address"),
589
+ ("addressFull", "address"),
590
+ ]
591
+ for old_name, new_name in _rename_priority:
592
+ if old_name in props.columns and new_name not in props.columns:
593
+ props = props.rename(columns={old_name: new_name})
594
+
595
+ # Ensure numeric price
596
+ if "price" in props.columns:
597
+ props["price"] = pd.to_numeric(props["price"], errors="coerce")
598
+ # Remove non-positive prices (data errors)
599
+ neg_price = props["price"] <= 0
600
+ if neg_price.any():
601
+ logger.info("Task F: removing %d rows with non-positive price", neg_price.sum())
602
+ props = props[~neg_price | props["price"].isna()]
603
+
604
+ # Deduplicate by address (keep first occurrence)
605
+ if "address" in props.columns:
606
+ before = len(props)
607
+ props = props.drop_duplicates(subset=["address"], keep="first")
608
+ deduped = before - len(props)
609
+ if deduped > 0:
610
+ logger.info("Task F: deduplicated %d rows by address", deduped)
611
+
612
+ # ------------------------------------------------------------------
613
+ # 2. Load rentals and merge rent into properties
614
+ # ------------------------------------------------------------------
615
+ if rentals_path.exists():
616
+ rentals_raw = pd.read_csv(rentals_path)
617
+ if not rentals_raw.empty:
618
+ # Standardise rental column names the same way
619
+ for old_name, new_name in _rename_priority:
620
+ if old_name in rentals_raw.columns and new_name not in rentals_raw.columns:
621
+ rentals_raw = rentals_raw.rename(columns={old_name: new_name})
622
+
623
+ if not props.empty:
624
+ props = _merge_rentals(props, rentals_raw)
625
+ else:
626
+ # No properties file -- use rentals as the base
627
+ props = rentals_raw.copy()
628
+ props["rent"] = pd.to_numeric(props.get("price", pd.Series(dtype=float)), errors="coerce")
629
+ props["price"] = np.nan # no sale price available
630
+
631
+ # Append rental-only rows (addresses not already in props)
632
+ if not props.empty and "address" in props.columns:
633
+ existing_addrs = set(props["address"].apply(_normalise_address))
634
+ if "address" in rentals_raw.columns:
635
+ rentals_raw["_norm_addr"] = rentals_raw["address"].apply(_normalise_address)
636
+ new_rentals = rentals_raw[~rentals_raw["_norm_addr"].isin(existing_addrs)].copy()
637
+ new_rentals.drop(columns=["_norm_addr"], inplace=True)
638
+ if not new_rentals.empty:
639
+ new_rentals["rent"] = pd.to_numeric(
640
+ new_rentals.get("price", pd.Series(dtype=float)), errors="coerce",
641
+ )
642
+ # Avoid column clash: rentals "price" is rent, not sale price
643
+ if "price" in new_rentals.columns:
644
+ new_rentals = new_rentals.drop(columns=["price"])
645
+ new_rentals["price"] = np.nan # no sale price for rental-only rows
646
+ props = pd.concat([props, new_rentals], ignore_index=True)
647
+ logger.info("Task F: appended %d rental-only rows", len(new_rentals))
648
+ else:
649
+ # No rentals file -- price-only (existing behaviour)
650
+ props["rent"] = np.nan
651
+
652
+ if props.empty:
653
+ return {"error": "Empty real estate data after merge"}
654
+
655
+ # Ensure rent column exists
656
+ if "rent" not in props.columns:
657
+ props["rent"] = np.nan
658
+
659
+ # ------------------------------------------------------------------
660
+ # 3. Filter to properties with at least one target (rent or price)
661
+ # ------------------------------------------------------------------
662
+ props = props.dropna(subset=["price", "rent"], how="all")
663
+
664
+ if len(props) < 10:
665
+ return {"error": f"Too few properties with rent/price data ({len(props)})"}
666
+
667
+ # ------------------------------------------------------------------
668
+ # 3b. Per-property TIME-AXIS features
669
+ # ------------------------------------------------------------------
670
+ # Each property in the RentCast snapshot carries a `last_sale_date`
671
+ # (when it last changed hands). This timestamp is the per-property
672
+ # historical observation that gives T7 a time axis even though the
673
+ # train/test split itself is geographic (by address). Methods can use
674
+ # `last_sale_date` and `years_since_last_sale` as features alongside
675
+ # static attributes.
676
+ SCRAPE_DATE = pd.Timestamp("2026-04-11", tz="UTC")
677
+ if "last_sale_date" in props.columns:
678
+ props["last_sale_date"] = pd.to_datetime(
679
+ props["last_sale_date"], errors="coerce", utc=True,
680
+ )
681
+ props["years_since_last_sale"] = (
682
+ (SCRAPE_DATE - props["last_sale_date"]).dt.total_seconds() / (365.25 * 86400)
683
+ )
684
+
685
+ # ------------------------------------------------------------------
686
+ # 4. Address-holdout 70/30 split (seeded). T7 is a static valuation
687
+ # task -- the OOD signal is across properties, not across time --
688
+ # so the train/test cutoff is geographic. The time axis lives in
689
+ # the per-property features added in step 3b.
690
+ # ------------------------------------------------------------------
691
+ rng = np.random.RandomState(config.BENCHMARK_SEED)
692
+ holdout_mask = rng.random(len(props)) < 0.3
693
+ train_props = props[~holdout_mask].copy()
694
+ test_props = props[holdout_mask].copy()
695
+
696
+ # ------------------------------------------------------------------
697
+ # 5. Build inputs and ground truth
698
+ # ------------------------------------------------------------------
699
+ input_candidates = [
700
+ "address", "city", "state", "zip_code",
701
+ "property_type", "bedrooms", "bathrooms", "sqft",
702
+ "lotSize", "lot_size", "year_built", "county",
703
+ "latitude", "longitude",
704
+ # Per-property time-axis features (Option B: time-aware features
705
+ # alongside the static attributes; address-holdout split):
706
+ "last_sale_date", "years_since_last_sale",
707
+ ]
708
+ input_cols = [c for c in input_candidates if c in test_props.columns]
709
+ inputs = test_props[input_cols].copy()
710
+
711
+ # Ground truth: address + both targets
712
+ gt_cols = []
713
+ if "address" in test_props.columns:
714
+ gt_cols.append("address")
715
+ gt_cols.extend(["price", "rent"])
716
+ gt = test_props[gt_cols].copy()
717
+
718
+ # ------------------------------------------------------------------
719
+ # 6. Save
720
+ # ------------------------------------------------------------------
721
+ train_props.to_parquet(output_dir / "re_train_properties.parquet", index=False)
722
+ inputs.to_parquet(output_dir / "re_eval_inputs.parquet", index=False)
723
+ gt.to_parquet(output_dir / "re_eval_ground_truth.parquet", index=False)
724
+
725
+ n_price = gt["price"].notna().sum()
726
+ n_rent = gt["rent"].notna().sum()
727
+ n_both = (gt["price"].notna() & gt["rent"].notna()).sum()
728
+
729
+ logger.info(
730
+ "Task F (RE Eval): %d train, %d test; price=%d, rent=%d, both=%d",
731
+ len(train_props), len(test_props), n_price, n_rent, n_both,
732
+ )
733
+
734
+ return {
735
+ "n_train": len(train_props),
736
+ "n_test": len(test_props),
737
+ "n_price": int(n_price),
738
+ "n_rent": int(n_rent),
739
+ "n_both": int(n_both),
740
+ "target_cols": ["price", "rent"],
741
+ "input_cols": input_cols,
742
+ }
743
+
744
+
745
+ # ===================================================================
746
+ # Task D: Private Company Valuation (PE Simulation)
747
+ # ===================================================================
748
+
749
+ # Columns derived from market price — must be stripped for private-company
750
+ # simulation because a PE analyst would not have access to market data.
751
+ _PRICE_DERIVED_COLS = {
752
+ "derived_market_cap", "derived_pe", "derived_ev", "derived_ev_to_revenue",
753
+ "derived_ev_to_ebitda", "derived_fcf_yield", "derived_pb",
754
+ "derived_price_to_book", "derived_debt_to_equity",
755
+ "close", "open", "high", "low", "volume", "adj_close",
756
+ "shares_outstanding",
757
+ }
758
+
759
+
760
+ def _build_task_d(
761
+ panel: pd.DataFrame,
762
+ company_info: pd.DataFrame,
763
+ holdout_tickers: list[str],
764
+ output_dir: Path,
765
+ ) -> dict[str, Any]:
766
+ """Build Task D: value an unseen company as if it were private.
767
+
768
+ Simulates the PE use case: the model trains on public companies where
769
+ all data (including market price) is available, but at test time it
770
+ receives ONLY what a PE analyst would have — financial statements,
771
+ sector, and industry. All price-derived columns are stripped from
772
+ the test inputs.
773
+
774
+ Same holdout tickers and ground truth as Task A, different input
775
+ columns.
776
+ """
777
+ if "derived_market_cap" not in panel.columns:
778
+ logger.warning("derived_market_cap not in panel; skipping Task D")
779
+ return {"error": "No market cap data"}
780
+
781
+ # Use panel data at quarterly frequency
782
+ quarterly = panel.copy()
783
+ quarterly["date"] = pd.to_datetime(quarterly["date"])
784
+ quarterly["quarter"] = quarterly["date"].dt.to_period("Q")
785
+
786
+ # Take last observation per ticker × quarter
787
+ quarterly = quarterly.sort_values("date").drop_duplicates(
788
+ subset=["ticker", "quarter"], keep="last",
789
+ )
790
+
791
+ # Split: holdout tickers = evaluation
792
+ eval_mask = quarterly["ticker"].isin(holdout_tickers)
793
+ eval_df = quarterly[eval_mask].copy()
794
+
795
+ if eval_df.empty:
796
+ return {"error": "No holdout tickers found in panel"}
797
+
798
+ # Build inputs — ONLY what a PE analyst would have (no market data)
799
+ input_cols = ["ticker", "date", "sector", "industry"]
800
+ for c in quarterly.columns:
801
+ if c.startswith("stmt_"):
802
+ input_cols.append(c)
803
+ # Include non-price-derived fundamentals (e.g. derived_effective_tax_rate,
804
+ # derived_cost_of_debt, derived_beta, derived_wacc are computable from
805
+ # financial statements + macro data without market price — but beta and
806
+ # wacc require stock returns, so strip them too for a clean PE simulation)
807
+ input_cols = [c for c in input_cols if c in eval_df.columns
808
+ and c not in _PRICE_DERIVED_COLS]
809
+ inputs = eval_df[input_cols].copy()
810
+
811
+ # Ground truth — same as Task A
812
+ gt = eval_df[["ticker", "date", "derived_market_cap"]].copy()
813
+ gt = gt.rename(columns={"derived_market_cap": "actual_market_cap"})
814
+ gt = gt.dropna(subset=["actual_market_cap"])
815
+
816
+ # Save
817
+ inputs.to_parquet(output_dir / "private_valuation_inputs.parquet", index=False)
818
+ gt.to_parquet(output_dir / "private_valuation_ground_truth.parquet", index=False)
819
+
820
+ logger.info(
821
+ "Task D (Private Valuation): %d tickers, %d instances, %d input cols (no price data)",
822
+ gt["ticker"].nunique(), len(gt), len(input_cols),
823
+ )
824
+
825
+ return {
826
+ "n_tickers": gt["ticker"].nunique(),
827
+ "n_instances": len(gt),
828
+ "n_input_cols": len(input_cols),
829
+ "input_cols": input_cols,
830
+ "date_range": [str(gt["date"].min()), str(gt["date"].max())],
831
+ }
832
+
833
+
834
+ # ===================================================================
835
+ # Main entry point
836
+ # ===================================================================
837
+
838
+ def build_valuation_benchmark(
839
+ granularity: str = "daily",
840
+ ) -> dict[str, Any]:
841
+ """Build all valuation benchmark artifacts for a given granularity.
842
+
843
+ Reads from existing processed panel and benchmark data.
844
+ Writes to ``benchmark/{granularity}/``.
845
+
846
+ Returns summary dict with per-task statistics.
847
+ """
848
+ bench_dir = config.get_benchmark_dir(granularity)
849
+ bench_dir.mkdir(parents=True, exist_ok=True)
850
+
851
+ # Load existing data
852
+ proc_dir = config.get_processed_dir(granularity)
853
+ panel_path = proc_dir / "panel.parquet"
854
+ if not panel_path.exists():
855
+ # Try CSV fallback
856
+ panel_path = proc_dir / "panel.csv"
857
+ if not panel_path.exists():
858
+ return {"error": f"No panel data at {proc_dir}"}
859
+
860
+ panel = pd.read_parquet(panel_path) if panel_path.suffix == ".parquet" else pd.read_csv(panel_path)
861
+
862
+ # Company info
863
+ info_path = config.FUNDAMENTALS_DIR / "company_info.csv"
864
+ company_info = pd.read_csv(info_path) if info_path.exists() else pd.DataFrame()
865
+
866
+ # Scenarios
867
+ scenarios_path = bench_dir / "scenarios.parquet"
868
+ scenarios = pd.read_parquet(scenarios_path) if scenarios_path.exists() else pd.DataFrame()
869
+
870
+ # Holdout tickers (random subset, seeded for reproducibility)
871
+ all_tickers = sorted(panel["ticker"].unique().tolist())
872
+ rng = np.random.RandomState(config.BENCHMARK_SEED)
873
+ n_holdout = max(1, int(len(all_tickers) * config.VALUATION_HOLDOUT_RATIO))
874
+ holdout_tickers = rng.choice(all_tickers, size=n_holdout, replace=False).tolist()
875
+
876
+ logger.info(
877
+ "Building valuation benchmark: %d total tickers, %d holdout",
878
+ len(all_tickers), len(holdout_tickers),
879
+ )
880
+
881
+ # Build each task
882
+ summary: dict[str, Any] = {
883
+ "granularity": granularity,
884
+ "n_tickers_total": len(all_tickers),
885
+ "n_holdout": len(holdout_tickers),
886
+ "holdout_tickers": holdout_tickers,
887
+ }
888
+
889
+ summary["task_a"] = _build_task_a(panel, company_info, holdout_tickers, bench_dir)
890
+ summary["task_b"] = _build_task_b(company_info, holdout_tickers, bench_dir)
891
+ summary["task_c"] = _build_task_c(panel, scenarios, bench_dir)
892
+ summary["task_d"] = _build_task_d(panel, company_info, holdout_tickers, bench_dir)
893
+ summary["task_e"] = _build_task_e(company_info, holdout_tickers, bench_dir)
894
+ summary["task_f"] = _build_task_f(bench_dir)
895
+
896
+ # Task definition JSON
897
+ task_def = {
898
+ "benchmark_name": "whatif_valuation_v1",
899
+ "tasks": {
900
+ "A_valuation_accuracy": {
901
+ "description": "Estimate intrinsic equity value of public companies",
902
+ "input": "valuation_inputs.parquet",
903
+ "ground_truth": "valuation_ground_truth.parquet",
904
+ "metrics": ["MAPE", "median_APE", "rank_correlation", "directional_accuracy"],
905
+ "primary_metric": "MAPE",
906
+ "target_col": "actual_market_cap",
907
+ },
908
+ "B_statement_generation": {
909
+ "description": "Generate plausible financial statements from company description",
910
+ "input": "generation_inputs.parquet",
911
+ "ground_truth": "generation_ground_truth.parquet",
912
+ "metrics": ["per_field_MAPE", "balance_equation_accuracy", "ontology_compliance"],
913
+ "primary_metric": "per_field_MAPE",
914
+ },
915
+ "C_scenario_forecast": {
916
+ "description": "Forecast financial impact of what-if scenarios",
917
+ "input": "scenarios.parquet",
918
+ "ground_truth": "scenario_forecast_ground_truth.parquet",
919
+ "metrics": ["return_MAE", "directional_accuracy", "CI_calibration"],
920
+ "primary_metric": "return_MAE",
921
+ },
922
+ "D_private_valuation": {
923
+ "description": "Value an unseen company using only financials + sector (PE simulation)",
924
+ "input": "private_valuation_inputs.parquet",
925
+ "ground_truth": "private_valuation_ground_truth.parquet",
926
+ "metrics": ["MAPE", "median_APE", "rank_correlation", "directional_accuracy"],
927
+ "primary_metric": "median_APE",
928
+ "target_col": "actual_market_cap",
929
+ "note": "Same holdout tickers as Task A but all price-derived columns stripped from inputs",
930
+ },
931
+ "E_generator_evaluation": {
932
+ "description": "Generate financial statements for unseen companies and compare to actual XBRL filings",
933
+ "input": "generator_eval_inputs.parquet",
934
+ "ground_truth": "generator_eval_ground_truth.parquet",
935
+ "metrics": ["per_field_MAPE", "balance_equation_accuracy"],
936
+ "primary_metric": "per_field_MAPE",
937
+ "note": "Evaluates the Generator agent's output against actual company financials",
938
+ },
939
+ "F_real_estate_valuation": {
940
+ "description": "Estimate rent and price for unseen properties given location and features",
941
+ "input": "re_eval_inputs.parquet",
942
+ "ground_truth": "re_eval_ground_truth.parquet",
943
+ "train_data": "re_train_properties.parquet",
944
+ "metrics": ["rent_MAPE", "price_MAPE"],
945
+ "primary_metric": "rent_MAPE",
946
+ "note": "70/30 random split of RentCast properties; train set serves as comps database",
947
+ },
948
+ },
949
+ "holdout_tickers": holdout_tickers,
950
+ }
951
+ (bench_dir / "valuation_tasks.json").write_text(
952
+ json.dumps(task_def, indent=2, default=str),
953
+ )
954
+
955
+ logger.info("Valuation benchmark complete: %s", summary)
956
+ return summary
code/collect_filings.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 4: Download SEC filings (PDF + Markdown) and XBRL company facts.
2
+
3
+ Uses:
4
+ - SecEdgarDownloader from projects.tools.sec_edgar.downloader
5
+ - playwright.html_to_pdf from projects.tools.utils.playwright
6
+ - html2text (project dependency) for HTML -> Markdown conversion
7
+ - SEC XBRL CompanyFacts API for structured financial data
8
+
9
+ Pipeline per ticker:
10
+ 1. Resolve CIK (direct ticker lookup, then fuzzy match by company name)
11
+ 2. Download HTML filings to a temp dir via SecEdgarDownloader.download()
12
+ 3. Convert HTML -> PDF via playwright.html_to_pdf() (human-readable)
13
+ 4. Convert HTML -> Markdown via html2text (LLM-friendly)
14
+ 5. Download XBRL company facts JSON from SEC CompanyFacts API
15
+
16
+ CIK resolution strategy (every US-listed company MUST have a CIK):
17
+ 1. Direct ticker → CIK lookup via SEC company_tickers.json
18
+ 2. If that fails, fuzzy match by company name via SEC company_tickers_exchange.json
19
+ 3. Only if both fail is the ticker skipped (logged as warning)
20
+
21
+ Parallel tickers via asyncio.Semaphore.
22
+
23
+ Output:
24
+ data/filings/{TICKER}/*.pdf -- human-readable PDFs
25
+ data/filings/{TICKER}/*.md -- LLM-friendly Markdown
26
+ data/xbrl/raw/{TICKER}.json -- structured XBRL facts
27
+ data/xbrl/cik_map.json -- ticker → CIK mapping
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import asyncio
33
+ import json
34
+ import logging
35
+ import os
36
+ import tempfile
37
+ from pathlib import Path
38
+
39
+ import html2text
40
+ import httpx
41
+ import pandas as pd
42
+ from bs4 import BeautifulSoup
43
+
44
+ from projects.tools.sec_edgar.downloader import SecEdgarDownloader
45
+ from projects.tools.utils.playwright import html_to_pdf
46
+
47
+ from . import config
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+ # Shared html2text converter configuration
52
+ _h2t = html2text.HTML2Text()
53
+ _h2t.ignore_links = False
54
+ _h2t.ignore_images = True
55
+ _h2t.body_width = 0 # no line wrapping -- let the consumer handle it
56
+ _h2t.protect_links = True
57
+ _h2t.wrap_links = False
58
+
59
+ # Inline XBRL tag names to strip (they contain machine-readable noise)
60
+ _XBRL_STRIP_TAGS = ["ix:header", "ix:hidden"]
61
+
62
+
63
+ def _html_to_markdown(html_path: Path, md_path: Path) -> None:
64
+ """Convert an SEC filing HTML directly to Markdown using html2text.
65
+
66
+ Strips inline XBRL metadata (ix:header, ix:hidden) before conversion
67
+ so the resulting Markdown contains only the human-readable filing text.
68
+ """
69
+ html_content = html_path.read_text(encoding="utf-8", errors="replace")
70
+ soup = BeautifulSoup(html_content, "html.parser")
71
+ for tag_name in _XBRL_STRIP_TAGS:
72
+ for tag in soup.find_all(tag_name):
73
+ tag.decompose()
74
+ markdown_text: str = _h2t.handle(str(soup))
75
+ _ = md_path.write_text(markdown_text, encoding="utf-8")
76
+
77
+
78
+ # ---------------------------------------------------------------------------
79
+ # XBRL Company Facts helpers
80
+ # ---------------------------------------------------------------------------
81
+
82
+ _XBRL_RAW_DIR = config.XBRL_DIR / "raw"
83
+
84
+
85
+ def _atomic_json_write(data: dict, dest: Path) -> None:
86
+ """Write JSON atomically (tempfile + os.replace)."""
87
+ dest.parent.mkdir(parents=True, exist_ok=True)
88
+ fd, tmp = tempfile.mkstemp(suffix=".json", dir=dest.parent)
89
+ try:
90
+ os.close(fd)
91
+ with open(tmp, "w", encoding="utf-8") as fh:
92
+ json.dump(data, fh, ensure_ascii=False)
93
+ os.replace(tmp, dest)
94
+ except BaseException:
95
+ try:
96
+ os.unlink(tmp)
97
+ except OSError:
98
+ pass
99
+ raise
100
+
101
+
102
+ async def _resolve_cik_map(
103
+ client: httpx.AsyncClient,
104
+ tickers: list[str],
105
+ ) -> dict[str, str]:
106
+ """Build ticker → zero-padded CIK mapping (single API call, cached)."""
107
+ url = "https://www.sec.gov/files/company_tickers.json"
108
+ resp = await client.get(url)
109
+ resp.raise_for_status()
110
+ await asyncio.sleep(0.1)
111
+
112
+ raw: dict = resp.json()
113
+ sec_map: dict[str, str] = {}
114
+ for entry in raw.values():
115
+ t = str(entry.get("ticker", "")).upper()
116
+ cik = str(entry.get("cik_str", ""))
117
+ if t and cik:
118
+ sec_map[t] = cik.zfill(10)
119
+
120
+ result: dict[str, str] = {}
121
+ missing: list[str] = []
122
+ for ticker in tickers:
123
+ cik = sec_map.get(ticker.upper())
124
+ if cik:
125
+ result[ticker] = cik
126
+ else:
127
+ missing.append(ticker)
128
+
129
+ if missing:
130
+ logger.info(
131
+ "CIK map: %d resolved, %d missing (will try fuzzy match during filing download)",
132
+ len(result), len(missing),
133
+ )
134
+ return result
135
+
136
+
137
+ async def _download_xbrl_facts(
138
+ client: httpx.AsyncClient,
139
+ ticker: str,
140
+ cik: str,
141
+ ) -> bool:
142
+ """Download one company's XBRL facts JSON. Returns True on success."""
143
+ dest = _XBRL_RAW_DIR / f"{ticker}.json"
144
+ if dest.exists() and dest.stat().st_size > 100:
145
+ return True # already collected
146
+
147
+ url = config.XBRL_COMPANY_FACTS_URL.format(cik=cik)
148
+
149
+ for attempt in range(3):
150
+ try:
151
+ resp = await client.get(url)
152
+ if resp.status_code == 404:
153
+ _atomic_json_write(
154
+ {"_no_xbrl": True, "cik": cik, "ticker": ticker}, dest,
155
+ )
156
+ return True
157
+
158
+ resp.raise_for_status()
159
+ _atomic_json_write(resp.json(), dest)
160
+ return True
161
+
162
+ except httpx.HTTPStatusError as exc:
163
+ if exc.response.status_code == 429:
164
+ await asyncio.sleep(2 ** (attempt + 1))
165
+ elif exc.response.status_code >= 500:
166
+ await asyncio.sleep(2 ** attempt)
167
+ else:
168
+ logger.warning("XBRL HTTP %d for %s", exc.response.status_code, ticker)
169
+ return False
170
+ except (httpx.ConnectError, httpx.ReadTimeout):
171
+ await asyncio.sleep(2 ** attempt)
172
+
173
+ logger.warning("XBRL download failed for %s after 3 attempts", ticker)
174
+ return False
175
+
176
+
177
+ # ---------------------------------------------------------------------------
178
+ # Filing download helpers
179
+ # ---------------------------------------------------------------------------
180
+
181
+ _MAX_RETRIES = 3
182
+
183
+
184
+ async def _retry_async(coro_factory, description: str, retries: int = _MAX_RETRIES):
185
+ """Call *coro_factory()* up to *retries* times with exponential backoff.
186
+
187
+ ValueError is never retried (it signals a deterministic failure like
188
+ missing CIK, not a transient network issue).
189
+ """
190
+ for attempt in range(retries):
191
+ try:
192
+ return await coro_factory()
193
+ except ValueError:
194
+ raise # deterministic – retrying won't help
195
+ except Exception as exc:
196
+ if attempt < retries - 1:
197
+ wait = 2 ** attempt * 3 # 3s, 6s, 12s
198
+ logger.warning("%s failed (attempt %d/%d), retrying in %ds: %s",
199
+ description, attempt + 1, retries, wait, exc)
200
+ await asyncio.sleep(wait)
201
+ else:
202
+ raise
203
+
204
+
205
+ async def _download_with_fallback(
206
+ ticker: str,
207
+ company_name: str,
208
+ downloader: SecEdgarDownloader,
209
+ output_dir: Path,
210
+ ) -> list[Path]:
211
+ """Download filings, falling back to CIK-by-company-name if ticker lookup fails.
212
+
213
+ Every US-listed company has a CIK. The direct ticker→CIK map sometimes
214
+ misses tickers (recent renames, class shares, etc.), so we fall back to
215
+ fuzzy-matching the company name against the SEC title database.
216
+ """
217
+ try:
218
+ return await downloader.download(
219
+ ticker=ticker,
220
+ filing_types=config.SEC_FILING_TYPES, # type: ignore[arg-type]
221
+ from_year=config.START_YEAR,
222
+ to_year=config.END_YEAR,
223
+ output_dir=output_dir,
224
+ )
225
+ except ValueError:
226
+ pass # ticker not in CIK map – try fallback
227
+
228
+ if not company_name:
229
+ raise ValueError(f"Ticker {ticker} not in SEC CIK map and no company name for fallback.")
230
+
231
+ logger.info("%s: ticker lookup failed, trying fuzzy match for '%s' ...", ticker, company_name)
232
+ matches = await downloader.score_title_fuzzy_match(company_name)
233
+ if not matches:
234
+ raise ValueError(f"Ticker {ticker}: no fuzzy matches for '{company_name}'.")
235
+
236
+ best = matches[0]
237
+ if best.score < 60:
238
+ raise ValueError(
239
+ f"Ticker {ticker}: best fuzzy match '{best.title}' (CIK={best.cik}) "
240
+ f"scored only {best.score:.0f} – too low to trust."
241
+ )
242
+
243
+ logger.info("%s: fuzzy matched → '%s' (CIK=%s, score=%.0f)", ticker, best.title, best.cik, best.score)
244
+ return await downloader.download(
245
+ cik=best.cik,
246
+ filing_types=config.SEC_FILING_TYPES, # type: ignore[arg-type]
247
+ from_year=config.START_YEAR,
248
+ to_year=config.END_YEAR,
249
+ output_dir=output_dir,
250
+ )
251
+
252
+
253
+ async def _download_ticker_filings(
254
+ ticker: str,
255
+ company_name: str,
256
+ downloader: SecEdgarDownloader,
257
+ semaphore: asyncio.Semaphore,
258
+ xbrl_client: httpx.AsyncClient | None = None,
259
+ cik: str | None = None,
260
+ ) -> int:
261
+ """Download filings + XBRL for a single ticker. Returns number of filings processed."""
262
+ ticker_dir = config.FILINGS_DIR / ticker
263
+ done_flag = ticker_dir / ".done"
264
+ filings_done = done_flag.exists()
265
+
266
+ xbrl_path = _XBRL_RAW_DIR / f"{ticker}.json"
267
+ xbrl_done = xbrl_path.exists() and xbrl_path.stat().st_size > 100
268
+
269
+ if filings_done and xbrl_done:
270
+ return 0 # everything already done
271
+
272
+ async with semaphore:
273
+ filing_count = 0
274
+
275
+ # ── Filing documents (PDF + Markdown) ─────────────────────────
276
+ if not filings_done:
277
+ logger.info("Downloading filings for %s ...", ticker)
278
+ ticker_dir.mkdir(parents=True, exist_ok=True)
279
+ all_conversions_ok = True
280
+
281
+ try:
282
+ with tempfile.TemporaryDirectory(prefix="whatif_sec_") as tmpdir:
283
+ tmpdir_path = Path(tmpdir)
284
+ html_paths = await _retry_async(
285
+ lambda: _download_with_fallback(
286
+ ticker, company_name, downloader, tmpdir_path,
287
+ ),
288
+ description=f"SEC download {ticker}",
289
+ )
290
+
291
+ for htm_path in html_paths:
292
+ base_name = htm_path.parent.name
293
+ pdf_path = ticker_dir / (base_name + ".pdf")
294
+ md_path = ticker_dir / (base_name + ".md")
295
+
296
+ # HTML -> PDF (human-readable; skip if already exists)
297
+ if not pdf_path.exists():
298
+ try:
299
+ await _retry_async(
300
+ lambda _h=htm_path, _p=pdf_path: html_to_pdf(_h, _p),
301
+ description=f"PDF {ticker}/{htm_path.name}",
302
+ )
303
+ except Exception as exc:
304
+ logger.warning("PDF conversion failed for %s/%s after retries: %s",
305
+ ticker, htm_path.name, exc)
306
+ all_conversions_ok = False
307
+
308
+ # HTML -> Markdown (LLM-friendly; skip if already exists)
309
+ if not md_path.exists():
310
+ try:
311
+ _html_to_markdown(htm_path, md_path)
312
+ except Exception as exc:
313
+ logger.warning("Markdown conversion failed for %s/%s: %s",
314
+ ticker, htm_path.name, exc)
315
+ all_conversions_ok = False
316
+
317
+ filing_count += 1
318
+
319
+ # Only mark as done if ALL conversions succeeded
320
+ if all_conversions_ok:
321
+ _ = done_flag.write_text(f"filings={filing_count}")
322
+ logger.info("%s: %d filings processed (PDF + MD).%s",
323
+ ticker, filing_count,
324
+ "" if all_conversions_ok else " (some conversions failed, will retry)")
325
+ except ValueError as exc:
326
+ logger.warning("Ticker %s: CIK resolution failed after all strategies: %s", ticker, exc)
327
+ except Exception as exc:
328
+ logger.warning("Filing download failed for %s: %s", ticker, exc)
329
+
330
+ # ── XBRL company facts ────────────────────────────────────────
331
+ if not xbrl_done and xbrl_client is not None and cik:
332
+ try:
333
+ await _download_xbrl_facts(xbrl_client, ticker, cik)
334
+ except Exception as exc:
335
+ logger.warning("XBRL download failed for %s: %s", ticker, exc)
336
+
337
+ return filing_count
338
+
339
+
340
+ def _load_company_names() -> dict[str, str]:
341
+ """Load ticker → company name mapping from the universe CSV."""
342
+ univ_path = config.UNIVERSE_DIR / "benchmark_universe.csv"
343
+ if not univ_path.exists():
344
+ return {}
345
+ df = pd.read_csv(univ_path)
346
+ if "ticker" in df.columns and "name" in df.columns:
347
+ return dict(zip(df["ticker"], df["name"].fillna("")))
348
+ return {}
349
+
350
+
351
+ async def run_async(tickers: list[str] | None = None) -> dict[str, int]:
352
+ """Execute Step 4 (async): download filings + XBRL facts.
353
+
354
+ Returns ``{ticker: filing_count}``.
355
+ """
356
+ config.FILINGS_DIR.mkdir(parents=True, exist_ok=True)
357
+ _XBRL_RAW_DIR.mkdir(parents=True, exist_ok=True)
358
+
359
+ user_agent = os.getenv("SEC_EDGAR_USER_AGENT")
360
+ if not user_agent:
361
+ raise ValueError("Set SEC_EDGAR_USER_AGENT environment variable.")
362
+
363
+ if tickers is None:
364
+ universe_path = config.UNIVERSE_DIR / "benchmark_universe.csv"
365
+ if not universe_path.exists():
366
+ raise FileNotFoundError(f"Run Step 1 first: {universe_path}")
367
+ tickers = pd.read_csv(universe_path)["ticker"].tolist()
368
+
369
+ # Load company names for CIK fuzzy-match fallback
370
+ company_names = _load_company_names()
371
+
372
+ # Resolve CIK map for XBRL (single API call, reused across all tickers)
373
+ headers = {"User-Agent": user_agent, "Accept-Encoding": "gzip, deflate"}
374
+ async with httpx.AsyncClient(
375
+ headers=headers, timeout=30.0, follow_redirects=True,
376
+ ) as xbrl_client:
377
+ cik_map = await _resolve_cik_map(xbrl_client, tickers)
378
+
379
+ # Persist CIK map for reference
380
+ cik_map_path = config.XBRL_DIR / "cik_map.json"
381
+ config.XBRL_DIR.mkdir(parents=True, exist_ok=True)
382
+ _atomic_json_write(cik_map, cik_map_path)
383
+
384
+ logger.info(
385
+ "Downloading SEC filings + XBRL for %d tickers "
386
+ "(%d with company names, %d with CIK) ...",
387
+ len(tickers), len(company_names), len(cik_map),
388
+ )
389
+
390
+ downloader = SecEdgarDownloader(user_agent=user_agent)
391
+ semaphore = asyncio.Semaphore(config.SEC_FILING_WORKERS)
392
+
393
+ tasks = [
394
+ _download_ticker_filings(
395
+ t,
396
+ company_names.get(t, ""),
397
+ downloader,
398
+ semaphore,
399
+ xbrl_client=xbrl_client,
400
+ cik=cik_map.get(t),
401
+ )
402
+ for t in tickers
403
+ ]
404
+ results = await asyncio.gather(*tasks, return_exceptions=True)
405
+
406
+ summary: dict[str, int] = {}
407
+ for ticker, result in zip(tickers, results):
408
+ if isinstance(result, BaseException):
409
+ logger.warning("Ticker %s raised: %s", ticker, result)
410
+ summary[ticker] = 0
411
+ else:
412
+ summary[ticker] = result
413
+
414
+ total = sum(summary.values())
415
+ xbrl_count = sum(1 for f in _XBRL_RAW_DIR.glob("*.json") if f.stat().st_size > 100)
416
+ logger.info(
417
+ "SEC Step 4 complete: %d filings across %d tickers, %d XBRL facts downloaded.",
418
+ total, len(tickers), xbrl_count,
419
+ )
420
+ return summary
421
+
422
+
423
+ def run(tickers: list[str] | None = None) -> dict[str, int]:
424
+ """Sync wrapper around the async implementation."""
425
+ return asyncio.run(run_async(tickers))
code/collect_fundamentals.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 2: Collect company fundamentals.
2
+
3
+ For each ticker in the universe: yfinance .info (PE, EPS, margins, ROE,
4
+ ROA, market cap, revenue, EBITDA) and quarterly financial statements
5
+ (quarterly_income_stmt, quarterly_balance_sheet, quarterly_cashflow).
6
+
7
+ Processes tickers sequentially with a mandatory delay between requests
8
+ to stay under yfinance rate limits. Includes retry with exponential
9
+ backoff on rate-limit errors.
10
+
11
+ Output:
12
+ data/fundamentals/company_info.csv -- summary info per ticker
13
+ data/fundamentals/{TICKER}_income.csv -- quarterly income statement
14
+ data/fundamentals/{TICKER}_balance.csv -- quarterly balance sheet
15
+ data/fundamentals/{TICKER}_cashflow.csv -- quarterly cash flow statement
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+ import time
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ import pandas as pd
26
+ import yfinance as yf
27
+
28
+ from . import config
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ # Fields to pull from yfinance Ticker.info
33
+ INFO_FIELDS = [
34
+ "marketCap",
35
+ "trailingPE",
36
+ "forwardPE",
37
+ "trailingEps",
38
+ "forwardEps",
39
+ "priceToSalesTrailing12Months",
40
+ "priceToBook",
41
+ "enterpriseValue",
42
+ "enterpriseToRevenue",
43
+ "enterpriseToEbitda",
44
+ "profitMargins",
45
+ "operatingMargins",
46
+ "grossMargins",
47
+ "returnOnEquity",
48
+ "returnOnAssets",
49
+ "debtToEquity",
50
+ "totalRevenue",
51
+ "revenueGrowth",
52
+ "ebitda",
53
+ "totalDebt",
54
+ "totalCash",
55
+ "freeCashflow",
56
+ "operatingCashflow",
57
+ "sector",
58
+ "industry",
59
+ "fullTimeEmployees",
60
+ ]
61
+
62
+
63
+ def _collect_single_ticker(ticker: str, out_dir: Path, max_retries: int = 3) -> dict[str, Any] | None:
64
+ """Collect info + statements for one ticker. Returns info dict or None."""
65
+ info_path = out_dir / f"{ticker}_info_done.flag"
66
+ if info_path.exists():
67
+ return None # already collected
68
+
69
+ info = None
70
+ for attempt in range(max_retries):
71
+ try:
72
+ t = yf.Ticker(ticker)
73
+ info = t.info
74
+ break
75
+ except Exception as exc:
76
+ err_str = str(exc)
77
+ if "Too Many Requests" in err_str or "Rate" in err_str:
78
+ wait = 2 ** attempt * 5 # 5s, 10s, 20s
79
+ time.sleep(wait)
80
+ continue
81
+ logger.warning("Skipping %s (.info failed): %s", ticker, exc)
82
+ return None
83
+
84
+ if info is None:
85
+ logger.warning("Rate-limited for %s after %d retries", ticker, max_retries)
86
+ return None
87
+
88
+ row: dict[str, Any] = {"ticker": ticker}
89
+ for field in INFO_FIELDS:
90
+ row[field] = info.get(field) # type: ignore[union-attr]
91
+
92
+ # Quarterly financial statements (native quarterly granularity)
93
+ for attr, suffix in [
94
+ ("quarterly_income_stmt", "income"),
95
+ ("quarterly_balance_sheet", "balance"),
96
+ ("quarterly_cashflow", "cashflow"),
97
+ ]:
98
+ try:
99
+ stmt: pd.DataFrame = getattr(t, attr)
100
+ if stmt is not None and not stmt.empty:
101
+ stmt.to_csv(out_dir / f"{ticker}_{suffix}.csv")
102
+ except Exception as exc:
103
+ logger.debug("Could not get %s for %s: %s", attr, ticker, exc)
104
+
105
+ # Mark as done
106
+ _ = info_path.write_text("done")
107
+ return row
108
+
109
+
110
+ def run(tickers: list[str] | None = None) -> pd.DataFrame:
111
+ """Execute Step 2 and return the company_info DataFrame."""
112
+ config.FUNDAMENTALS_DIR.mkdir(parents=True, exist_ok=True)
113
+ out_path = config.FUNDAMENTALS_DIR / "company_info.csv"
114
+
115
+ if tickers is None:
116
+ universe_path = config.UNIVERSE_DIR / "benchmark_universe.csv"
117
+ if not universe_path.exists():
118
+ raise FileNotFoundError(f"Run Step 1 first: {universe_path}")
119
+ tickers = pd.read_csv(universe_path)["ticker"].tolist()
120
+
121
+ # Filter to tickers not yet collected (resume-safe via flag files)
122
+ already_done = {f.stem.replace("_info_done", "")
123
+ for f in config.FUNDAMENTALS_DIR.glob("*_info_done.flag")}
124
+ remaining = [t for t in tickers if t not in already_done]
125
+ logger.info("Collecting fundamentals for %d tickers (%d already done) ...",
126
+ len(remaining), len(already_done))
127
+
128
+ rows: list[dict] = []
129
+ # Sequential with delay to avoid yfinance rate limits
130
+ for i, ticker in enumerate(remaining):
131
+ result = _collect_single_ticker(ticker, config.FUNDAMENTALS_DIR)
132
+ if result is not None:
133
+ rows.append(result)
134
+ # Checkpoint every 10 tickers (more frequent = less data loss on crash,
135
+ # and the flag file is only written AFTER statements are saved so the
136
+ # checkpoint is the only window where data could be lost)
137
+ if (i + 1) % 10 == 0:
138
+ if rows:
139
+ _df = pd.DataFrame(rows)
140
+ if out_path.exists():
141
+ _existing = pd.read_csv(out_path)
142
+ _df = pd.concat([_existing, _df]).drop_duplicates(subset="ticker", keep="last")
143
+ _df.sort_values("ticker").to_csv(out_path, index=False)
144
+ rows.clear() # flush — already persisted
145
+ if (i + 1) % 50 == 0:
146
+ logger.info("Fundamentals progress: %d / %d", i + 1, len(remaining))
147
+ # Mandatory delay between requests to stay under yfinance limits
148
+ time.sleep(1.5)
149
+
150
+ if rows:
151
+ new_df = pd.DataFrame(rows)
152
+ # Merge with any existing data (resume-safe)
153
+ if out_path.exists():
154
+ existing = pd.read_csv(out_path)
155
+ combined = pd.concat([existing, new_df]).drop_duplicates(subset="ticker", keep="last")
156
+ else:
157
+ combined = new_df
158
+ combined.sort_values("ticker").to_csv(out_path, index=False)
159
+ logger.info("Saved company_info (%d rows) to %s", len(combined), out_path)
160
+ return combined
161
+
162
+ if out_path.exists():
163
+ return pd.read_csv(out_path)
164
+ return pd.DataFrame()
code/collect_macro.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 5: Collect macro-economic context data.
2
+
3
+ Uses:
4
+ - FredClient from projects.tools.finance.fred (interest rates, indices, dollar index)
5
+ - EIAClient from projects.tools.commodity.eia (crude oil, natural gas)
6
+
7
+ Resume logic:
8
+ - FRED: per-series file check + freshness validation.
9
+ - EIA: per-file freshness check (not per-category!).
10
+ If any processed CSV is stale (max date > STALE_DAYS behind END_DATE),
11
+ it is deleted and re-fetched.
12
+
13
+ Output:
14
+ data/macro/fred_{SERIES_ID}.csv
15
+ data/macro/crude_oil/{name}_raw.csv + {name}.csv
16
+ data/macro/natural_gas/{name}_raw.csv + {name}.csv
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import logging
23
+ import os
24
+ import tempfile
25
+ from pathlib import Path
26
+
27
+ import pandas as pd
28
+
29
+ from projects.tools.commodity.eia import EIAClient
30
+ from projects.tools.finance.fred import FredClient
31
+
32
+ from . import config
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ _MAX_RETRIES = 3
37
+
38
+ # A processed CSV is considered stale if its latest date is more than
39
+ # STALE_DAYS before config.END_DATE.
40
+ _STALE_DAYS = 90
41
+
42
+
43
+ async def _retry_async(coro_factory, description: str, retries: int = _MAX_RETRIES):
44
+ """Call *coro_factory()* up to *retries* times with exponential backoff."""
45
+ for attempt in range(retries):
46
+ try:
47
+ return await coro_factory()
48
+ except Exception as exc:
49
+ if attempt < retries - 1:
50
+ wait = 2 ** attempt * 3 # 3s, 6s, 12s
51
+ logger.warning("%s failed (attempt %d/%d), retrying in %ds: %s",
52
+ description, attempt + 1, retries, wait, exc)
53
+ await asyncio.sleep(wait)
54
+ else:
55
+ raise
56
+
57
+
58
+ def _atomic_csv_write(df: pd.DataFrame, dest: Path) -> None:
59
+ """Write a CSV atomically: write to temp file first, then rename."""
60
+ dest.parent.mkdir(parents=True, exist_ok=True)
61
+ fd, tmp_path = tempfile.mkstemp(suffix=".csv", dir=dest.parent)
62
+ try:
63
+ os.close(fd)
64
+ df.to_csv(tmp_path, index=False)
65
+ os.replace(tmp_path, dest)
66
+ except BaseException:
67
+ try:
68
+ os.unlink(tmp_path)
69
+ except OSError:
70
+ pass
71
+ raise
72
+
73
+
74
+ def _is_stale(csv_path: Path) -> bool:
75
+ """Check if a CSV's latest date is too far behind config.END_DATE."""
76
+ if not csv_path.exists():
77
+ return True # missing = stale
78
+ try:
79
+ df = pd.read_csv(csv_path, nrows=0)
80
+ date_col = next(
81
+ (c for c in df.columns if "date" in c.lower()
82
+ or "period" in c.lower() or "time" in c.lower()),
83
+ None,
84
+ )
85
+ if date_col is None:
86
+ return False # can't determine, assume OK
87
+ df = pd.read_csv(csv_path, usecols=[date_col])
88
+ df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
89
+ max_date = df[date_col].max()
90
+ if pd.isna(max_date):
91
+ return True
92
+ cutoff = pd.Timestamp(config.END_DATE) - pd.Timedelta(days=_STALE_DAYS)
93
+ if max_date < cutoff:
94
+ logger.warning(
95
+ "STALE: %s latest date is %s (cutoff %s, %d days behind)",
96
+ csv_path.name, max_date.date(), cutoff.date(),
97
+ (pd.Timestamp(config.END_DATE) - max_date).days,
98
+ )
99
+ return True
100
+ return False
101
+ except Exception as exc:
102
+ logger.warning("Could not check freshness of %s (treating as stale): %s", csv_path.name, exc)
103
+ return True # corrupt / unreadable → treat as stale so it gets re-fetched
104
+
105
+
106
+ # ---------------------------------------------------------------------------
107
+ # FRED collection (per-series resume + freshness)
108
+ # ---------------------------------------------------------------------------
109
+
110
+ async def _collect_fred(client: FredClient) -> None:
111
+ """Fetch every FRED series defined in config."""
112
+ fred_dir = config.MACRO_DIR
113
+ fred_dir.mkdir(parents=True, exist_ok=True)
114
+
115
+ for series_id, description in config.FRED_SERIES.items():
116
+ out_path = fred_dir / f"fred_{series_id}.csv"
117
+ if out_path.exists() and not _is_stale(out_path):
118
+ logger.info("FRED %s already exists and is fresh, skipping.", series_id)
119
+ continue
120
+
121
+ reason = "stale" if out_path.exists() else "missing"
122
+ logger.info("Fetching FRED %s (%s) [%s] ...", series_id, description, reason)
123
+ try:
124
+ df = await _retry_async(
125
+ lambda sid=series_id: client.fetch_series_data(
126
+ series_id=sid,
127
+ start_date=config.START_DATE,
128
+ end_date=config.END_DATE,
129
+ ),
130
+ description=f"FRED {series_id}",
131
+ )
132
+ _atomic_csv_write(df, out_path)
133
+ logger.info("Saved FRED %s (%d rows).", series_id, len(df))
134
+ except Exception as exc:
135
+ logger.warning("FRED %s failed after retries: %s", series_id, exc)
136
+
137
+
138
+ # ---------------------------------------------------------------------------
139
+ # EIA collection (per-file freshness, NOT per-category!)
140
+ # ---------------------------------------------------------------------------
141
+
142
+ async def _collect_eia_category(
143
+ client: EIAClient,
144
+ category: str,
145
+ out_dir: Path,
146
+ fetch_fn,
147
+ ) -> None:
148
+ """Fetch an EIA category, re-downloading only missing or stale files."""
149
+ out_dir.mkdir(parents=True, exist_ok=True)
150
+
151
+ # Inventory existing processed files
152
+ existing = {f.stem: f for f in out_dir.glob("*.csv") if "_raw" not in f.stem}
153
+ stale_files = [name for name, path in existing.items() if _is_stale(path)]
154
+ fresh_count = len(existing) - len(stale_files)
155
+
156
+ if stale_files:
157
+ logger.info(
158
+ "EIA %s: %d fresh files, %d stale to re-fetch: %s",
159
+ category, fresh_count, len(stale_files), stale_files,
160
+ )
161
+ # Delete stale files so they get re-written
162
+ for name in stale_files:
163
+ for suffix in ["", "_raw"]:
164
+ p = out_dir / f"{name}{suffix}.csv"
165
+ if p.exists():
166
+ p.unlink()
167
+ logger.info(" Deleted stale %s", p.name)
168
+ elif existing:
169
+ logger.info("EIA %s: all %d files are fresh, skipping.", category, len(existing))
170
+ return
171
+
172
+ # Fetch all data from the API (EIA client returns all endpoints at once)
173
+ logger.info("Fetching EIA %s data ...", category)
174
+ try:
175
+ results = await _retry_async(fetch_fn, description=f"EIA {category}")
176
+ if not results:
177
+ logger.warning("EIA %s: all endpoints returned empty (check API key / network).",
178
+ category)
179
+ return
180
+ for name, raw_df, processed_df in results:
181
+ processed_path = out_dir / f"{name}.csv"
182
+ raw_path = out_dir / f"{name}_raw.csv"
183
+ # Only write if the file is missing or was stale
184
+ if not processed_path.exists() or name in stale_files:
185
+ _atomic_csv_write(raw_df, raw_path)
186
+ _atomic_csv_write(processed_df, processed_path)
187
+ logger.info(" Saved %s %s (%d raw, %d processed rows).",
188
+ category, name, len(raw_df), len(processed_df))
189
+ else:
190
+ logger.info(" %s %s already fresh, not overwriting.", category, name)
191
+ except Exception as exc:
192
+ logger.error("EIA %s collection failed after retries: %s: %s",
193
+ category, type(exc).__name__, exc, exc_info=True)
194
+
195
+
196
+ async def _collect_eia(client: EIAClient) -> None:
197
+ """Fetch crude oil and natural gas data from EIA (per-file freshness)."""
198
+ await _collect_eia_category(
199
+ client,
200
+ category="crude_oil",
201
+ out_dir=config.MACRO_DIR / "crude_oil",
202
+ fetch_fn=lambda: client.get_all_crude_oil_data(),
203
+ )
204
+ await _collect_eia_category(
205
+ client,
206
+ category="natural_gas",
207
+ out_dir=config.MACRO_DIR / "natural_gas",
208
+ fetch_fn=lambda: client.get_all_natural_gas_data(),
209
+ )
210
+
211
+
212
+ async def run_async() -> None:
213
+ """Execute Step 5 (async)."""
214
+ fred_key = os.getenv("FRED_API_KEY")
215
+ if not fred_key:
216
+ raise ValueError("Set FRED_API_KEY environment variable.")
217
+
218
+ eia_key = os.getenv("EIA_API_KEY")
219
+ if not eia_key:
220
+ raise ValueError("Set EIA_API_KEY environment variable.")
221
+
222
+ fred_client = FredClient(api_key=fred_key)
223
+ eia_client = EIAClient(api_key=eia_key)
224
+
225
+ await _collect_fred(fred_client)
226
+ await _collect_eia(eia_client)
227
+
228
+ logger.info("Macro data collection complete.")
229
+
230
+
231
+ def run() -> None:
232
+ """Sync wrapper around the async implementation."""
233
+ asyncio.run(run_async())
code/collect_news.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 10 – News collection.
2
+
3
+ Collects two categories of news data:
4
+
5
+ Part A: Per-ticker news & press releases via YFinance (FREE, recent only).
6
+ Part B: Per-scenario event-specific news via Firecrawl (date-targeted)
7
+ with Tavily fallback.
8
+
9
+ Output
10
+ ------
11
+ data/news/tickers/{TICKER}.json -- per-ticker yfinance news + press
12
+ data/news/scenarios/{scenario_id}.json -- per-scenario Firecrawl/Tavily
13
+
14
+ Resume: skips if output file already exists.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import json
21
+ import logging
22
+ import os
23
+ import time
24
+ from concurrent.futures import ThreadPoolExecutor
25
+ from pathlib import Path
26
+
27
+ import pandas as pd
28
+ from dotenv import load_dotenv
29
+
30
+ from projects.agent_builder.scripts.whatif_bench import config
31
+
32
+ load_dotenv()
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # Helpers
38
+ # ---------------------------------------------------------------------------
39
+
40
+ def _ensure_dirs() -> tuple[Path, Path]:
41
+ """Create news output directories and return (tickers_dir, scenarios_dir)."""
42
+ tickers_dir = config.NEWS_DIR / "tickers"
43
+ scenarios_dir = config.NEWS_DIR / "scenarios"
44
+ tickers_dir.mkdir(parents=True, exist_ok=True)
45
+ scenarios_dir.mkdir(parents=True, exist_ok=True)
46
+ return tickers_dir, scenarios_dir
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Part A – Per-ticker news + press releases (yfinance, FREE)
51
+ # ---------------------------------------------------------------------------
52
+
53
+ def _collect_single_ticker_news(ticker: str, tickers_dir: Path, client) -> int:
54
+ """Fetch news + press releases for a single ticker. Returns article count."""
55
+ out_path = tickers_dir / f"{ticker}.json"
56
+ if out_path.exists():
57
+ return 0 # resume: already collected
58
+
59
+ articles: list[dict] = []
60
+ any_success = False
61
+
62
+ for tab in ("news", "press releases"):
63
+ for attempt in range(3):
64
+ try:
65
+ result = client.fetch_news_from_single_ticker(
66
+ ticker, tab=tab, count=config.NEWS_PER_TICKER_COUNT,
67
+ )
68
+ articles.extend([item.model_dump(mode="json") for item in result.root])
69
+ any_success = True
70
+ break
71
+ except Exception:
72
+ if attempt == 2:
73
+ logger.warning("Failed to fetch %s tab=%s after 3 attempts", ticker, tab)
74
+ else:
75
+ time.sleep(2 ** attempt)
76
+
77
+ # Fallback: if yfinance returned nothing, try Tavily for per-ticker news.
78
+ # Tavily is a paid API but handles obscure small-caps better than yfinance.
79
+ if not articles:
80
+ tavily_key = os.environ.get("TAVILY_API_KEY", "")
81
+ if tavily_key:
82
+ try:
83
+ from tavily import TavilyClient
84
+ tv = TavilyClient(api_key=tavily_key)
85
+ tv_results = tv.search(
86
+ query=f"{ticker} stock news financial",
87
+ search_depth="basic",
88
+ max_results=config.NEWS_PER_TICKER_COUNT,
89
+ topic="news",
90
+ )
91
+ for item in tv_results.get("results", []):
92
+ articles.append({
93
+ "source": "tavily",
94
+ "title": item.get("title", ""),
95
+ "url": item.get("url", ""),
96
+ "snippet": item.get("content", ""),
97
+ "date": item.get("published_date", ""),
98
+ })
99
+ if articles:
100
+ any_success = True
101
+ logger.info("Tavily fallback for %s: %d articles", ticker, len(articles))
102
+ except Exception as exc:
103
+ logger.debug("Tavily fallback failed for %s: %s", ticker, exc)
104
+
105
+ # Only write the file if at least one tab succeeded.
106
+ # If ALL tabs failed, do NOT write — leave the file missing so it's retried next run.
107
+ if any_success:
108
+ tmp_path = out_path.with_suffix(".json.tmp")
109
+ tmp_path.write_text(json.dumps(articles, default=str), encoding="utf-8")
110
+ tmp_path.replace(out_path) # atomic rename
111
+ else:
112
+ logger.warning("All tabs failed for %s — NOT writing file (will retry next run)", ticker)
113
+
114
+ return len(articles)
115
+
116
+
117
+ # Shared lock to enforce actual rate limiting across threads
118
+ import threading
119
+ _rate_lock = threading.Lock()
120
+ _last_request_time = 0.0
121
+
122
+
123
+ def _rate_limited_worker(ticker: str, tickers_dir: Path, client) -> int:
124
+ """Worker that enforces sequential rate limiting via a shared lock."""
125
+ global _last_request_time
126
+ with _rate_lock:
127
+ elapsed = time.time() - _last_request_time
128
+ if elapsed < config.NEWS_RATE_LIMIT_SEC:
129
+ time.sleep(config.NEWS_RATE_LIMIT_SEC - elapsed)
130
+ _last_request_time = time.time()
131
+ return _collect_single_ticker_news(ticker, tickers_dir, client)
132
+
133
+
134
+ def _run_part_a(tickers: list[str], tickers_dir: Path) -> None:
135
+ """Parallel per-ticker news collection with proper rate limiting."""
136
+ logger.info("Part A: collecting per-ticker news for %d tickers …", len(tickers))
137
+
138
+ from concurrent.futures import as_completed
139
+ from projects.tools.finance.yahoo import YFinanceClient
140
+
141
+ # Single shared client for connection reuse
142
+ client = YFinanceClient()
143
+ total_articles = 0
144
+ done = 0
145
+
146
+ with ThreadPoolExecutor(max_workers=config.NEWS_WORKERS) as pool:
147
+ futures = {pool.submit(_rate_limited_worker, t, tickers_dir, client): t for t in tickers}
148
+ for future in as_completed(futures):
149
+ ticker = futures[future]
150
+ try:
151
+ n = future.result()
152
+ total_articles += n
153
+ except Exception:
154
+ logger.exception("Error collecting news for %s", ticker)
155
+ done += 1
156
+ if done % 200 == 0:
157
+ logger.info(" Part A progress: %d / %d tickers", done, len(tickers))
158
+
159
+ logger.info("Part A complete: %d articles across %d tickers", total_articles, len(tickers))
160
+
161
+
162
+ # ---------------------------------------------------------------------------
163
+ # Part B – Scenario-event news (Firecrawl + Tavily fallback)
164
+ # ---------------------------------------------------------------------------
165
+
166
+ async def _collect_single_scenario_news(
167
+ scenario: dict,
168
+ scenarios_dir: Path,
169
+ firecrawl_client,
170
+ tavily_client,
171
+ ) -> int:
172
+ """Fetch news for a single scenario event. Returns article count."""
173
+ sc_id = scenario["scenario_id"]
174
+ out_path = scenarios_dir / f"{sc_id}.json"
175
+ if out_path.exists():
176
+ return 0
177
+
178
+ event_date = pd.Timestamp(scenario["event_date"])
179
+ # Wider window (±30 days) — narrow windows return empty from news APIs
180
+ start = (event_date - pd.Timedelta(days=30)).strftime("%-m/%-d/%Y")
181
+ end = (event_date + pd.Timedelta(days=30)).strftime("%-m/%-d/%Y")
182
+ tbs = f"cdr:1,cd_min:{start},cd_max:{end}"
183
+ # Simplify query: use event_type keywords + date, not full description
184
+ event_type = scenario.get("event_type", "").replace("_", " ")
185
+ year_month = event_date.strftime("%B %Y")
186
+ query = f"{event_type} {year_month} financial markets impact"
187
+
188
+ articles: list[dict] = []
189
+
190
+ # Try Firecrawl first
191
+ try:
192
+ fc_results = await firecrawl_client._search(
193
+ query=query,
194
+ limit=config.NEWS_SCENARIO_LIMIT,
195
+ sources=["news"],
196
+ categories=[],
197
+ tbs=tbs,
198
+ )
199
+ if fc_results and hasattr(fc_results, "news") and fc_results.news:
200
+ for item in fc_results.news:
201
+ articles.append({
202
+ "source": "firecrawl",
203
+ "title": getattr(item, "title", ""),
204
+ "url": getattr(item, "url", ""),
205
+ "snippet": getattr(item, "snippet", getattr(item, "description", "")),
206
+ "date": getattr(item, "date", ""),
207
+ })
208
+ except Exception:
209
+ logger.warning("Firecrawl failed for scenario %s, trying Tavily", sc_id)
210
+
211
+ # Tavily fallback if Firecrawl returned nothing
212
+ if not articles and tavily_client is not None:
213
+ try:
214
+ tv_results = await tavily_client._search(
215
+ query=query,
216
+ search_depth="advanced",
217
+ include_raw_content=True,
218
+ max_results=config.NEWS_SCENARIO_LIMIT,
219
+ )
220
+ for item in tv_results.get("results", []):
221
+ articles.append({
222
+ "source": "tavily",
223
+ "title": item.get("title", ""),
224
+ "url": item.get("url", ""),
225
+ "snippet": item.get("content", ""),
226
+ "date": item.get("published_date", ""),
227
+ "raw_content": item.get("raw_content", ""),
228
+ })
229
+ except Exception:
230
+ logger.warning("Tavily also failed for scenario %s", sc_id)
231
+
232
+ out_path.write_text(json.dumps(articles, default=str), encoding="utf-8")
233
+ return len(articles)
234
+
235
+
236
+ async def _run_part_b(scenarios_dir: Path) -> None:
237
+ """Async per-scenario news collection."""
238
+ # Load scenarios
239
+ benchmark_dir = config.get_benchmark_dir()
240
+ scenarios_path = benchmark_dir / "scenarios.parquet"
241
+ if not scenarios_path.exists():
242
+ logger.warning("scenarios.parquet not found at %s — skipping Part B", scenarios_path)
243
+ return
244
+
245
+ scenarios_df = pd.read_parquet(scenarios_path)
246
+ scenarios = scenarios_df.to_dict("records")
247
+ logger.info("Part B: collecting scenario news for %d events …", len(scenarios))
248
+
249
+ # Init clients
250
+ firecrawl_api_key = os.environ.get("FIRECRAWL_API_KEY", "")
251
+ tavily_api_key = os.environ.get("TAVILY_API_KEY", "")
252
+
253
+ from projects.tools.web.firecrawl_search import FirecrawlClient
254
+ from projects.tools.web.tavily_search import TavilyClient
255
+
256
+ fc_client = FirecrawlClient(api_key=firecrawl_api_key) if firecrawl_api_key else None
257
+ tv_client = TavilyClient(api_key=tavily_api_key) if tavily_api_key else None
258
+
259
+ if fc_client is None and tv_client is None:
260
+ logger.error("Neither FIRECRAWL_API_KEY nor TAVILY_API_KEY set — skipping Part B")
261
+ return
262
+
263
+ total = 0
264
+ for i, sc in enumerate(scenarios):
265
+ if fc_client is not None:
266
+ n = await _collect_single_scenario_news(sc, scenarios_dir, fc_client, tv_client)
267
+ elif tv_client is not None:
268
+ n = await _collect_single_scenario_news(sc, scenarios_dir, None, tv_client)
269
+ else:
270
+ n = 0
271
+ total += n
272
+ await asyncio.sleep(config.NEWS_RATE_LIMIT_SEC)
273
+ if (i + 1) % 10 == 0:
274
+ logger.info(" Part B progress: %d / %d scenarios", i + 1, len(scenarios))
275
+
276
+ logger.info("Part B complete: %d articles across %d scenarios", total, len(scenarios))
277
+
278
+
279
+ # ---------------------------------------------------------------------------
280
+ # Public entry points
281
+ # ---------------------------------------------------------------------------
282
+
283
+ async def run_async(tickers: list[str] | None = None) -> None:
284
+ """Run both Part A and Part B news collection.
285
+
286
+ Parameters
287
+ ----------
288
+ tickers : list[str] | None
289
+ Ticker symbols for Part A. If None, reads from universe CSV.
290
+ """
291
+ tickers_dir, scenarios_dir = _ensure_dirs()
292
+
293
+ # Resolve tickers
294
+ if tickers is None:
295
+ universe_path = config.UNIVERSE_DIR / "benchmark_universe.csv"
296
+ if universe_path.exists():
297
+ tickers = pd.read_csv(universe_path)["ticker"].tolist()
298
+ else:
299
+ logger.error("No tickers provided and universe CSV not found")
300
+ return
301
+
302
+ # Part A: synchronous (uses ThreadPoolExecutor internally)
303
+ _run_part_a(tickers, tickers_dir)
304
+
305
+ # Part B: async
306
+ await _run_part_b(scenarios_dir)
307
+
308
+ logger.info("News collection complete.")
code/collect_prices.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 3: Collect daily stock prices (OHLCV + Adj Close).
2
+
3
+ Downloads daily OHLCV data for the full ticker universe using
4
+ yf.download() in batches of PRICE_BATCH_SIZE.
5
+
6
+ Uses ``auto_adjust=False`` to preserve the ``Adj Close`` column,
7
+ which is required for the shares_outstanding derivation in Layer 2.
8
+
9
+ Includes retry with backoff for rate-limited batches, per-batch
10
+ checkpointing (so crashes don't lose all progress), and filters out
11
+ tickers/rows where ``Close`` is entirely NaN (junk/delisted symbols).
12
+
13
+ Output: data/prices/daily_prices.csv
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ import os
20
+ import tempfile
21
+ import time
22
+
23
+ import pandas as pd
24
+ import yfinance as yf
25
+
26
+ from . import config
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ MAX_BATCH_RETRIES = 3
31
+
32
+
33
+ def _download_batch_with_retry(
34
+ batch: list[str],
35
+ start: str,
36
+ end: str,
37
+ retries: int = MAX_BATCH_RETRIES,
38
+ ) -> pd.DataFrame | None:
39
+ """Download a batch of tickers with retry on rate-limit errors."""
40
+ for attempt in range(retries):
41
+ try:
42
+ df = yf.download(
43
+ batch,
44
+ start=start,
45
+ end=end,
46
+ group_by="ticker",
47
+ auto_adjust=False,
48
+ threads=True,
49
+ )
50
+ if df is not None and not df.empty:
51
+ return df
52
+ return None
53
+ except Exception as exc:
54
+ err_str = str(exc)
55
+ if "Too Many Requests" in err_str or "Rate" in err_str:
56
+ wait = 2 ** attempt * 5 # 5s, 10s, 20s
57
+ logger.warning("Batch rate-limited (attempt %d/%d), waiting %ds ...",
58
+ attempt + 1, retries, wait)
59
+ time.sleep(wait)
60
+ continue
61
+ logger.warning("Batch download failed: %s", exc)
62
+ return None
63
+ logger.warning("Batch exhausted %d retries.", retries)
64
+ return None
65
+
66
+
67
+ def _reshape_batch(raw: pd.DataFrame, batch: list[str]) -> pd.DataFrame:
68
+ """Reshape a yfinance MultiIndex batch to long format."""
69
+ records = []
70
+ if isinstance(raw.columns, pd.MultiIndex):
71
+ for ticker in raw.columns.get_level_values(0).unique():
72
+ try:
73
+ sub = raw[ticker].copy()
74
+ sub = sub.reset_index()
75
+ sub["Ticker"] = ticker
76
+ records.append(sub)
77
+ except Exception as exc:
78
+ logger.warning("Could not reshape ticker %s: %s", ticker, exc)
79
+ continue
80
+ else:
81
+ # Single ticker case
82
+ raw = raw.reset_index()
83
+ raw["Ticker"] = batch[0] if len(batch) == 1 else "UNKNOWN"
84
+ records.append(raw)
85
+
86
+ if not records:
87
+ return pd.DataFrame()
88
+ return pd.concat(records, ignore_index=True)
89
+
90
+
91
+ def _atomic_csv_write(df: pd.DataFrame, dest) -> None:
92
+ """Write CSV atomically via temp file + rename."""
93
+ dest_parent = dest.parent if hasattr(dest, "parent") else os.path.dirname(dest)
94
+ fd, tmp_path = tempfile.mkstemp(suffix=".csv", dir=dest_parent)
95
+ try:
96
+ os.close(fd)
97
+ df.to_csv(tmp_path, index=False)
98
+ os.replace(tmp_path, str(dest))
99
+ except BaseException:
100
+ try:
101
+ os.unlink(tmp_path)
102
+ except OSError:
103
+ pass
104
+ raise
105
+
106
+
107
+ def run(tickers: list[str] | None = None) -> pd.DataFrame:
108
+ """Execute Step 3 and return the daily prices DataFrame."""
109
+ config.PRICES_DIR.mkdir(parents=True, exist_ok=True)
110
+ out_path = config.PRICES_DIR / "daily_prices.csv"
111
+ checkpoint_path = config.PRICES_DIR / "_prices_checkpoint.csv"
112
+
113
+ if out_path.exists():
114
+ logger.info("Daily prices file already exists at %s, loading.", out_path)
115
+ return pd.read_csv(out_path, parse_dates=["Date"])
116
+
117
+ if tickers is None:
118
+ universe_path = config.UNIVERSE_DIR / "benchmark_universe.csv"
119
+ if not universe_path.exists():
120
+ raise FileNotFoundError(f"Run Step 1 first: {universe_path}")
121
+ tickers = pd.read_csv(universe_path)["ticker"].tolist()
122
+
123
+ # Resume from checkpoint if it exists
124
+ existing = pd.DataFrame()
125
+ already_done: set[str] = set()
126
+ if checkpoint_path.exists():
127
+ try:
128
+ existing = pd.read_csv(checkpoint_path)
129
+ already_done = set(existing["Ticker"].unique())
130
+ logger.info("Resuming from checkpoint: %d tickers already downloaded.", len(already_done))
131
+ except Exception:
132
+ logger.warning("Checkpoint file corrupt, starting fresh.")
133
+ existing = pd.DataFrame()
134
+
135
+ remaining = [t for t in tickers if t not in already_done]
136
+ logger.info("Downloading daily prices for %d tickers (%d already done) ...",
137
+ len(remaining), len(already_done))
138
+
139
+ batch_size = config.PRICE_BATCH_SIZE
140
+ batches_since_checkpoint = 0
141
+
142
+ for i in range(0, len(remaining), batch_size):
143
+ batch = remaining[i : i + batch_size]
144
+ logger.info("Downloading batch %d-%d / %d remaining", i, i + len(batch), len(remaining))
145
+ raw = _download_batch_with_retry(batch, config.START_DATE, config.END_DATE)
146
+ if raw is not None:
147
+ reshaped = _reshape_batch(raw, batch)
148
+ if not reshaped.empty:
149
+ existing = pd.concat([existing, reshaped], ignore_index=True)
150
+ batches_since_checkpoint += 1
151
+
152
+ # Checkpoint every 5 batches (~250 tickers)
153
+ if batches_since_checkpoint >= 5 and not existing.empty:
154
+ _atomic_csv_write(existing, checkpoint_path)
155
+ batches_since_checkpoint = 0
156
+ logger.info(" Checkpoint saved (%d rows, %d tickers).",
157
+ len(existing), existing["Ticker"].nunique())
158
+
159
+ if existing.empty:
160
+ logger.warning("No price data downloaded.")
161
+ return pd.DataFrame()
162
+
163
+ # Standardize column names
164
+ col_map = {c: c.strip() for c in existing.columns}
165
+ result = existing.rename(columns=col_map)
166
+
167
+ # Filter out rows where Close is NaN (junk/delisted tickers, pre-listing dates)
168
+ before_len = len(result)
169
+ result = result.dropna(subset=["Close"])
170
+ dropped = before_len - len(result)
171
+ if dropped > 0:
172
+ logger.info("Filtered %d rows with NaN Close (kept %d).", dropped, len(result))
173
+
174
+ # Report tickers with zero valid rows
175
+ valid_tickers = result["Ticker"].nunique()
176
+ all_tickers_set = set(tickers)
177
+ tickers_in_result = set(result["Ticker"].unique())
178
+ missing = all_tickers_set - tickers_in_result
179
+ if missing:
180
+ logger.info("%d tickers had no valid price data: %s",
181
+ len(missing), sorted(missing))
182
+
183
+ _atomic_csv_write(result, out_path)
184
+ logger.info("Saved daily prices (%d rows, %d tickers) to %s",
185
+ len(result), valid_tickers, out_path)
186
+
187
+ # Clean up checkpoint
188
+ if checkpoint_path.exists():
189
+ checkpoint_path.unlink()
190
+
191
+ return result
code/collect_real_estate.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 6: Collect multifamily real estate with logical locations.
2
+
3
+ Uses:
4
+ - RentCastPropertiesClient from projects.tools.property_market.rentcast
5
+ .get_properties_by_address() -- property records
6
+ .get_rental_listings_by_address() -- rental listings
7
+ .get_sale_listings_by_address() -- sale listings
8
+ .export_records() -- CSV export
9
+ - EsriAPIClient from projects.tools.property_market.esri_package.esri_package.esri
10
+ .get_processed_demographic_info() -- demographics per metro
11
+
12
+ Includes resume checks (skip if output CSVs exist) and retry with
13
+ exponential backoff for transient RentCast API failures.
14
+
15
+ Output:
16
+ data/real_estate/properties.csv
17
+ data/real_estate/rentals.csv
18
+ data/real_estate/sales.csv
19
+ data/real_estate/demographics.csv
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+ import logging
26
+ import os
27
+
28
+ import pandas as pd
29
+
30
+ from projects.tools.property_market.rentcast import RentCastPropertiesClient
31
+
32
+ from . import config
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ _MAX_RETRIES = 3
37
+
38
+
39
+ async def _retry_async(coro_factory, description: str, retries: int = _MAX_RETRIES):
40
+ """Call *coro_factory()* up to *retries* times with exponential backoff."""
41
+ for attempt in range(retries):
42
+ try:
43
+ return await coro_factory()
44
+ except Exception as exc:
45
+ if attempt < retries - 1:
46
+ wait = 2 ** attempt * 3 # 3s, 6s, 12s
47
+ logger.warning("%s failed (attempt %d/%d), retrying in %ds: %s",
48
+ description, attempt + 1, retries, wait, exc)
49
+ await asyncio.sleep(wait)
50
+ else:
51
+ raise
52
+
53
+
54
+ async def _collect_rentcast(client: RentCastPropertiesClient) -> None:
55
+ """Fetch properties, rental listings, and sale listings for every metro."""
56
+ re_dir = config.REAL_ESTATE_DIR
57
+ re_dir.mkdir(parents=True, exist_ok=True)
58
+
59
+ # Resume check: skip if all three output CSVs already exist
60
+ props_path = re_dir / "properties.csv"
61
+ rentals_path = re_dir / "rentals.csv"
62
+ sales_path = re_dir / "sales.csv"
63
+ if props_path.exists() and rentals_path.exists() and sales_path.exists():
64
+ logger.info("RentCast data already exists (properties, rentals, sales), skipping.")
65
+ return
66
+
67
+ all_properties = []
68
+ all_rentals = []
69
+ all_sales = []
70
+
71
+ for metro_addr in config.METROS:
72
+ logger.info("RentCast: querying %s ...", metro_addr)
73
+ try:
74
+ props = await _retry_async(
75
+ lambda addr=metro_addr: client.get_properties_by_address(
76
+ address=addr,
77
+ property_types=config.RENTCAST_PROPERTY_TYPES, # type: ignore[arg-type]
78
+ radius=config.RENTCAST_RADIUS_MILES,
79
+ auto_paginate=False,
80
+ limit=config.RENTCAST_MAX_RESULTS,
81
+ ),
82
+ description=f"RentCast properties {metro_addr}",
83
+ )
84
+ all_properties.extend(props)
85
+ logger.info(" properties: %d", len(props))
86
+ except Exception as exc:
87
+ logger.warning(" properties failed for %s after retries: %s", metro_addr, exc)
88
+
89
+ try:
90
+ rentals = await _retry_async(
91
+ lambda addr=metro_addr: client.get_rental_listings_by_address(
92
+ address=addr,
93
+ property_types=config.RENTCAST_PROPERTY_TYPES, # type: ignore[arg-type]
94
+ radius=config.RENTCAST_RADIUS_MILES,
95
+ auto_paginate=False,
96
+ limit=config.RENTCAST_MAX_RESULTS,
97
+ ),
98
+ description=f"RentCast rentals {metro_addr}",
99
+ )
100
+ all_rentals.extend(rentals)
101
+ logger.info(" rental listings: %d", len(rentals))
102
+ except Exception as exc:
103
+ logger.warning(" rentals failed for %s after retries: %s", metro_addr, exc)
104
+
105
+ try:
106
+ sales = await _retry_async(
107
+ lambda addr=metro_addr: client.get_sale_listings_by_address(
108
+ address=addr,
109
+ property_types=config.RENTCAST_PROPERTY_TYPES, # type: ignore[arg-type]
110
+ radius=config.RENTCAST_RADIUS_MILES,
111
+ auto_paginate=False,
112
+ limit=config.RENTCAST_MAX_RESULTS,
113
+ ),
114
+ description=f"RentCast sales {metro_addr}",
115
+ )
116
+ all_sales.extend(sales)
117
+ logger.info(" sale listings: %d", len(sales))
118
+ except Exception as exc:
119
+ logger.warning(" sales failed for %s after retries: %s", metro_addr, exc)
120
+
121
+ # Brief pause between metros to be polite to the API
122
+ await asyncio.sleep(0.5)
123
+
124
+ # Write each file individually so partial success is preserved
125
+ if all_properties:
126
+ client.export_records(all_properties, props_path)
127
+ logger.info("Saved %d property records.", len(all_properties))
128
+ if all_rentals:
129
+ client.export_records(all_rentals, rentals_path)
130
+ logger.info("Saved %d rental listings.", len(all_rentals))
131
+ if all_sales:
132
+ client.export_records(all_sales, sales_path)
133
+ logger.info("Saved %d sale listings.", len(all_sales))
134
+
135
+ # Write a done marker so we know all 3 were attempted
136
+ done_marker = re_dir / ".rentcast_done"
137
+ done_marker.write_text("done")
138
+
139
+
140
+ async def _collect_demographics(client) -> None:
141
+ """Fetch ESRI demographic data for each metro to make locations 'logical'."""
142
+ re_dir = config.REAL_ESTATE_DIR
143
+ demo_path = re_dir / "demographics.csv"
144
+ if demo_path.exists():
145
+ logger.info("Demographics file already exists, skipping.")
146
+ return
147
+
148
+ rows = []
149
+ for metro_addr in config.METROS:
150
+ logger.info("ESRI demographics: %s ...", metro_addr)
151
+ try:
152
+ info = await _retry_async(
153
+ lambda addr=metro_addr: client.get_processed_demographic_info(addr),
154
+ description=f"ESRI demographics {metro_addr}",
155
+ )
156
+ rows.append(info.model_dump())
157
+ except Exception as exc:
158
+ logger.warning(" demographics failed for %s after retries: %s", metro_addr, exc)
159
+
160
+ if rows:
161
+ df = pd.DataFrame(rows)
162
+ df.to_csv(demo_path, index=False)
163
+ logger.info("Saved demographics (%d metros).", len(df))
164
+
165
+
166
+ async def run_async() -> None:
167
+ """Execute Step 6 (async)."""
168
+ rentcast_key = os.getenv("RENTCAST_API_KEY")
169
+ if not rentcast_key:
170
+ raise ValueError("Set RENTCAST_API_KEY environment variable.")
171
+
172
+ rentcast_client = RentCastPropertiesClient(api_key=rentcast_key)
173
+ await _collect_rentcast(rentcast_client)
174
+
175
+ # Demographics via ESRI (requires arcgis package -- skip if unavailable)
176
+ esri_user = os.getenv("ARCGIS_USERNAME")
177
+ esri_pass = os.getenv("ARCGIS_PASSWORD")
178
+ if not esri_user or not esri_pass:
179
+ logger.warning("ARCGIS_USERNAME / ARCGIS_PASSWORD not set, skipping demographics.")
180
+ else:
181
+ try:
182
+ from projects.tools.property_market.esri_package.esri_package.esri import EsriAPIClient
183
+ esri_client = EsriAPIClient(username=esri_user, password=esri_pass)
184
+ await _collect_demographics(esri_client)
185
+ except ImportError:
186
+ logger.warning("arcgis package not installed, skipping demographics collection.")
187
+
188
+ logger.info("Real estate data collection complete.")
189
+
190
+
191
+ def run() -> None:
192
+ """Sync wrapper around the async implementation."""
193
+ asyncio.run(run_async())
code/collect_universe.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 1: Collect the small-cap ticker universe.
2
+
3
+ Universe definition: union of small-cap-and-below tickers from major
4
+ S&P/Russell/iShares ETFs:
5
+
6
+ - IWM: iShares Russell 2000 ETF (Russell 2000 small-caps)
7
+ - IJR: iShares Core S&P SmallCap ETF (S&P 600 small-caps)
8
+ - IWC: iShares Micro-Cap ETF (micro-caps below small-cap threshold)
9
+
10
+ Tickers exceeding the S&P 600 upper bound ($7.4B median market cap) are
11
+ filtered out downstream in preprocess.py via SMALL_CAP_MAX_MEDIAN_MCAP.
12
+ We do NOT filter on ETF holding value here because it does not correlate
13
+ with actual company market cap (mega-caps may have small ETF positions).
14
+
15
+ This satisfies Prof. Hwang's Requirement 1.1: "Collect R2K + small caps".
16
+
17
+ - Uses iShares CSV data directly for market value, sector, exchange.
18
+ - Normalises multi-class share tickers (e.g. BFA -> BF-A) so yfinance can find them.
19
+ - Removes duplicates, zero-price entries, and non-equity rows.
20
+
21
+ Output: data/universe/benchmark_universe.csv
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import io
27
+ import logging
28
+ import math
29
+ import os
30
+ import tempfile
31
+ import time
32
+
33
+ import httpx
34
+ import pandas as pd
35
+
36
+ from . import config
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ _MAX_HTTP_RETRIES = 3
41
+
42
+ # Sanity bounds for company market cap (USD).
43
+ # Anything outside this range is treated as an invalid lookup.
44
+ _MCAP_MIN_VALID = 1.0e5 # $100k — below this is almost certainly bad data
45
+ _MCAP_MAX_VALID = 1.0e13 # $10T — above this is impossible
46
+
47
+ # yfinance lookup pacing — pure serial.
48
+ #
49
+ # Empirically, ANY parallelism (even 4 workers × 0.3s delay = ~5 req/s)
50
+ # triggers Yahoo's per-IP rate limit on runs of >2000 tickers, dropping
51
+ # coverage to ~60%. Pure serial at ~3 req/s stays under the threshold and
52
+ # achieves ~99% coverage. For ~5,345 tickers this takes ~27 minutes — that
53
+ # is the minimum reliable wall time for this dataset size.
54
+ _MCAP_LOOKUP_DELAY_SEC = 0.3
55
+
56
+ # iShares strips the dash from multi-class share tickers.
57
+ # This map restores the yfinance-compatible format.
58
+ _CLASS_SHARE_FIXES: dict[str, str] = {
59
+ "BFA": "BF-A",
60
+ "BFB": "BF-B",
61
+ "BRKB": "BRK-B",
62
+ "LENB": "LEN-B",
63
+ "MOGA": "MOG-A",
64
+ "MOGB": "MOG-B",
65
+ "GEFB": "GEF-B",
66
+ "CWENA": "CWEN-A",
67
+ "UHALB": "UHAL-B",
68
+ "CRDA": "CRD-A", # Crawford & Co Class A — non-voting
69
+ "CRDB": "CRD-B", # Crawford & Co Class B — voting
70
+ }
71
+
72
+ # NASDAQ Trader public symbol directory — authoritative source for ALL
73
+ # US-listed common equities (NASDAQ + NYSE + NYSE Mkt + AMEX). Used to
74
+ # populate Prof. Hwang's third universe component: small caps that are
75
+ # NOT in any major index (recent IPOs, between-rebalance additions,
76
+ # dropped-from-index small caps still trading).
77
+ _NASDAQ_LISTED_URL = "https://www.nasdaqtrader.com/dynamic/symdir/nasdaqlisted.txt"
78
+ _OTHER_LISTED_URL = "https://www.nasdaqtrader.com/dynamic/symdir/otherlisted.txt"
79
+
80
+
81
+ def _download_ishares_holdings(url: str) -> pd.DataFrame:
82
+ """Download iShares ETF holdings CSV and return a cleaned DataFrame."""
83
+ for attempt in range(_MAX_HTTP_RETRIES):
84
+ try:
85
+ resp = httpx.get(url, follow_redirects=True, timeout=60)
86
+ resp.raise_for_status()
87
+ break
88
+ except Exception as exc:
89
+ if attempt < _MAX_HTTP_RETRIES - 1:
90
+ wait = 2 ** attempt * 5
91
+ logger.warning("iShares download failed (attempt %d/%d), retrying in %ds: %s",
92
+ attempt + 1, _MAX_HTTP_RETRIES, wait, exc)
93
+ time.sleep(wait)
94
+ else:
95
+ raise
96
+ text = resp.text
97
+
98
+ # iShares CSVs have metadata rows before the actual header.
99
+ lines = text.splitlines()
100
+ header_idx = 0
101
+ for i, line in enumerate(lines):
102
+ if line.strip().lower().startswith("ticker"):
103
+ header_idx = i
104
+ break
105
+
106
+ csv_text = "\n".join(lines[header_idx:])
107
+ df = pd.read_csv(io.StringIO(csv_text))
108
+ df.columns = [c.strip() for c in df.columns]
109
+ if "Ticker" in df.columns:
110
+ df = df[df["Ticker"].notna() & (df["Ticker"].str.strip() != "-") & (df["Ticker"].str.strip() != "")]
111
+ df["Ticker"] = df["Ticker"].str.strip().str.upper()
112
+ # Filter out junk rows (e.g. iShares copyright disclaimers parsed as tickers)
113
+ df = df[df["Ticker"].str.len() <= 10]
114
+ # Keep only equity instruments (remove futures, cash, CVRs, etc.)
115
+ if "Asset Class" in df.columns:
116
+ before = len(df)
117
+ df = df[df["Asset Class"].str.strip().str.lower() == "equity"]
118
+ dropped = before - len(df)
119
+ if dropped > 0:
120
+ logger.info("Filtered %d non-equity entries (kept %d equities).", dropped, len(df))
121
+ # Remove zero-price entries (CVRs, escrows, delisted, private vestings
122
+ # that iShares mislabels as Equity)
123
+ if "Price" in df.columns:
124
+ price_num = pd.to_numeric(df["Price"].astype(str).str.replace(",", ""), errors="coerce")
125
+ before = len(df)
126
+ df = df[price_num > 0]
127
+ dropped = before - len(df)
128
+ if dropped > 0:
129
+ logger.info("Filtered %d zero-price entries (CVRs/escrows/delisted).", dropped)
130
+ return df
131
+
132
+
133
+ def _download_nasdaq_trader(url: str) -> pd.DataFrame:
134
+ """Download a pipe-delimited NASDAQ Trader symbol directory file.
135
+
136
+ Both nasdaqlisted.txt and otherlisted.txt share the same format:
137
+ pipe-delimited, one header row, last line is a 'File Creation Time'
138
+ footer that must be skipped.
139
+ """
140
+ for attempt in range(_MAX_HTTP_RETRIES):
141
+ try:
142
+ resp = httpx.get(url, follow_redirects=True, timeout=60)
143
+ resp.raise_for_status()
144
+ break
145
+ except Exception as exc:
146
+ if attempt < _MAX_HTTP_RETRIES - 1:
147
+ wait = 2 ** attempt * 5
148
+ logger.warning("NASDAQ Trader download failed (attempt %d/%d), retrying in %ds: %s",
149
+ attempt + 1, _MAX_HTTP_RETRIES, wait, exc)
150
+ time.sleep(wait)
151
+ else:
152
+ raise
153
+ text = resp.text
154
+
155
+ # Drop the trailing "File Creation Time" footer line
156
+ lines = [ln for ln in text.splitlines() if ln and not ln.startswith("File Creation Time")]
157
+ df = pd.read_csv(io.StringIO("\n".join(lines)), sep="|")
158
+ df.columns = [c.strip() for c in df.columns]
159
+ return df
160
+
161
+
162
+ def _collect_uncovered_smallcaps(already_seen: set[str]) -> list[dict]:
163
+ """Return candidate records for Prof. Hwang's third universe component:
164
+ small caps listed on NYSE/NASDAQ that are NOT in any major index
165
+ (specifically not in the IWM/IJR/IWC ETF holdings already collected).
166
+
167
+ Each record is a dict with keys: ticker, exchange, name. The exchange
168
+ and security name come directly from the NASDAQ Trader symbol directory
169
+ files (no extra API calls). Sector is filled later by collect_fundamentals.
170
+
171
+ The mcap filter (≤ $7.4B) is applied later in run() via the same serial
172
+ yfinance lookup pass; this function only produces the candidate set.
173
+
174
+ Filtering rules:
175
+ - Drop ETFs (ETF=Y in nasdaqlisted.txt)
176
+ - Drop test issues (Test Issue=Y)
177
+ - Drop tickers already in IWM/IJR/IWC (passed via `already_seen`)
178
+ - Drop preferreds (containing '$' or '.' which mark preferred classes)
179
+ - Drop warrants and units (suffix W/U/R on a 5-char base)
180
+ - Keep only common stock (Common Stock / Common Shares in security name)
181
+ """
182
+ logger.info("Downloading NASDAQ Trader symbol directories ...")
183
+ nas = _download_nasdaq_trader(_NASDAQ_LISTED_URL)
184
+ oth = _download_nasdaq_trader(_OTHER_LISTED_URL)
185
+ logger.info("nasdaqlisted: %d rows, otherlisted: %d rows", len(nas), len(oth))
186
+
187
+ candidates: list[tuple[str, str, str]] = [] # (ticker, exchange_code, security_name)
188
+
189
+ # ── nasdaqlisted.txt fields: Symbol|Security Name|Market Category|Test Issue|Financial Status|Round Lot Size|ETF|NextShares
190
+ if not nas.empty:
191
+ nas = nas[nas["Test Issue"].astype(str).str.upper() != "Y"]
192
+ nas = nas[nas["ETF"].astype(str).str.upper() != "Y"]
193
+ for _, row in nas.iterrows():
194
+ sym = str(row.get("Symbol", "")).strip().upper()
195
+ sec_name = str(row.get("Security Name", ""))
196
+ if not sym or sym == "NAN":
197
+ continue
198
+ candidates.append((sym, "NASDAQ", sec_name))
199
+
200
+ # ── otherlisted.txt fields: ACT Symbol|Security Name|Exchange|CQS Symbol|ETF|Round Lot Size|Test Issue|NASDAQ Symbol
201
+ # Exchange codes: A=NYSE Mkt (AMEX), N=NYSE, P=NYSE Arca, Z=BATS, V=IEX
202
+ if not oth.empty:
203
+ oth = oth[oth["Test Issue"].astype(str).str.upper() != "Y"]
204
+ oth = oth[oth["ETF"].astype(str).str.upper() != "Y"]
205
+ # Keep only NYSE-family exchanges
206
+ oth = oth[oth["Exchange"].astype(str).str.upper().isin(["N", "A"])]
207
+ for _, row in oth.iterrows():
208
+ sym = str(row.get("ACT Symbol", "")).strip().upper()
209
+ sec_name = str(row.get("Security Name", ""))
210
+ exch = "NYSE" if row.get("Exchange") == "N" else "NYSE_MKT"
211
+ if not sym or sym == "NAN":
212
+ continue
213
+ candidates.append((sym, exch, sec_name))
214
+
215
+ # Filter to common stock only (drop preferreds, warrants, units, notes,
216
+ # rights, depositary shares, etc.). Use security name keyword whitelist
217
+ # — most US-listed equities have "Common Stock" or "Common Shares".
218
+ common_kws = ("common stock", "common share", "ordinary share", "class a common",
219
+ "class b common", "class c common")
220
+ drop_kws = ("preferred", "warrant", "unit ", " unit", "% notes", "depositary",
221
+ "right ", " rights", "subordinate", "convertible", "trust preferred",
222
+ "% senior", "debenture", " etn ", "exchange-traded note")
223
+
224
+ # Build per-ticker dict (dedupe by ticker, prefer first occurrence)
225
+ by_ticker: dict[str, dict] = {}
226
+ for sym, exch, sec_name in candidates:
227
+ sn_low = sec_name.lower()
228
+ if any(k in sn_low for k in drop_kws):
229
+ continue
230
+ if not any(k in sn_low for k in common_kws):
231
+ continue
232
+ # Drop ticker symbols that look like preferred/warrant variants:
233
+ # tickers containing $ or . (preferred class markers like BAC.PA),
234
+ # 5-char tickers ending in W (warrant), U (unit), R (rights).
235
+ if "$" in sym or "." in sym:
236
+ continue
237
+ if len(sym) >= 5 and sym.endswith(("W", "U", "R")):
238
+ continue
239
+ if sym in by_ticker:
240
+ continue # first occurrence wins
241
+ # Strip the " - Common Stock" suffix from the security name for cleaner display
242
+ clean_name = sec_name
243
+ for suffix in (" - Common Stock", " - Common Shares", " - Class A Common Stock",
244
+ " - Class B Common Stock", " - Class C Common Stock"):
245
+ if clean_name.endswith(suffix):
246
+ clean_name = clean_name[: -len(suffix)]
247
+ break
248
+ by_ticker[sym] = {
249
+ "ticker": sym,
250
+ "exchange": exch,
251
+ "name": clean_name.strip(),
252
+ }
253
+
254
+ # Subtract already-known tickers (those in IWM/IJR/IWC)
255
+ new_records = [r for sym, r in sorted(by_ticker.items()) if sym not in already_seen]
256
+ overlap = sum(1 for sym in by_ticker if sym in already_seen)
257
+ logger.info("NASDAQ Trader common-stock candidates: %d (after subtracting "
258
+ "%d already-known tickers: %d)", len(by_ticker), overlap, len(new_records))
259
+ return new_records
260
+
261
+
262
+ def _fetch_one_market_cap(ticker: str) -> float | None:
263
+ """Fetch a single ticker's company market cap from yfinance.
264
+
265
+ Uses ONLY `fast_info.market_cap` — a single fast network call. The
266
+ deliberately simple approach avoids the multi-fallback hangs that
267
+ occur when `tk.info` blocks for 30+ seconds on rate limits or bad
268
+ tickers. Tickers where fast_info fails are returned as None and
269
+ dropped from the universe per Option A (a small-cap benchmark
270
+ cannot include a ticker without a verified market cap).
271
+
272
+ Returns a float USD value in [_MCAP_MIN_VALID, _MCAP_MAX_VALID]
273
+ or None on any failure.
274
+ """
275
+ import yfinance as yf # local import — yfinance is heavy
276
+
277
+ try:
278
+ mc = yf.Ticker(ticker).fast_info.market_cap
279
+ except Exception:
280
+ return None
281
+ try:
282
+ mcf = float(mc)
283
+ except (TypeError, ValueError):
284
+ return None
285
+ if not math.isfinite(mcf):
286
+ return None
287
+ if not (_MCAP_MIN_VALID <= mcf <= _MCAP_MAX_VALID):
288
+ return None
289
+ return mcf
290
+
291
+
292
+ def _serial_fetch_pass(tickers: list[str], pass_label: str) -> dict[str, float | None]:
293
+ """One serial pass over `tickers`. fast_info call + delay per ticker."""
294
+ results: dict[str, float | None] = {}
295
+ total = len(tickers)
296
+ if total == 0:
297
+ return results
298
+ logger.info("%s: %d tickers, serial, %.2fs delay ...",
299
+ pass_label, total, _MCAP_LOOKUP_DELAY_SEC)
300
+ t0 = time.time()
301
+ for i, t in enumerate(tickers, start=1):
302
+ results[t] = _fetch_one_market_cap(t)
303
+ time.sleep(_MCAP_LOOKUP_DELAY_SEC)
304
+ if i % 200 == 0 or i == total:
305
+ elapsed = time.time() - t0
306
+ ok = sum(1 for v in results.values() if v is not None)
307
+ rate = i / elapsed if elapsed > 0 else 0
308
+ eta = (total - i) / rate if rate > 0 else 0
309
+ logger.info(" %s progress: %d/%d (ok=%d) — %.0fs elapsed, ETA %.0fs",
310
+ pass_label, i, total, ok, elapsed, eta)
311
+ return results
312
+
313
+
314
+ def _fetch_market_caps(tickers: list[str]) -> dict[str, float | None]:
315
+ """Fetch market caps via two serial passes for maximum coverage.
316
+
317
+ Pass 1: serial fast_info call for every ticker (~3 req/s, no rate limit).
318
+ Pass 2: serial retry of any tickers that returned None in pass 1 (catches
319
+ transient errors; permanent no-data tickers will fail again and
320
+ be dropped per Option A).
321
+
322
+ Pure serial avoids the per-IP rate limit that even 4 workers triggered.
323
+ Expected wall time for ~5,345 tickers: ~27 min pass 1 + ~3 min pass 2.
324
+ """
325
+ t0 = time.time()
326
+
327
+ # ── Pass 1: serial over all tickers ──
328
+ results = _serial_fetch_pass(tickers, pass_label="Pass 1")
329
+ pass1_ok = sum(1 for v in results.values() if v is not None)
330
+ logger.info("Pass 1 complete: %d/%d resolved in %.0fs",
331
+ pass1_ok, len(tickers), time.time() - t0)
332
+
333
+ # ── Pass 2: serial retry of pass-1 failures ──
334
+ failed = [t for t in tickers if results.get(t) is None]
335
+ if failed:
336
+ retry_results = _serial_fetch_pass(failed, pass_label="Pass 2 (retry)")
337
+ recovered = 0
338
+ for t, mc in retry_results.items():
339
+ if mc is not None:
340
+ results[t] = mc
341
+ recovered += 1
342
+ logger.info("Pass 2 complete: recovered %d/%d failures",
343
+ recovered, len(failed))
344
+
345
+ final_ok = sum(1 for v in results.values() if v is not None)
346
+ logger.info("Total market_cap coverage: %d/%d (%.1f%%) in %.0fs",
347
+ final_ok, len(tickers), 100 * final_ok / len(tickers),
348
+ time.time() - t0)
349
+ return results
350
+
351
+
352
+ def run() -> pd.DataFrame:
353
+ """Execute Step 1 and return the universe DataFrame."""
354
+ config.UNIVERSE_DIR.mkdir(parents=True, exist_ok=True)
355
+ out_path = config.UNIVERSE_DIR / "benchmark_universe.csv"
356
+
357
+ if out_path.exists():
358
+ logger.info("Universe file already exists at %s, loading.", out_path)
359
+ return pd.read_csv(out_path)
360
+
361
+ def _records_from_ishares(holdings_df: pd.DataFrame, source: str) -> list[dict]:
362
+ records = []
363
+ for _, row in holdings_df.iterrows():
364
+ ticker = row["Ticker"]
365
+ mv_str = str(row.get("Market Value", "")).replace(",", "")
366
+ try:
367
+ market_value = float(mv_str)
368
+ except (ValueError, TypeError):
369
+ market_value = None
370
+ records.append({
371
+ "ticker": ticker,
372
+ "market_value": market_value,
373
+ "sector": row.get("Sector"),
374
+ "exchange": row.get("Exchange"),
375
+ "name": row.get("Name"),
376
+ "source": source,
377
+ })
378
+ return records
379
+
380
+ # ----- Russell 2000 from IWM -----
381
+ logger.info("Downloading IWM (Russell 2000) holdings ...")
382
+ iwm_df = _download_ishares_holdings(config.IWM_HOLDINGS_URL)
383
+ logger.info("IWM tickers: %d", len(iwm_df))
384
+ iwm_records = _records_from_ishares(iwm_df, source="IWM")
385
+ iwm_set = {r["ticker"] for r in iwm_records}
386
+
387
+ # ----- S&P SmallCap 600 from IJR -----
388
+ logger.info("Downloading IJR (S&P SmallCap 600) holdings ...")
389
+ ijr_df = _download_ishares_holdings(config.IJR_HOLDINGS_URL)
390
+ logger.info("IJR tickers: %d", len(ijr_df))
391
+ ijr_records = _records_from_ishares(ijr_df, source="IJR")
392
+ # Keep only IJR tickers not already in IWM
393
+ ijr_only = [r for r in ijr_records if r["ticker"] not in iwm_set]
394
+ logger.info("IJR-only tickers (not in IWM): %d", len(ijr_only))
395
+
396
+ # ----- Micro-cap from IWC -----
397
+ logger.info("Downloading IWC (Micro-Cap) holdings ...")
398
+ iwc_df = _download_ishares_holdings(config.IWC_HOLDINGS_URL)
399
+ iwc_records = _records_from_ishares(iwc_df, source="IWC")
400
+ seen = iwm_set | {r["ticker"] for r in ijr_only}
401
+ iwc_only = [r for r in iwc_records if r["ticker"] not in seen]
402
+ logger.info("IWC-only tickers (not in IWM or IJR): %d", len(iwc_only))
403
+
404
+ # ----- Uncovered NYSE/NASDAQ small caps (Prof. Hwang component 3) -----
405
+ # "those who are not even included in the index (small caps in NYSE or NASDAQ)"
406
+ # We pull the full NASDAQ Trader symbol directories, filter to common stock
407
+ # only, subtract everything already in IWM/IJR/IWC, and let the downstream
408
+ # mcap pass apply the $7.4B small-cap upper bound. The remainder is the
409
+ # set of small caps that are NOT in any major index (recent IPOs,
410
+ # between-rebalance additions, dropped-from-index small caps).
411
+ seen_for_uncovered = iwm_set | {r["ticker"] for r in ijr_only} | {r["ticker"] for r in iwc_only}
412
+ uncovered_seed = _collect_uncovered_smallcaps(seen_for_uncovered)
413
+ uncovered_records = [
414
+ {
415
+ "ticker": rec["ticker"],
416
+ "market_value": None, # iShares-only field; not applicable
417
+ "sector": None, # filled later by collect_fundamentals
418
+ "exchange": rec["exchange"], # populated from NASDAQ Trader directory
419
+ "name": rec["name"], # populated from NASDAQ Trader directory
420
+ "source": "UNCOVERED",
421
+ }
422
+ for rec in uncovered_seed
423
+ ]
424
+ logger.info("UNCOVERED small-cap candidates (pre-mcap-filter): %d", len(uncovered_records))
425
+
426
+ # Build the set of ALL S&P 600 tickers (BEFORE the IJR-only subtraction
427
+ # against IWM). This is what `in_sp_smallcap_600` should reflect: an
428
+ # IJR ticker is an S&P 600 small-cap regardless of whether it ALSO
429
+ # happens to appear in IWM (they overlap by hundreds of names). The
430
+ # earlier `source` column does NOT capture this -- a ticker in both
431
+ # IWM and IJR carries source='IWM', losing the SP600 attestation.
432
+ all_ijr_tickers = {r["ticker"] for r in ijr_records}
433
+
434
+ # Combine: IWM + IJR-only + IWC-only + UNCOVERED
435
+ all_records = []
436
+ for r in iwm_records:
437
+ all_records.append({
438
+ **r,
439
+ "in_russell_2000": True,
440
+ "in_sp_smallcap_600": r["ticker"] in all_ijr_tickers,
441
+ "small_cap_outside": False,
442
+ })
443
+ for r in ijr_only:
444
+ all_records.append({
445
+ **r,
446
+ "in_russell_2000": False,
447
+ "in_sp_smallcap_600": True,
448
+ "small_cap_outside": True,
449
+ })
450
+ for r in iwc_only:
451
+ all_records.append({
452
+ **r,
453
+ "in_russell_2000": False,
454
+ "in_sp_smallcap_600": False,
455
+ "small_cap_outside": True,
456
+ })
457
+ for r in uncovered_records:
458
+ all_records.append({
459
+ **r,
460
+ "in_russell_2000": False,
461
+ "in_sp_smallcap_600": False,
462
+ "small_cap_outside": True,
463
+ })
464
+
465
+ df = pd.DataFrame(all_records)
466
+ logger.info("Combined raw universe: %d tickers (IWM=%d, IJR-only=%d, IWC-only=%d, UNCOVERED=%d)",
467
+ len(df), len(iwm_records), len(ijr_only), len(iwc_only), len(uncovered_records))
468
+
469
+ # Normalise multi-class share tickers (iShares strips the dash)
470
+ fixed = 0
471
+ for old, new in _CLASS_SHARE_FIXES.items():
472
+ mask = df["ticker"] == old
473
+ if mask.any():
474
+ df.loc[mask, "ticker"] = new
475
+ fixed += mask.sum()
476
+ if fixed:
477
+ logger.info("Normalised %d multi-class share tickers (e.g. BFA -> BF-A).", fixed)
478
+
479
+ # Remove exact duplicates (same ticker appearing as CVR + regular stock)
480
+ before = len(df)
481
+ df = df.drop_duplicates(subset="ticker", keep="first")
482
+ dupes = before - len(df)
483
+ if dupes:
484
+ logger.info("Removed %d duplicate tickers.", dupes)
485
+
486
+ # ── Fetch authoritative company market cap from yfinance ──────────────
487
+ # NOTE: iShares "market_value" is the ETF's holding value, NOT the
488
+ # company's market cap. We fetch the real market cap here so the saved
489
+ # universe file is the authoritative small-cap set from the start.
490
+ #
491
+ # Every ticker in the saved file MUST have a verified market_cap, or it
492
+ # is dropped (cannot honestly be classified as small-cap without knowing).
493
+ tickers = df["ticker"].tolist()
494
+ mcap_map = _fetch_market_caps(tickers)
495
+ df["market_cap"] = df["ticker"].map(mcap_map)
496
+
497
+ # Drop tickers with no reliable market cap (delisted, SPAC residue, ADR glitches)
498
+ invalid_mask = df["market_cap"].isna()
499
+ invalid_tickers = sorted(df.loc[invalid_mask, "ticker"].tolist())
500
+ if invalid_tickers:
501
+ logger.warning("Dropped %d tickers with no valid market_cap (showing first 30): %s",
502
+ len(invalid_tickers), invalid_tickers[:30])
503
+ df = df.loc[~invalid_mask].copy()
504
+
505
+ # Drop mega-caps from IWC and UNCOVERED sources.
506
+ #
507
+ # IWM (Russell 2000) and IJR (S&P SmallCap 600) constituents are
508
+ # index-designated small-caps by FTSE Russell / S&P Dow Jones methodology
509
+ # — we respect those classifications and do NOT filter them by current
510
+ # market cap (a few names may have drifted above $7.4B since the last
511
+ # index reconstitution, but they remain index-designated small-caps).
512
+ #
513
+ # IWC has known mega-cap leakage (iShares holds tiny tracking positions
514
+ # in NVDA/AAPL/etc. for index-fit reasons) and must be filtered.
515
+ #
516
+ # UNCOVERED tickers have no index attestation at all and so require
517
+ # an explicit small-cap upper bound. The S&P 600 SmallCap upper bound
518
+ # ($7.4B) is the official threshold per S&P Dow Jones methodology.
519
+ needs_filter = df["source"].isin(["IWC", "UNCOVERED"])
520
+ mega_mask = needs_filter & (df["market_cap"] > config.SMALL_CAP_MAX_MEDIAN_MCAP)
521
+ mega_rows = df.loc[mega_mask, ["ticker", "source", "market_cap"]].sort_values(
522
+ "market_cap", ascending=False
523
+ )
524
+ if not mega_rows.empty:
525
+ logger.warning(
526
+ "Dropped %d mega-caps from IWC/UNCOVERED (market_cap > $%.1fB). First 30:\n%s",
527
+ len(mega_rows),
528
+ config.SMALL_CAP_MAX_MEDIAN_MCAP / 1e9,
529
+ mega_rows.head(30).to_string(index=False),
530
+ )
531
+ df = df.loc[~mega_mask].copy()
532
+
533
+ logger.info(
534
+ "Universe after market-cap filtering: %d tickers (max mcap=$%.2fB, median=$%.2fB)",
535
+ len(df),
536
+ df["market_cap"].max() / 1e9,
537
+ df["market_cap"].median() / 1e9,
538
+ )
539
+
540
+ # Apply MAX_TICKERS cap if set
541
+ if config.MAX_TICKERS is not None:
542
+ df = df.head(config.MAX_TICKERS)
543
+
544
+ # Label lower-end by market value percentile (within Russell 2000 subset)
545
+ r2k = df[df["in_russell_2000"] & df["market_value"].notna()]
546
+ if not r2k.empty:
547
+ threshold = r2k["market_value"].quantile(config.LOWER_END_PERCENTILE / 100.0)
548
+ df["lower_end_russell2000"] = df["in_russell_2000"] & (df["market_value"] <= threshold)
549
+ logger.info("Lower-end R2K threshold: market_value <= %.0f (%d tickers)",
550
+ threshold, df["lower_end_russell2000"].sum())
551
+ else:
552
+ df["lower_end_russell2000"] = False
553
+
554
+ df = df.sort_values("ticker").reset_index(drop=True)
555
+ # Atomic write: write to temp file first, then rename
556
+ fd, tmp_path = tempfile.mkstemp(suffix=".csv", dir=out_path.parent)
557
+ try:
558
+ os.close(fd)
559
+ df.to_csv(tmp_path, index=False)
560
+ os.replace(tmp_path, out_path)
561
+ except BaseException:
562
+ try:
563
+ os.unlink(tmp_path)
564
+ except OSError:
565
+ pass
566
+ raise
567
+ logger.info("Saved universe (%d tickers) to %s", len(df), out_path)
568
+ return df
code/config.py ADDED
@@ -0,0 +1,833 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Centralised configuration for the What-If Scenario Benchmark pipeline.
2
+
3
+ Every tunable parameter lives here so that notebooks and scripts have a
4
+ single source of truth.
5
+
6
+ Architecture:
7
+ Layer 1 (Raw Collection) -> data/{source}/
8
+ Layer 2 (Preprocessing) -> data/processed/{GRANULARITY}/
9
+ Layer 3 (Benchmark) -> data/benchmark/{GRANULARITY}/
10
+ """
11
+
12
+ from pathlib import Path
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Paths -- Layer 1 (raw data)
16
+ # ---------------------------------------------------------------------------
17
+ import os as _os
18
+
19
+ BASE_DIR = Path(__file__).resolve().parent
20
+ # Small-cap rebuild: all data lives under data_small_caps/ for the
21
+ # clean-slate small-cap-and-below universe rebuild (Apr 2026).
22
+ DATA_DIR = BASE_DIR / _os.environ.get("WHATIF_DATA_DIR", "data_small_caps")
23
+
24
+ UNIVERSE_DIR = DATA_DIR / "universe"
25
+ FUNDAMENTALS_DIR = DATA_DIR / "fundamentals"
26
+ PRICES_DIR = DATA_DIR / "prices"
27
+ FILINGS_DIR = DATA_DIR / "filings"
28
+ MACRO_DIR = DATA_DIR / "macro"
29
+ REAL_ESTATE_DIR = DATA_DIR / "real_estate"
30
+ NEWS_DIR = DATA_DIR / "news"
31
+ XBRL_DIR = DATA_DIR / "xbrl"
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Paths -- Layer 2 & 3 (derived from GRANULARITY)
35
+ # ---------------------------------------------------------------------------
36
+ GRANULARITY: str = "daily" # "daily", "weekly", or "monthly"
37
+
38
+
39
+ def get_processed_dir(granularity: str | None = None) -> Path:
40
+ """Return the processed-data directory for *granularity* (default: GRANULARITY)."""
41
+ return DATA_DIR / "processed" / (granularity or GRANULARITY)
42
+
43
+
44
+ def get_benchmark_dir(granularity: str | None = None) -> Path:
45
+ """Return the benchmark-output directory for *granularity* (default: GRANULARITY)."""
46
+ return DATA_DIR / "benchmark" / (granularity or GRANULARITY)
47
+
48
+
49
+ # Legacy module-level aliases (point to the default granularity).
50
+ # Use the functions above when the caller might override granularity.
51
+ PROCESSED_DIR = get_processed_dir()
52
+ BENCHMARK_DIR = get_benchmark_dir()
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Date range (fixed for reproducibility)
56
+ # ---------------------------------------------------------------------------
57
+ START_DATE = "2021-01-01"
58
+ END_DATE = "2026-04-01"
59
+ START_YEAR = int(START_DATE[:4]) # 2021 — used by collect_filings.py
60
+ END_YEAR = int(END_DATE[:4]) # 2026 — used by collect_filings.py
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Global reproducibility seed
64
+ # ---------------------------------------------------------------------------
65
+ BENCHMARK_SEED = 42
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Ticker universe
69
+ # ---------------------------------------------------------------------------
70
+ # iShares Russell 2000 ETF holdings CSV URL
71
+ IWM_HOLDINGS_URL = (
72
+ "https://www.ishares.com/us/products/239710/"
73
+ "ishares-russell-2000-etf/1467271812596.ajax?"
74
+ "fileType=csv&fileName=IWM_holdings&dataType=fund"
75
+ )
76
+ # iShares Core S&P SmallCap ETF (IJR) — tracks S&P SmallCap 600 index
77
+ # Defines official "small-cap" range: $1B – $7.4B (S&P methodology, 2025).
78
+ IJR_HOLDINGS_URL = (
79
+ "https://www.ishares.com/us/products/239774/"
80
+ "ishares-core-sp-smallcap-etf/1467271812596.ajax?"
81
+ "fileType=csv&fileName=IJR_holdings&dataType=fund"
82
+ )
83
+ # iShares Micro-Cap ETF holdings CSV URL (micro-caps below small-cap threshold)
84
+ IWC_HOLDINGS_URL = (
85
+ "https://www.ishares.com/us/products/239724/"
86
+ "ishares-microcap-etf/1467271812596.ajax?"
87
+ "fileType=csv&fileName=IWC_holdings&dataType=fund"
88
+ )
89
+
90
+ # Market-cap upper bound for the "small-cap and below" universe.
91
+ # $7.4B = official S&P 600 SmallCap upper bound (S&P Dow Jones Indices, 2025).
92
+ # Tickers with median derived_market_cap above this are filtered out as
93
+ # mid-cap or larger and excluded from the benchmark.
94
+ SMALL_CAP_MAX_MEDIAN_MCAP: float = 7.4e9
95
+
96
+ # Market-cap percentile threshold to label "lower end" of Russell 2000
97
+ LOWER_END_PERCENTILE = 50 # bottom 50 %
98
+
99
+ # Cap the total number of tickers (set to None for full universe)
100
+ MAX_TICKERS: int | None = None
101
+
102
+ # Tickers excluded from the universe (none — filter is applied via market cap).
103
+ EXCLUDED_TICKERS: list[str] = []
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Fundamentals collection
107
+ # ---------------------------------------------------------------------------
108
+ FUNDAMENTALS_WORKERS = 2 # ThreadPoolExecutor parallelism (low to avoid yfinance rate limits)
109
+
110
+ # ---------------------------------------------------------------------------
111
+ # Price collection
112
+ # ---------------------------------------------------------------------------
113
+ PRICE_BATCH_SIZE = 50 # tickers per yf.download() call
114
+
115
+ # ---------------------------------------------------------------------------
116
+ # SEC filings
117
+ # ---------------------------------------------------------------------------
118
+ SEC_FILING_TYPES: list[str] = ["10-K", "10-Q", "8-K", "20-F", "6-K", "N-CSR", "N-CSRS"]
119
+ SEC_FILING_WORKERS = 4 # asyncio.Semaphore concurrency
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # FRED macro series
123
+ # ---------------------------------------------------------------------------
124
+ FRED_SERIES: dict[str, str] = {
125
+ # ── Rates & monetary policy ──
126
+ "FEDFUNDS": "Federal Funds Effective Rate",
127
+ "SOFR": "Secured Overnight Financing Rate",
128
+ "DGS2": "2-Year Treasury Constant Maturity Rate",
129
+ "DGS10": "10-Year Treasury Constant Maturity Rate",
130
+ "DGS30": "30-Year Treasury Constant Maturity Rate",
131
+ "T10Y3M": "10-Year Treasury Minus 3-Month Treasury",
132
+ "T10Y2Y": "10-Year Treasury Minus 2-Year Treasury",
133
+ "MORTGAGE30US": "30-Year Fixed Rate Mortgage Average",
134
+ # ── Equity & volatility ──
135
+ "SP500": "S&P 500 Index",
136
+ "NASDAQCOM": "NASDAQ Composite Index",
137
+ "DJIA": "Dow Jones Industrial Average",
138
+ "VIXCLS": "CBOE Volatility Index (VIX)",
139
+ # ── Commodities (FRED daily) ──
140
+ "DCOILWTICO": "Crude Oil Prices: West Texas Intermediate (WTI)",
141
+ "DHHNGSP": "Henry Hub Natural Gas Spot Price",
142
+ # ── Currency & exchange rates ──
143
+ "DTWEXBGS": "Trade Weighted U.S. Dollar Index",
144
+ "DEXUSEU": "U.S. / Euro Foreign Exchange Rate",
145
+ "DEXJPUS": "Japan / U.S. Foreign Exchange Rate",
146
+ "DEXUSUK": "U.S. / U.K. Foreign Exchange Rate",
147
+ "DEXCHUS": "China / U.S. Foreign Exchange Rate",
148
+ # ── Inflation & prices ──
149
+ "CPIAUCSL": "Consumer Price Index For All Urban Consumers (All Items)",
150
+ "CPILFESL": "Consumer Price Index Less Food and Energy (Core CPI)",
151
+ "PPIACO": "Producer Price Index (All Commodities)",
152
+ "T10YIE": "10-Year Breakeven Inflation Rate",
153
+ "T5YIE": "5-Year Breakeven Inflation Rate",
154
+ "PCEPI": "Personal Consumption Expenditures: Chain-type Price Index",
155
+ # ── Labor market ──
156
+ "UNRATE": "Unemployment Rate",
157
+ "ICSA": "Initial Claims (Weekly Jobless Claims)",
158
+ "PAYEMS": "All Employees Total Nonfarm (Payrolls)",
159
+ "JTSJOL": "Job Openings: Total Nonfarm (JOLTS)",
160
+ "CES0500000003": "Average Hourly Earnings of All Employees (Total Private)",
161
+ # ── Credit & financial stress ──
162
+ "BAMLH0A0HYM2": "ICE BofA US High Yield Option-Adjusted Spread",
163
+ "BAMLC0A0CM": "ICE BofA US Corporate Master Option-Adjusted Spread",
164
+ "TEDRATE": "TED Spread (3-Month LIBOR minus 3-Month T-Bill)",
165
+ "STLFSI2": "St. Louis Fed Financial Stress Index",
166
+ "NFCI": "Chicago Fed National Financial Conditions Index",
167
+ # ── Economic activity ──
168
+ "INDPRO": "Industrial Production Index",
169
+ "RSAFS": "Advance Retail Sales: Retail and Food Services",
170
+ "UMCSENT": "University of Michigan Consumer Sentiment",
171
+ "TOTALSA": "Total Vehicle Sales",
172
+ "PERMIT": "New Privately-Owned Housing Units Authorized (Building Permits)",
173
+ # ── Housing ──
174
+ "CSUSHPISA": "S&P/Case-Shiller U.S. National Home Price Index",
175
+ "HOUST": "Housing Starts: Total New Privately Owned",
176
+ # ── Money supply & central bank ──
177
+ "M2SL": "M2 Money Stock",
178
+ "BOGMBASE": "Monetary Base; Total",
179
+ "WALCL": "Federal Reserve Total Assets (Balance Sheet)",
180
+ # ── Business lending ──
181
+ "BUSLOANS": "Commercial and Industrial Loans, All Commercial Banks",
182
+ }
183
+
184
+ # ---------------------------------------------------------------------------
185
+ # Real estate metros (address anchors for RentCast radius search)
186
+ # ---------------------------------------------------------------------------
187
+ _ALL_METROS: list[str] = [
188
+ # ── Top 20 (original) ──
189
+ "350 5th Ave, New York, NY 10118",
190
+ "233 S Wacker Dr, Chicago, IL 60606",
191
+ "1000 Vin Scully Ave, Los Angeles, CA 90012",
192
+ "600 Travis St, Houston, TX 77002",
193
+ "400 S Tryon St, Charlotte, NC 28202",
194
+ "100 Peachtree St NW, Atlanta, GA 30303",
195
+ "200 E Las Olas Blvd, Fort Lauderdale, FL 33301",
196
+ "700 2nd Ave S, Nashville, TN 37210",
197
+ "1 N Central Ave, Phoenix, AZ 85004",
198
+ "2001 Ross Ave, Dallas, TX 75201",
199
+ "200 E Colfax Ave, Denver, CO 80203",
200
+ "1 S Broad St, Philadelphia, PA 19107",
201
+ "100 Summer St, Boston, MA 02110",
202
+ "700 5th Ave, Seattle, WA 98104",
203
+ "50 Fremont St, San Francisco, CA 94105",
204
+ "401 E Pratt St, Baltimore, MD 21202",
205
+ "1 S Main St, Salt Lake City, UT 84111",
206
+ "400 S Orange Ave, Orlando, FL 32801",
207
+ "100 NE 2nd Ave, Portland, OR 97232",
208
+ "325 John Knox Rd, Tallahassee, FL 32303",
209
+ # ── 21-40: Large metros ──
210
+ "1 Riverfront Plz, Newark, NJ 07102",
211
+ "100 N Main St, Memphis, TN 38103",
212
+ "200 W Washington St, Indianapolis, IN 46204",
213
+ "100 S Main St, Las Vegas, NV 89101",
214
+ "600 E Market St, San Antonio, TX 78205",
215
+ "200 E Pratt St, Milwaukee, WI 53202",
216
+ "100 N Broadway, Oklahoma City, OK 73102",
217
+ "500 Main St, Louisville, KY 40202",
218
+ "100 N Main St, Richmond, VA 23219",
219
+ "1 S Pinckney St, Madison, WI 53703",
220
+ "200 E Main St, Norfolk, VA 23510",
221
+ "100 W Capitol Ave, Little Rock, AR 72201",
222
+ "100 S Main St, Tulsa, OK 74103",
223
+ "1 Canal St, New Orleans, LA 70130",
224
+ "100 E Capitol St, Jackson, MS 39201",
225
+ "200 W Adams St, Jacksonville, FL 32202",
226
+ "100 N Main St, Wichita, KS 67202",
227
+ "100 State St, Hartford, CT 06103",
228
+ "1 Exchange Pl, Providence, RI 02903",
229
+ "100 N Tryon St, Raleigh, NC 27601",
230
+ # ── 41-60: Mid-size metros ──
231
+ "200 E Main St, Lexington, KY 40507",
232
+ "100 N Main St, Dayton, OH 45402",
233
+ "100 W 10th St, Wilmington, DE 19801",
234
+ "100 S Main St, Akron, OH 44308",
235
+ "200 N Main St, Greenville, SC 29601",
236
+ "100 E Washington St, Boise, ID 83702",
237
+ "1 City Hall Plz, Durham, NC 27701",
238
+ "100 W Trade St, Winston-Salem, NC 27101",
239
+ "100 S Virginia St, Reno, NV 89501",
240
+ "200 E Main St, Chattanooga, TN 37402",
241
+ "100 N Main St, Columbia, SC 29201",
242
+ "1 S Main St, Spokane, WA 99201",
243
+ "100 E Congress St, Tucson, AZ 85701",
244
+ "200 W Markham St, Birmingham, AL 35203",
245
+ "100 S Main St, Omaha, NE 68102",
246
+ "100 W Broad St, Columbus, OH 43215",
247
+ "100 W Michigan Ave, Kalamazoo, MI 49007",
248
+ "200 N Main St, Ann Arbor, MI 48104",
249
+ "100 E 8th St, Cincinnati, OH 45202",
250
+ "100 S 4th St, Minneapolis, MN 55401",
251
+ # ── 61-80: Growing metros ──
252
+ "100 N Main St, Knoxville, TN 37902",
253
+ "200 W Camelback Rd, Scottsdale, AZ 85251",
254
+ "100 S State St, Provo, UT 84601",
255
+ "100 N College Ave, Fort Collins, CO 80524",
256
+ "200 E Main St, Lakeland, FL 33801",
257
+ "100 S Main St, Savannah, GA 31401",
258
+ "100 W Liberty St, Roanoke, VA 24011",
259
+ "200 E Bay St, Charleston, SC 29401",
260
+ "100 N Main St, Greensburg, PA 15601",
261
+ "100 S Palafox St, Pensacola, FL 32502",
262
+ "200 W Capitol Dr, Baton Rouge, LA 70801",
263
+ "100 E Main St, Mesa, AZ 85201",
264
+ "100 N Central Ave, St. Louis, MO 63101",
265
+ "200 Ross St, Pittsburgh, PA 15219",
266
+ "100 Woodward Ave, Detroit, MI 48226",
267
+ "100 W Main St, Bozeman, MT 59715",
268
+ "100 S 1st Ave, Sioux Falls, SD 57104",
269
+ "200 N Main St, Santa Fe, NM 87501",
270
+ "100 N Stone Ave, Albuquerque, NM 87102",
271
+ "100 S Capitol Blvd, Boise, ID 83702",
272
+ # ── 81-100: Smaller / emerging metros ──
273
+ "200 E Main St, Asheville, NC 28801",
274
+ "100 Congress Ave, Austin, TX 78701",
275
+ "200 E Commerce St, San Jose, CA 95113",
276
+ "100 W Flagler St, Miami, FL 33130",
277
+ "200 S Orange Ave, Sarasota, FL 34236",
278
+ "100 N Main St, Gainesville, FL 32601",
279
+ "200 E College Ave, Tallahassee, FL 32301",
280
+ "100 N Main St, Fayetteville, AR 72701",
281
+ "100 E Market St, Des Moines, IA 50309",
282
+ "200 N Main St, McAllen, TX 78501",
283
+ "100 S Broadway, Wichita Falls, TX 76301",
284
+ "100 W Front St, Missoula, MT 59802",
285
+ "200 E Main St, Rapid City, SD 57701",
286
+ "100 N 1st St, Bismarck, ND 58501",
287
+ "200 W Superior St, Duluth, MN 55802",
288
+ "100 E Main St, Rochester, NY 14604",
289
+ "200 S Warren St, Syracuse, NY 13202",
290
+ "100 Main St, Buffalo, NY 14202",
291
+ "200 E State St, Trenton, NJ 08608",
292
+ "100 S Main St, Harrisburg, PA 17101",
293
+ ]
294
+ # For testing: set MAX_METROS to limit (None = all 100)
295
+ MAX_METROS: int | None = None
296
+ METROS: list[str] = _ALL_METROS[:MAX_METROS] if MAX_METROS else _ALL_METROS
297
+ RENTCAST_PROPERTY_TYPES = ["Multi-Family", "Apartment", "Single Family", "Condo", "Townhouse"]
298
+ RENTCAST_RADIUS_MILES = 5.0
299
+ RENTCAST_MAX_RESULTS = 500 # max properties per endpoint per metro (1 page)
300
+
301
+ # ---------------------------------------------------------------------------
302
+ # Preprocessing (Layer 2)
303
+ # ---------------------------------------------------------------------------
304
+ # Key metrics to extract from per-ticker financial statement CSVs
305
+ INCOME_KEYS: dict[str, str] = {
306
+ "Total Revenue": "stmt_revenue",
307
+ "Net Income": "stmt_net_income",
308
+ "EBITDA": "stmt_ebitda",
309
+ "EBIT": "stmt_ebit",
310
+ "Gross Profit": "stmt_gross_profit",
311
+ "Operating Income": "stmt_operating_income",
312
+ "Basic EPS": "stmt_basic_eps",
313
+ # Valuation inputs (WACC / effective tax rate / cost of debt)
314
+ "Tax Provision": "stmt_tax_provision",
315
+ "Pretax Income": "stmt_pretax_income",
316
+ "Interest Expense": "stmt_interest_expense",
317
+ "Tax Rate For Calcs": "stmt_tax_rate",
318
+ # Income-statement detail items
319
+ "Cost Of Revenue": "stmt_cogs",
320
+ "Operating Expense": "stmt_operating_expenses",
321
+ }
322
+ BALANCE_KEYS: dict[str, str] = {
323
+ "Total Assets": "stmt_total_assets",
324
+ "Total Liabilities Net Minority Interest": "stmt_total_liabilities",
325
+ "Total Debt": "stmt_total_debt",
326
+ "Total Equity Gross Minority Interest": "stmt_total_equity",
327
+ "Cash And Cash Equivalents": "stmt_cash",
328
+ "Ordinary Shares Number": "stmt_shares_outstanding",
329
+ "Share Issued": "stmt_shares_issued",
330
+ # Balance-sheet detail items
331
+ "Accounts Receivable": "stmt_accounts_receivable",
332
+ "Net Receivables": "stmt_accounts_receivable",
333
+ "Inventory": "stmt_inventory",
334
+ "Current Assets": "stmt_current_assets",
335
+ "Net PPE": "stmt_ppe_net",
336
+ "Goodwill": "stmt_goodwill",
337
+ "Accounts Payable": "stmt_accounts_payable",
338
+ "Current Liabilities": "stmt_current_liabilities",
339
+ "Long Term Debt": "stmt_lt_debt",
340
+ }
341
+ CASHFLOW_KEYS: dict[str, str] = {
342
+ "Operating Cash Flow": "stmt_operating_cashflow",
343
+ "Free Cash Flow": "stmt_free_cashflow",
344
+ "Capital Expenditure": "stmt_capex",
345
+ "Financing Cash Flow": "stmt_financing_cashflow",
346
+ }
347
+
348
+ # XBRL tag → stmt_ column mapping (SEC EDGAR).
349
+ # Each stmt_ column maps to a list of XBRL tags tried in priority order;
350
+ # the first non-null value wins. Tags are US-GAAP concepts reported in
351
+ # 10-K / 10-Q filings stored in data/xbrl/parsed/company_facts.parquet.
352
+ XBRL_TAG_MAP: dict[str, list[str]] = {
353
+ "stmt_revenue": [
354
+ "Revenues",
355
+ "RevenueFromContractWithCustomerExcludingAssessedTax",
356
+ "SalesRevenueNet",
357
+ "RevenueFromContractWithCustomerIncludingAssessedTax",
358
+ # Banking / Financial Services equivalents
359
+ "InterestAndDividendIncomeOperating",
360
+ "InterestIncomeExpenseNet",
361
+ "NetInterestIncome",
362
+ "NoninterestIncome",
363
+ "FinancialServicesRevenue",
364
+ # Insurance equivalents
365
+ "PremiumsEarnedNet",
366
+ "InsuranceServicesRevenue",
367
+ "PremiumsWrittenNet",
368
+ # IFRS equivalents
369
+ "Revenue",
370
+ "RevenueFromContractsWithCustomers",
371
+ ],
372
+ "stmt_net_income": [
373
+ "NetIncomeLoss",
374
+ # IFRS
375
+ "ProfitLoss",
376
+ "ProfitLossAttributableToOwnersOfParent",
377
+ ],
378
+ "stmt_ebit": [
379
+ "OperatingIncomeLoss",
380
+ # IFRS
381
+ "ProfitLossBeforeFinanceCostsAndTax",
382
+ "OperatingProfitLoss",
383
+ ],
384
+ "stmt_gross_profit": [
385
+ "GrossProfit",
386
+ ],
387
+ "stmt_operating_income": [
388
+ "OperatingIncomeLoss",
389
+ # IFRS
390
+ "ProfitLossFromOperatingActivities",
391
+ "OperatingProfitLoss",
392
+ ],
393
+ "stmt_basic_eps": [
394
+ "EarningsPerShareBasic",
395
+ # IFRS
396
+ "BasicEarningsLossPerShare",
397
+ ],
398
+ "stmt_tax_provision": [
399
+ "IncomeTaxExpenseBenefit",
400
+ # IFRS
401
+ "IncomeTaxExpenseContinuingOperations",
402
+ ],
403
+ "stmt_pretax_income": [
404
+ "IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest",
405
+ # IFRS
406
+ "ProfitLossBeforeTax",
407
+ ],
408
+ "stmt_interest_expense": [
409
+ "InterestExpense",
410
+ # IFRS
411
+ "FinanceCosts",
412
+ "InterestExpenseOnBorrowings",
413
+ ],
414
+ "stmt_operating_cashflow": [
415
+ "NetCashProvidedByUsedInOperatingActivities",
416
+ # IFRS
417
+ "CashFlowsFromUsedInOperatingActivities",
418
+ ],
419
+ "stmt_capex": [
420
+ "PaymentsToAcquirePropertyPlantAndEquipment",
421
+ # IFRS
422
+ "PurchaseOfPropertyPlantAndEquipmentClassifiedAsInvestingActivities",
423
+ ],
424
+ "stmt_total_assets": ["Assets"],
425
+ "stmt_total_liabilities": ["Liabilities"],
426
+ "stmt_total_debt": [
427
+ "LongTermDebt",
428
+ "LongTermDebtNoncurrent",
429
+ # IFRS
430
+ "NoncurrentFinancialLiabilities",
431
+ "BorrowingsNoncurrent",
432
+ "NoncurrentPortionOfNoncurrentBorrowings",
433
+ ],
434
+ "stmt_total_equity": [
435
+ "StockholdersEquity",
436
+ "StockholdersEquityIncludingPortionAttributableToNoncontrollingInterest",
437
+ # IFRS
438
+ "Equity",
439
+ "EquityAttributableToOwnersOfParent",
440
+ ],
441
+ "stmt_cash": [
442
+ "CashAndCashEquivalentsAtCarryingValue",
443
+ "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents",
444
+ # IFRS
445
+ "CashAndCashEquivalents",
446
+ ],
447
+ "stmt_shares_outstanding": [
448
+ "CommonStockSharesOutstanding",
449
+ "EntityCommonStockSharesOutstanding",
450
+ # Fallback: weighted-average for dual-class companies (CRWD, DDOG, etc.)
451
+ "WeightedAverageNumberOfSharesOutstandingBasic",
452
+ "WeightedAverageNumberOfDilutedSharesOutstanding",
453
+ "CommonSharesOutstanding",
454
+ ],
455
+ "stmt_shares_issued": [
456
+ "CommonStockSharesIssued",
457
+ # IFRS
458
+ "IssuedCapital",
459
+ ],
460
+ # ── Balance-sheet detail items ──
461
+ "stmt_accounts_receivable": [
462
+ "AccountsReceivableNetCurrent",
463
+ "AccountsReceivableNet",
464
+ # IFRS
465
+ "TradeAndOtherCurrentReceivables",
466
+ ],
467
+ "stmt_inventory": [
468
+ "InventoryNet",
469
+ "Inventories",
470
+ # IFRS
471
+ "CurrentInventories",
472
+ ],
473
+ "stmt_current_assets": [
474
+ "AssetsCurrent",
475
+ # IFRS
476
+ "CurrentAssets",
477
+ ],
478
+ "stmt_ppe_net": [
479
+ "PropertyPlantAndEquipmentNet",
480
+ # IFRS
481
+ "PropertyPlantAndEquipment",
482
+ ],
483
+ "stmt_goodwill": [
484
+ "Goodwill",
485
+ # IFRS
486
+ "GoodwillGross",
487
+ ],
488
+ "stmt_accounts_payable": [
489
+ "AccountsPayableCurrent",
490
+ "AccountsPayable",
491
+ # IFRS
492
+ "TradeAndOtherCurrentPayables",
493
+ ],
494
+ "stmt_current_liabilities": [
495
+ "LiabilitiesCurrent",
496
+ # IFRS
497
+ "CurrentLiabilities",
498
+ ],
499
+ "stmt_lt_debt": [
500
+ "LongTermDebtNoncurrent",
501
+ "LongTermDebt",
502
+ "LongTermDebtAndCapitalLeaseObligations",
503
+ # IFRS
504
+ "NoncurrentFinancialLiabilities",
505
+ "BorrowingsNoncurrent",
506
+ ],
507
+ # ── Income-statement detail items ──
508
+ "stmt_cogs": [
509
+ "CostOfGoodsAndServicesSold",
510
+ "CostOfRevenue",
511
+ "CostOfGoodsSold",
512
+ # IFRS
513
+ "CostOfSales",
514
+ ],
515
+ "stmt_operating_expenses": [
516
+ "OperatingExpenses",
517
+ # IFRS
518
+ "AdministrativeExpense",
519
+ ],
520
+ # ── Cash-flow detail items ──
521
+ "stmt_financing_cashflow": [
522
+ "NetCashProvidedByUsedInFinancingActivities",
523
+ # IFRS
524
+ "CashFlowsFromUsedInFinancingActivities",
525
+ ],
526
+ }
527
+
528
+ # Auxiliary XBRL tags used to derive composite metrics (EBITDA, FCF, tax rate).
529
+ XBRL_DA_TAGS: list[str] = [
530
+ "DepreciationDepletionAndAmortization",
531
+ "DepreciationAndAmortization",
532
+ "Depreciation",
533
+ # IFRS
534
+ "DepreciationAmortisationAndImpairmentLossReversalOfImpairmentLossRecognisedInProfitOrLoss",
535
+ "DepreciationAndAmortisationExpense",
536
+ ]
537
+
538
+ # ---------------------------------------------------------------------------
539
+ # Benchmark assembly (Layer 3)
540
+ # ---------------------------------------------------------------------------
541
+ # Temporal split configuration.
542
+ # Set TEMPORAL_SPLIT_DATE to a fixed date string (e.g. "2024-01-01") to split
543
+ # at that exact date, OR set it to None and use TEMPORAL_SPLIT_RATIO instead.
544
+ TEMPORAL_SPLIT_DATE: str | None = None
545
+
546
+ # Train fraction of unique panel dates (e.g. 0.7 = 70% train, 30% test).
547
+ # Only used when TEMPORAL_SPLIT_DATE is None.
548
+ TEMPORAL_SPLIT_RATIO: float = 0.7
549
+
550
+ # Forecasting task parameters -- granularity-aware.
551
+ # Values are in *panel periods* (not calendar days).
552
+ # daily: 5d≈1w, 21d≈1mo, 63d≈1q, 126d≈6mo, 252d≈1y
553
+ # weekly: 4w≈1mo, 13w≈1q, 26w≈6mo, 52w≈1y
554
+ # monthly: 1mo, 3mo≈1q, 6mo, 12mo≈1y
555
+ HORIZONS_BY_GRANULARITY: dict[str, list[int]] = {
556
+ "daily": [5, 21, 63, 126, 252],
557
+ "weekly": [4, 13, 26, 52],
558
+ "monthly": [1, 3, 6, 12],
559
+ }
560
+ LOOKBACK_WINDOWS_BY_GRANULARITY: dict[str, list[int]] = {
561
+ "daily": [63, 126, 252],
562
+ "weekly": [13, 26, 52],
563
+ "monthly": [3, 6, 12],
564
+ }
565
+
566
+ # Legacy flat aliases (default granularity) -- prefer the dicts above.
567
+ HORIZONS: list[int] = HORIZONS_BY_GRANULARITY[GRANULARITY]
568
+ LOOKBACK_WINDOWS: list[int] = LOOKBACK_WINDOWS_BY_GRANULARITY[GRANULARITY]
569
+
570
+
571
+ def get_horizons(granularity: str | None = None) -> list[int]:
572
+ """Return forecast horizons for *granularity*."""
573
+ return HORIZONS_BY_GRANULARITY[granularity or GRANULARITY]
574
+
575
+
576
+ def get_lookback_windows(granularity: str | None = None) -> list[int]:
577
+ """Return lookback windows for *granularity*."""
578
+ return LOOKBACK_WINDOWS_BY_GRANULARITY[granularity or GRANULARITY]
579
+
580
+ # ---------------------------------------------------------------------------
581
+ # Scenario detection thresholds (Layer 3 -- generate_scenarios.py)
582
+ # ---------------------------------------------------------------------------
583
+ # Fed funds: minimum absolute change in rate (percentage points) between
584
+ # consecutive monthly observations to flag as a rate-change event.
585
+ SCENARIO_FEDFUNDS_DELTA = 0.25 # 25 bps
586
+
587
+ # VIX: spike ratio -- current value / rolling mean must exceed this.
588
+ SCENARIO_VIX_SPIKE_RATIO = 1.4
589
+ SCENARIO_VIX_ROLLING_WINDOW = 63 # observations (daily)
590
+
591
+ # Oil (EIA commodity or FRED DCOILWTICO): pct move over rolling window.
592
+ SCENARIO_OIL_PCT_CHANGE = 0.09 # 9 %
593
+ SCENARIO_OIL_ROLLING_WINDOW = 21 # observations (daily)
594
+
595
+ # Natural gas: minimum percentage move over a rolling window.
596
+ SCENARIO_NATGAS_PCT_CHANGE = 0.15 # 15 %
597
+ SCENARIO_NATGAS_ROLLING_WINDOW = 4 # observations (weekly data)
598
+
599
+ # Market drawdown: minimum percentage drop in S&P 500 over a rolling window.
600
+ SCENARIO_SP500_DRAWDOWN = 0.025 # 2.5 %
601
+ SCENARIO_SP500_ROLLING_WINDOW = 21 # observations (daily)
602
+
603
+ # NASDAQ: minimum percentage move (crash or rally divergence).
604
+ SCENARIO_NASDAQ_PCT_CHANGE = 0.045 # 4.5 %
605
+ SCENARIO_NASDAQ_ROLLING_WINDOW = 21 # observations (daily)
606
+
607
+ # Yield curve: DGS10 - DGS2 spread thresholds.
608
+ SCENARIO_YIELD_CURVE_INVERSION = 0.0 # spread crosses below 0 = inversion
609
+ SCENARIO_YIELD_CURVE_STEEPENING = 0.50 # spread widens by ≥ 50bps over window
610
+ SCENARIO_YIELD_CURVE_WINDOW = 63 # observations (daily)
611
+
612
+ # Treasury rate (DGS10): large absolute move in 10-year yield.
613
+ SCENARIO_DGS10_DELTA = 0.45 # 45 bps move over window
614
+ SCENARIO_DGS10_ROLLING_WINDOW = 21 # observations (daily)
615
+
616
+ # USD index (DTWEXBGS): large percentage move in trade-weighted dollar.
617
+ SCENARIO_USD_PCT_CHANGE = 0.025 # 2.5 %
618
+ SCENARIO_USD_ROLLING_WINDOW = 21 # observations (daily)
619
+
620
+ # CPI / Inflation: large month-over-month change in annualized rate.
621
+ SCENARIO_CPI_MOM_THRESHOLD = 0.004 # 0.4% month-over-month (≈4.8% annualized)
622
+
623
+ # PPI: large month-over-month change.
624
+ SCENARIO_PPI_MOM_THRESHOLD = 0.01 # 1% month-over-month
625
+
626
+ # Unemployment: jump in rate between consecutive observations.
627
+ SCENARIO_UNRATE_DELTA = 0.3 # 30 bps increase
628
+
629
+ # Jobless claims (ICSA): spike ratio vs rolling mean.
630
+ SCENARIO_ICSA_SPIKE_RATIO = 1.3
631
+ SCENARIO_ICSA_ROLLING_WINDOW = 8 # observations (weekly)
632
+
633
+ # Payrolls (PAYEMS): large month-over-month change in thousands.
634
+ SCENARIO_PAYROLLS_DELTA = 0.002 # 0.2% month-over-month change
635
+
636
+ # High-yield credit spread: large move over rolling window.
637
+ SCENARIO_HY_SPREAD_DELTA = 1.0 # 100 bps widening/tightening over window
638
+ SCENARIO_HY_SPREAD_WINDOW = 21 # observations (daily)
639
+
640
+ # IG corporate spread: large move over rolling window.
641
+ SCENARIO_IG_SPREAD_DELTA = 0.30 # 30 bps over window
642
+ SCENARIO_IG_SPREAD_WINDOW = 21
643
+
644
+ # TED spread: spike above threshold.
645
+ SCENARIO_TED_SPIKE = 0.50 # 50 bps
646
+
647
+ # Financial stress index: large move.
648
+ SCENARIO_FSI_THRESHOLD = 1.0 # standard deviation units (index is z-scored)
649
+
650
+ # Mortgage rate: large move over rolling window.
651
+ SCENARIO_MORTGAGE_DELTA = 0.50 # 50 bps move over window
652
+ SCENARIO_MORTGAGE_ROLLING_WINDOW = 4 # observations (weekly)
653
+
654
+ # Consumer sentiment (UMCSENT): large drop.
655
+ SCENARIO_SENTIMENT_PCT_CHANGE = 0.10 # 10% drop
656
+ SCENARIO_SENTIMENT_ROLLING_WINDOW = 2 # observations (monthly)
657
+
658
+ # Industrial production: large month-over-month change.
659
+ SCENARIO_INDPRO_PCT_CHANGE = 0.01 # 1% month-over-month
660
+
661
+ # Retail sales: large month-over-month change.
662
+ SCENARIO_RETAIL_PCT_CHANGE = 0.02 # 2% month-over-month
663
+
664
+ # Housing starts: large month-over-month change.
665
+ SCENARIO_HOUSING_PCT_CHANGE = 0.10 # 10% month-over-month
666
+
667
+ # Home prices (Case-Shiller): year-over-year deceleration/acceleration.
668
+ SCENARIO_HOME_PRICE_YOY_DELTA = 0.03 # 3pp change in YoY rate
669
+
670
+ # Money supply (M2): year-over-year contraction.
671
+ SCENARIO_M2_YOY_THRESHOLD = -0.01 # YoY growth below -1% (contraction)
672
+
673
+ # 30-year Treasury: large move.
674
+ SCENARIO_DGS30_DELTA = 0.50 # 50 bps over window
675
+ SCENARIO_DGS30_ROLLING_WINDOW = 21
676
+
677
+ # Cross-asset: S&P 500 vs NASDAQ divergence.
678
+ SCENARIO_SP_NASDAQ_DIVERGENCE = 0.05 # 5% divergence over window
679
+ SCENARIO_SP_NASDAQ_WINDOW = 21
680
+
681
+ # VIX regime: sustained elevated volatility.
682
+ SCENARIO_VIX_REGIME_THRESHOLD = 25.0 # VIX above 25
683
+ SCENARIO_VIX_REGIME_MIN_DAYS = 10 # sustained for at least 10 days
684
+
685
+ # ── NEW: Major FX pair shocks (EUR, JPY, GBP, CNY) ──
686
+ SCENARIO_FX_PCT_CHANGE = 0.03 # 3% move over window
687
+ SCENARIO_FX_ROLLING_WINDOW = 21
688
+
689
+ # ── NEW: Breakeven inflation shocks (T10YIE, T5YIE) ──
690
+ SCENARIO_BEI_DELTA = 0.30 # 30 bps move over window
691
+ SCENARIO_BEI_ROLLING_WINDOW = 21
692
+
693
+ # ── NEW: DJIA large moves ──
694
+ SCENARIO_DJIA_PCT_CHANGE = 0.03 # 3% move over window
695
+ SCENARIO_DJIA_ROLLING_WINDOW = 21
696
+
697
+ # ── NEW: JOLTS job openings ──
698
+ SCENARIO_JOLTS_PCT_CHANGE = 0.05 # 5% month-over-month change
699
+ SCENARIO_JOLTS_DEDUP_DAYS = 28
700
+
701
+ # ── NEW: Average hourly earnings ──
702
+ SCENARIO_EARNINGS_MOM_THRESHOLD = 0.005 # 0.5% month-over-month
703
+
704
+ # ── NEW: Vehicle sales ──
705
+ SCENARIO_VEHICLE_PCT_CHANGE = 0.08 # 8% month-over-month
706
+
707
+ # ── NEW: Building permits ──
708
+ SCENARIO_PERMIT_PCT_CHANGE = 0.08 # 8% month-over-month
709
+
710
+ # ── NEW: Existing home sales ──
711
+ SCENARIO_EXISTING_HOME_SALES_PCT = 0.05 # 5% month-over-month
712
+
713
+ # ── NEW: Chicago Fed NFCI ──
714
+ SCENARIO_NFCI_THRESHOLD = 0.0 # NFCI crosses above 0 (tighter than avg)
715
+
716
+ # ── NEW: Fed balance sheet (WALCL) ──
717
+ SCENARIO_FED_BS_PCT_CHANGE = 0.05 # 5% change over window (quarterly)
718
+ SCENARIO_FED_BS_ROLLING_WINDOW = 13 # ~quarterly for weekly data
719
+
720
+ # ── NEW: Monetary base (BOGMBASE) ──
721
+ SCENARIO_MONETARY_BASE_PCT = 0.05 # 5% month-over-month
722
+
723
+ # ── NEW: Business loans (BUSLOANS) ──
724
+ SCENARIO_BUSLOANS_PCT_CHANGE = 0.02 # 2% month-over-month
725
+
726
+ # ── NEW: PCE inflation ──
727
+ SCENARIO_PCEPI_MOM_THRESHOLD = 0.004 # 0.4% month-over-month
728
+
729
+ # ── NEW: SOFR rate shocks ──
730
+ SCENARIO_SOFR_DELTA = 0.25 # 25 bps move
731
+ SCENARIO_SOFR_WINDOW = 10 # observations
732
+
733
+ # ── NEW: Cross-asset composites ──
734
+ # Real yield: DGS10 - T10YIE (breakeven inflation)
735
+ SCENARIO_REAL_YIELD_DELTA = 0.40 # 40 bps change in real yield
736
+ SCENARIO_REAL_YIELD_WINDOW = 21
737
+ # Credit compression: HY spread minus IG spread
738
+ SCENARIO_CREDIT_COMPRESSION_DELTA = 0.75 # 75 bps change
739
+ SCENARIO_CREDIT_COMPRESSION_WINDOW = 21
740
+ # Term premium: DGS30 - DGS2
741
+ SCENARIO_TERM_PREMIUM_DELTA = 0.50 # 50 bps change
742
+ SCENARIO_TERM_PREMIUM_WINDOW = 21
743
+ # ── NEW: Short-term shock windows (5-day) for daily series ──
744
+ SCENARIO_SP500_SHORT_DRAWDOWN = 0.03 # 3% over 5 days (acute crash)
745
+ SCENARIO_SP500_SHORT_WINDOW = 5
746
+ SCENARIO_NASDAQ_SHORT_PCT = 0.04 # 4% over 5 days
747
+ SCENARIO_NASDAQ_SHORT_WINDOW = 5
748
+ SCENARIO_OIL_SHORT_PCT = 0.08 # 8% over 5 days
749
+ SCENARIO_OIL_SHORT_WINDOW = 5
750
+ SCENARIO_DGS10_SHORT_DELTA = 0.25 # 25 bps over 5 days
751
+ SCENARIO_DGS10_SHORT_WINDOW = 5
752
+
753
+ # Pre/post event windows for scenario context (calendar days).
754
+ SCENARIO_PRE_WINDOW_DAYS = 63
755
+ SCENARIO_POST_WINDOW_DAYS = 63
756
+
757
+ # ---------------------------------------------------------------------------
758
+ # News collection (Layer 1 -- collect_news.py, Step 10)
759
+ # ---------------------------------------------------------------------------
760
+ NEWS_WORKERS = 4 # ThreadPoolExecutor parallelism for yfinance news
761
+ NEWS_PER_TICKER_COUNT = 50 # articles per ticker per tab (news / press releases)
762
+ NEWS_SCENARIO_LIMIT = 10 # Firecrawl results per scenario event
763
+ NEWS_RATE_LIMIT_SEC = 1.0 # seconds between API calls
764
+
765
+ # ---------------------------------------------------------------------------
766
+ # Synthetic property generation (agents/synthetic_re/)
767
+ # ---------------------------------------------------------------------------
768
+ COMMERCIAL_RE_TYPES = ["Office", "Retail", "Industrial", "Mixed-Use"]
769
+ COMMERCIAL_RE_SEED_LIMIT = 20 # Firecrawl results per type per metro
770
+
771
+ # ---------------------------------------------------------------------------
772
+ # Valuation (agents/valuation/)
773
+ # ---------------------------------------------------------------------------
774
+ VALUATION_DIR = DATA_DIR / "valuation"
775
+
776
+ # DCF parameters
777
+ DCF_PROJECTION_YEARS = 5
778
+ DCF_TERMINAL_GROWTH_DEFAULT = 0.025 # 2.5% long-term GDP growth
779
+ MARKET_RISK_PREMIUM = 0.06 # 6% historical equity risk premium
780
+ BETA_LOOKBACK_DAYS = 252 # 1 year of trading days for rolling beta
781
+
782
+ # Comparable company analysis
783
+ COMPS_MAX_PEERS = 10
784
+ COMPS_MARKET_CAP_BAND = 0.5 # +/- 50 % for peer filtering by size
785
+
786
+ # Valuation benchmark
787
+ VALUATION_BENCHMARK_TASKS = [
788
+ "valuation_accuracy", # Task A: estimate intrinsic value
789
+ "statement_generation", # Task B: generate plausible financials
790
+ "scenario_forecast", # Task C: forecast impact of what-if
791
+ ]
792
+ VALUATION_HOLDOUT_RATIO = 0.3 # 30 % of tickers held out for eval (Hwang: 50/50 or 70/30)
793
+
794
+ # ---------------------------------------------------------------------------
795
+ # XBRL collection & ontology (Layer 1 -- collected via collect_filings.py)
796
+ # ---------------------------------------------------------------------------
797
+ # SEC XBRL API base URL (no auth, just User-Agent required)
798
+ XBRL_COMPANY_FACTS_URL = "https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json"
799
+ XBRL_WORKERS = 8 # asyncio.Semaphore concurrency
800
+ XBRL_RATE_LIMIT_SEC = 0.12 # seconds between requests (≤10 req/s SEC limit)
801
+ # Filing forms to include in ontology extraction.
802
+ # Policy: include EVERY form on which SEC accepts XBRL facts from our universe
803
+ # (enumerated from raw responses — 37 distinct forms). Do not gate the
804
+ # benchmark by form type: the parser keeps everything SEC deems a valid
805
+ # XBRL-bearing filing, and downstream preprocessing picks the latest value
806
+ # per (ticker, tag, unit) regardless of form.
807
+ XBRL_FORMS: list[str] = [
808
+ # US domestic periodic statements
809
+ "10-K", "10-K/A", "10-Q", "10-Q/A",
810
+ "10-KT", "10-KT/A", "10-QT", # fiscal-year transition period filings
811
+ # Foreign private issuer periodic (file US-GAAP or IFRS via these)
812
+ "20-F", "20-F/A", "40-F", "40-F/A", "6-K", "6-K/A",
813
+ # Current / event reports (earnings releases often carry full financials)
814
+ "8-K", "8-K/A",
815
+ # Registration statements — IPO, shelf, M&A, employee plans
816
+ "S-1", "S-1/A", "S-1MEF",
817
+ "F-1/A", "F-1MEF",
818
+ "S-3", "S-3ASR",
819
+ "S-4", "S-4/A",
820
+ "S-8",
821
+ "POS AM",
822
+ # Investment company filings (cef / invest taxonomy)
823
+ "N-CSR", "N-2",
824
+ # Prospectus supplements
825
+ "424B2", "424B5", "424B7",
826
+ # Proxy statements
827
+ "DEF 14A", "PRE 14A", "DEFR14A", "DEFC14A", "PREM14A",
828
+ # Tender offers
829
+ "SC TO-I",
830
+ ]
831
+ # Ontology classification thresholds (fraction of companies in an industry)
832
+ XBRL_CORE_THRESHOLD = 0.70 # tag appears in ≥70% → core
833
+ XBRL_COMMON_THRESHOLD = 0.30 # tag appears in ≥30% → common (else extension)
code/dataloader/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MacroLens dataloader: canonical sample budgets + index generators.
2
+
3
+ Sits between the immutable benchmark artifacts (`data_small_caps/benchmark/`)
4
+ and the family runners (`baselines/`). Owns:
5
+
6
+ - `budgets.EVAL_N_PER_TASK`, `budgets.TRAIN_N_PER_TASK`, `budgets.SEED`:
7
+ the canonical sample budgets per task. Single source of truth.
8
+ - `canonical_indices.get_canonical_indices(task, split)`: deterministic,
9
+ stratified index generator with on-disk cache. Same indices for every
10
+ method, so cross-method comparison on each task is fair.
11
+
12
+ Cache layout: `experiments/cache/canonical_indices/<key>/<split>_<task>.parquet`
13
+ where `<key>` encodes (n_eval, n_train, seed, stratifier_version).
14
+ Changing any cache-key dimension produces a new cache directory; the
15
+ immutable benchmark artifacts under `data_small_caps/` are NEVER touched
16
+ (the cache lives experiment-side, not in the dataset tree).
17
+ """
18
+
19
+ from .budgets import (
20
+ EVAL_N_PER_TASK,
21
+ TRAIN_N_PER_TASK,
22
+ SEED,
23
+ STRATIFIER_VERSION,
24
+ cache_key,
25
+ )
26
+ from .canonical_indices import get_canonical_indices, build_all
27
+
28
+ __all__ = [
29
+ "EVAL_N_PER_TASK",
30
+ "TRAIN_N_PER_TASK",
31
+ "SEED",
32
+ "STRATIFIER_VERSION",
33
+ "cache_key",
34
+ "get_canonical_indices",
35
+ "build_all",
36
+ ]
code/dataloader/_ablation.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Feature-group filter for the 5-step context ablation (A--E).
2
+
3
+ The ablation isolates the marginal value of each context source on the
4
+ panel-best LLM. Settings nest:
5
+
6
+ A: OHLCV only
7
+ B: A + Fundamentals (XBRL stmt_* + derived_* + shares_outstanding + fullTimeEmployees)
8
+ C: B + Macro (fred_* + eia_*)
9
+ D: C + Scenario flags (days_since_filing, filing_8k_count_30d,
10
+ news_count_7d, has_press_release_7d)
11
+ E: D + Filing text (handled in the LLM prompt; numeric features
12
+ identical to D)
13
+
14
+ Only the LLM ablation runs use this filter; classical / sequence / TSFM
15
+ methods always see the full feature set in the main panel results.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ ABLATION_SETTINGS: tuple[str, ...] = ("A", "B", "C", "D", "E")
24
+
25
+ OHLCV: tuple[str, ...] = (
26
+ "open", "high", "low", "close", "volume", "adj_close",
27
+ )
28
+
29
+ # Static fundamentals not following a prefix
30
+ _STATIC_FUNDAMENTALS: tuple[str, ...] = (
31
+ "shares_outstanding", "fullTimeEmployees",
32
+ )
33
+
34
+ # Scenario / event flags (proxy for macro-event signal in the panel;
35
+ # the broader 1,130-event scenario layer enters via the prompt for T4
36
+ # and via news/8K density features here).
37
+ SCENARIO_FLAGS: tuple[str, ...] = (
38
+ "days_since_filing",
39
+ "filing_8k_count_30d",
40
+ "news_count_7d",
41
+ "has_press_release_7d",
42
+ )
43
+
44
+
45
+ def _is_fundamentals(name: str) -> bool:
46
+ return (
47
+ name.startswith("stmt_")
48
+ or name.startswith("derived_")
49
+ or name in _STATIC_FUNDAMENTALS
50
+ )
51
+
52
+
53
+ def _is_macro(name: str) -> bool:
54
+ return name.startswith("fred_") or name.startswith("eia_")
55
+
56
+
57
+ def _is_scenario(name: str) -> bool:
58
+ return name in SCENARIO_FLAGS
59
+
60
+
61
+ def column_mask(feature_names: list[str], setting: str) -> list[bool]:
62
+ """Return a per-column bool mask for the requested setting.
63
+
64
+ The mask is over ``feature_names``; elements set to True are KEPT.
65
+ """
66
+ if setting not in ABLATION_SETTINGS:
67
+ raise ValueError(
68
+ f"setting must be one of {ABLATION_SETTINGS}, got {setting!r}"
69
+ )
70
+
71
+ keep: list[bool] = []
72
+ for n in feature_names:
73
+ if n in OHLCV:
74
+ keep.append(True)
75
+ continue
76
+ if setting == "A":
77
+ keep.append(False)
78
+ continue
79
+ if _is_fundamentals(n):
80
+ keep.append(True)
81
+ continue
82
+ if setting == "B":
83
+ keep.append(False)
84
+ continue
85
+ if _is_macro(n):
86
+ keep.append(True)
87
+ continue
88
+ if setting == "C":
89
+ keep.append(False)
90
+ continue
91
+ if _is_scenario(n):
92
+ keep.append(True)
93
+ continue
94
+ # setting D or E: keep nothing else (unknown columns excluded)
95
+ keep.append(False)
96
+ return keep
97
+
98
+
99
+ def filter_columns(
100
+ feature_names: list[str], setting: str,
101
+ ) -> list[str]:
102
+ """Return the kept feature names for ``setting``."""
103
+ mask = column_mask(feature_names, setting)
104
+ return [n for n, k in zip(feature_names, mask) if k]
105
+
106
+
107
+ def apply_to_t1_array(
108
+ X: np.ndarray, feature_names: list[str], setting: str,
109
+ ) -> tuple[np.ndarray, list[str]]:
110
+ """Filter T1 ``(N, L, F)`` array to the columns of ``setting``."""
111
+ if X.ndim != 3:
112
+ raise ValueError(f"T1 X must be 3D (N,L,F); got shape={X.shape}")
113
+ if X.shape[2] != len(feature_names):
114
+ raise ValueError(
115
+ f"T1 X feature dim {X.shape[2]} != len(feature_names) "
116
+ f"{len(feature_names)}"
117
+ )
118
+ mask = column_mask(feature_names, setting)
119
+ keep_idx = [i for i, k in enumerate(mask) if k]
120
+ if not keep_idx:
121
+ raise RuntimeError(
122
+ f"setting={setting!r} produced 0 kept columns from "
123
+ f"{len(feature_names)} features"
124
+ )
125
+ new_X = X[:, :, keep_idx].astype(X.dtype, copy=False)
126
+ new_names = [feature_names[i] for i in keep_idx]
127
+ return new_X, new_names
128
+
129
+
130
+ def apply_to_dataframe(
131
+ X: pd.DataFrame, setting: str, *, lookback_cell_col: str | None = None,
132
+ ) -> pd.DataFrame:
133
+ """Filter a 2D DataFrame to the columns of ``setting``.
134
+
135
+ For T4 the dataframe carries a ``lookback`` cell column whose values
136
+ are ``(L, F)`` numpy arrays; pass ``lookback_cell_col`` so we can also
137
+ project the cell-arrays to the same column subset. The prefix-based
138
+ test on the dataframe's own columns still runs for any side-by-side
139
+ numeric columns.
140
+ """
141
+ df = X.copy()
142
+
143
+ if lookback_cell_col and lookback_cell_col in df.columns:
144
+ # The (L, F) arrays in this column do not carry their feature
145
+ # names with them. Trust meta.attrs["feature_names"]; resolve at
146
+ # the call site that has access to it. This branch is wired
147
+ # through ``apply_to_loaded`` below.
148
+ pass
149
+
150
+ # Project numeric columns if any exist
151
+ keep = []
152
+ for c in df.columns:
153
+ if c in OHLCV:
154
+ keep.append(c)
155
+ continue
156
+ if setting == "A":
157
+ continue
158
+ if _is_fundamentals(c):
159
+ keep.append(c)
160
+ continue
161
+ if setting == "B":
162
+ continue
163
+ if _is_macro(c):
164
+ keep.append(c)
165
+ continue
166
+ if setting == "C":
167
+ continue
168
+ if _is_scenario(c):
169
+ keep.append(c)
170
+ continue
171
+ # Always preserve non-feature object cols (sector dummies, text fields
172
+ # that the method may consume) by keeping any column that has no
173
+ # known prefix and is not numeric.
174
+ extra = [c for c in df.columns if c not in keep and df[c].dtype == object]
175
+ return df[keep + extra]
176
+
177
+
178
+ def apply_to_loaded(
179
+ loaded: "Any", setting: str, # type: ignore[name-defined]
180
+ ): # -> LoadedData
181
+ """Filter a ``LoadedData`` tuple in-place semantics; returns a new tuple.
182
+
183
+ Handles the four ablation tasks:
184
+ T1: 3D ndarray (N, L, F) -- mask axis 2
185
+ T2 / T5: 2D DataFrame -- drop columns
186
+ T4: DataFrame with `lookback` cell column -- project each cell
187
+ """
188
+ from typing import NamedTuple
189
+ X, y, meta = loaded
190
+
191
+ feat_names = list(meta.attrs.get("feature_names") or [])
192
+ task = meta.attrs.get("task")
193
+
194
+ if task == "T1":
195
+ new_X, new_names = apply_to_t1_array(X, feat_names, setting)
196
+ new_meta = meta.copy()
197
+ new_meta.attrs.update(meta.attrs)
198
+ new_meta.attrs["feature_names"] = new_names
199
+ new_meta.attrs["ablation_setting"] = setting
200
+ return type(loaded)(new_X, y, new_meta)
201
+
202
+ if task in ("T2", "T5"):
203
+ if not isinstance(X, pd.DataFrame):
204
+ raise TypeError(f"T2/T5 X expected DataFrame, got {type(X)}")
205
+ new_X = apply_to_dataframe(X, setting)
206
+ new_meta = meta.copy()
207
+ new_meta.attrs.update(meta.attrs)
208
+ new_meta.attrs["feature_names"] = list(new_X.columns)
209
+ new_meta.attrs["ablation_setting"] = setting
210
+ return type(loaded)(new_X, y, new_meta)
211
+
212
+ if task == "T4":
213
+ if not isinstance(X, pd.DataFrame):
214
+ raise TypeError(f"T4 X expected DataFrame, got {type(X)}")
215
+ if not feat_names:
216
+ raise RuntimeError(
217
+ "T4 ablation requires meta.attrs['feature_names'] to be "
218
+ "set by the loader; was None/empty."
219
+ )
220
+ mask = column_mask(feat_names, setting)
221
+ keep_idx = [i for i, k in enumerate(mask) if k]
222
+ new_X = X.copy()
223
+ if "lookback" in new_X.columns:
224
+ def _project(arr):
225
+ if arr is None:
226
+ return arr
227
+ if hasattr(arr, "shape") and arr.ndim == 2:
228
+ return arr[:, keep_idx]
229
+ return arr
230
+ new_X["lookback"] = new_X["lookback"].apply(_project)
231
+ new_meta = meta.copy()
232
+ new_meta.attrs.update(meta.attrs)
233
+ new_meta.attrs["feature_names"] = [feat_names[i] for i in keep_idx]
234
+ new_meta.attrs["ablation_setting"] = setting
235
+ return type(loaded)(new_X, y, new_meta)
236
+
237
+ raise ValueError(
238
+ f"Ablation not supported for task={task!r}; "
239
+ "ABLATION_TASKS = (T1, T2, T4, T5)"
240
+ )
code/dataloader/_provenance.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SHA256 helpers for canonical-indices cache invalidation + result-record
2
+ provenance. Computing the digest of every upstream parquet a loader reads,
3
+ embedded into ``meta.attrs["data_sha256"]``, makes silent dataset drift
4
+ detectable: if a panel parquet mutates, the canonical-indices cache key
5
+ changes and any downstream ``RunRecord`` carries a different hash.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ from pathlib import Path
12
+
13
+
14
+ _BUF_SIZE = 1 << 20 # 1 MB
15
+
16
+
17
+ def sha256_file(path: str | Path) -> str:
18
+ """Return the hex SHA-256 of ``path`` (full file)."""
19
+ p = Path(path)
20
+ if not p.exists():
21
+ raise FileNotFoundError(f"sha256_file: {p} does not exist")
22
+ h = hashlib.sha256()
23
+ with p.open("rb") as fh:
24
+ while chunk := fh.read(_BUF_SIZE):
25
+ h.update(chunk)
26
+ return h.hexdigest()
27
+
28
+
29
+ def sha256_dataset(paths: list[str | Path]) -> dict[str, str]:
30
+ """Return ``{path_str: sha256}`` for every existing path in ``paths``."""
31
+ return {str(Path(p)): sha256_file(p) for p in paths}
32
+
33
+
34
+ def sha256_combined(paths: list[str | Path]) -> str:
35
+ """Return a single hex digest combining every file in ``paths``.
36
+
37
+ Used as a cache-key suffix for canonical-indices: if ANY upstream
38
+ parquet mutates, the suffix changes and the cache regenerates.
39
+ """
40
+ h = hashlib.sha256()
41
+ for p in sorted(str(Path(x)) for x in paths):
42
+ sub = sha256_file(p).encode()
43
+ h.update(p.encode() + b":" + sub + b"\n")
44
+ return h.hexdigest()[:16]
code/dataloader/budgets.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical sample budgets per task.
2
+
3
+ Single source of truth. Every family runner reads from here so that
4
+ cross-method comparison on each task is fair (same N for every method,
5
+ same instances, same indices).
6
+
7
+ Normalization principle:
8
+ - Forecasting / regression-with-subsample tasks (T1, T4, T7):
9
+ N_eval = 1,000 / N_train = 10,000 (stratified subsample from larger pools)
10
+ - Ticker-holdout valuation tasks (T2, T5):
11
+ N_eval = 1,324 / N_train = 2,673 (full 30% holdout, no subsampling)
12
+ - Filing-level generation tasks (T3, T6):
13
+ N_eval = 1,058 (some holdout tickers lack complete XBRL); train varies
14
+
15
+ Sample sizes are intentionally conservative -- ~10x the median peer-benchmark
16
+ scale (CiK 125 / WIT 446 / EDINET 350 / SciTS 1,250) so reviewers cannot
17
+ claim small-sample noise, while keeping LLM eval (4 LLMs x 7 tasks x ~1K
18
+ samples = ~28K calls) tractable on 4xA100 within the wall-clock budget.
19
+
20
+ The values here are DEFAULTS; runners may override via the
21
+ `get_canonical_indices(task, split, n_eval=..., n_train=...)` keyword
22
+ arguments to regenerate (and re-cache) for a re-tune without rebuilding
23
+ any artifacts.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from typing import Literal
29
+
30
+
31
+ Task = Literal["T1", "T2", "T3", "T4", "T5", "T6", "T7"]
32
+
33
+
34
+ # ── Canonical budgets ─────────────────────────────────────────────────────
35
+
36
+ EVAL_N_PER_TASK: dict[Task, int] = {
37
+ "T1": 1_000, # subsampled (full ~1.3M)
38
+ "T2": 1_324, # full 30% ticker holdout
39
+ "T3": 1_058, # filing-level holdout (subset of 1,324 with full XBRL)
40
+ "T4": 1_000, # subsampled (full ~3M scenario-ticker pairs)
41
+ "T5": 1_324, # full 30% ticker holdout
42
+ "T6": 1_058, # filing-level holdout
43
+ "T7": 1_000, # subsampled (full ~23K properties)
44
+ }
45
+
46
+ TRAIN_N_PER_TASK: dict[Task, int] = {
47
+ "T1": 10_000, # subsampled training windows, sector x mcap_q
48
+ "T2": 2_673, # latest snapshot per non-holdout ticker
49
+ "T3": 9_458, # prior fiscal years across non-holdout tickers
50
+ "T4": 10_000, # subsampled scenario-conditioned windows
51
+ "T5": 2_673, # latest snapshot per non-holdout ticker
52
+ "T6": 1_377, # prior fiscal years for filing-level holdout
53
+ "T7": 10_000, # subsampled training properties, property_type x state
54
+ }
55
+
56
+
57
+ # ── Seed + stratifier ─────────────────────────────────────────────────────
58
+
59
+ SEED: int = 42
60
+
61
+ # Bumped if the stratifier logic changes (forces cache invalidation
62
+ # without changing N values). Increment when:
63
+ # - the panel column used for stratification changes
64
+ # - the per-task stratifier columns change
65
+ # - the sampler's tie-breaking / fallback logic changes
66
+ STRATIFIER_VERSION: int = 1
67
+
68
+
69
+ # ── Cache key derivation ──────────────────────────────────────────────────
70
+
71
+ def cache_key(
72
+ *,
73
+ n_eval: dict[Task, int] | None = None,
74
+ n_train: dict[Task, int] | None = None,
75
+ seed: int | None = None,
76
+ stratifier_version: int | None = None,
77
+ ) -> str:
78
+ """Stable cache-directory name for the (budgets, seed, stratifier) tuple.
79
+
80
+ Defaults to the module-level canonical values. Override any subset to
81
+ generate a non-canonical cache (e.g. a re-tune at N_eval=2000 produces
82
+ its own cache dir leaving the canonical cache intact).
83
+ """
84
+ ne = n_eval or EVAL_N_PER_TASK
85
+ nt = n_train or TRAIN_N_PER_TASK
86
+ s = SEED if seed is None else seed
87
+ sv = STRATIFIER_VERSION if stratifier_version is None else stratifier_version
88
+
89
+ # Compact, readable encoding -- avoids sha hashes so the directory
90
+ # contents are inspectable.
91
+ eval_str = "-".join(f"{t}={ne[t]}" for t in ("T1", "T2", "T3", "T4", "T5", "T6", "T7"))
92
+ train_str = "-".join(f"{t}={nt[t]}" for t in ("T1", "T2", "T3", "T4", "T5", "T6", "T7"))
93
+ return f"seed={s}_strat=v{sv}_eval[{eval_str}]_train[{train_str}]"
code/dataloader/canonical_indices.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical-indices generator.
2
+
3
+ Reads the immutable benchmark artifacts and produces deterministic,
4
+ stratified train/eval index lists per task. Every family runner reads
5
+ from here so cross-method comparison is fair: same N, same instances,
6
+ same indices.
7
+
8
+ The cache lives under `experiments/cache/canonical_indices/<key>/`
9
+ where `<key>` encodes (n_eval, n_train, seed, stratifier_version) -- so
10
+ changing any sample-budget parameter produces a new cache directory.
11
+ The cache is an experiment-side speed optimisation; the canonical
12
+ dataset tree under `data_small_caps/` contains only raw and derived
13
+ benchmark artifacts (which are immutable).
14
+
15
+ Per-task stratification:
16
+ T1 (TSF): sector x market_cap_quartile -> (ticker, anchor_date)
17
+ T2 (Val-PT): full 30% ticker holdout -> (ticker, date)
18
+ T3 (Stmt-Gen): per-(ticker, fiscal_year) holdout -> (ticker, fiscal_year)
19
+ T4 (Scen-Ret): sector x mcap_q x event_type -> (scenario_id, ticker)
20
+ T5 (Val-Priv): full 30% ticker holdout -> (ticker, date)
21
+ T6 (Gen-Eval): per-(ticker, fiscal_year) holdout -> (ticker, fiscal_year)
22
+ T7 (RE-Val): property_type x state -> address
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ from pathlib import Path
29
+ from typing import Literal
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+
34
+ from .. import config
35
+ from . import budgets
36
+ from .budgets import EVAL_N_PER_TASK, TRAIN_N_PER_TASK, SEED, Task
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+
41
+ Split = Literal["train", "eval"]
42
+
43
+
44
+ def _cfg_get_lookback(granularity: str) -> int:
45
+ """Return the canonical (shortest) lookback for ``granularity``."""
46
+ return config.get_lookback_windows(granularity)[0] if hasattr(config, "get_lookback_windows") else 63
47
+
48
+
49
+ def _provenance_suffix(granularity: str) -> str:
50
+ """16-char SHA-256-derived suffix encoding the relevant benchmark
51
+ parquets for ``granularity``. Mutating any of those parquets changes
52
+ the cache key, forcing canonical-indices regeneration.
53
+ """
54
+ from ._provenance import sha256_combined
55
+
56
+ bench_dir = config.get_benchmark_dir(granularity)
57
+ candidates = [
58
+ bench_dir / "panel_train.parquet",
59
+ bench_dir / "panel_test.parquet",
60
+ bench_dir / "valuation_inputs.parquet",
61
+ bench_dir / "valuation_ground_truth.parquet",
62
+ bench_dir / "private_valuation_inputs.parquet",
63
+ bench_dir / "private_valuation_ground_truth.parquet",
64
+ bench_dir / "generation_inputs.parquet",
65
+ bench_dir / "generation_ground_truth.parquet",
66
+ bench_dir / "generator_eval_inputs.parquet",
67
+ bench_dir / "generator_eval_ground_truth.parquet",
68
+ bench_dir / "scenario_forecast_ground_truth.parquet",
69
+ bench_dir / "scenarios.parquet",
70
+ bench_dir / "re_train_properties.parquet",
71
+ bench_dir / "re_eval_inputs.parquet",
72
+ bench_dir / "re_eval_ground_truth.parquet",
73
+ ]
74
+ existing = [p for p in candidates if p.exists()]
75
+ if not existing:
76
+ return "noprov"
77
+ return sha256_combined(existing)
78
+
79
+
80
+ def _cache_dir(granularity: str, key: str | None = None) -> Path:
81
+ """Return the cache directory for a given budget key.
82
+
83
+ Lives under ``experiments/cache/canonical_indices/`` (experiment-side
84
+ speed optimisation, regenerable on miss). The canonical dataset tree
85
+ under ``data_small_caps/`` contains only raw and derived benchmark
86
+ artifacts; experiment-side caches NEVER live there.
87
+
88
+ The cache key suffix encodes (i) a SHA-256 over the benchmark
89
+ parquets and (ii) the current ``max(lookback)`` and ``max(horizon)``
90
+ for ``granularity``. Either upstream-data drift or a horizon/lookback
91
+ config change atomically invalidates the cache.
92
+ """
93
+ k = key or budgets.cache_key()
94
+ suffix = _provenance_suffix(granularity)
95
+ max_lb = max(config.get_lookback_windows(granularity))
96
+ max_h = max(config.get_horizons(granularity))
97
+ # Resolve experiments/ as a sibling of dataloader/ (this file lives
98
+ # at projects/.../whatif_bench/dataloader/canonical_indices.py).
99
+ experiments_dir = Path(__file__).resolve().parents[1] / "experiments"
100
+ return (
101
+ experiments_dir
102
+ / "cache"
103
+ / "canonical_indices"
104
+ / granularity
105
+ / f"{k}_prov={suffix}_lb={max_lb}_h={max_h}"
106
+ )
107
+
108
+
109
+ def _stratified_sample(
110
+ df: pd.DataFrame,
111
+ n: int,
112
+ strata_cols: list[str],
113
+ seed: int,
114
+ ) -> pd.DataFrame:
115
+ """Stratified subsample of `df` to size `n`, preserving the joint
116
+ distribution of `strata_cols` (Cartesian-product strata, with
117
+ proportional allocation and remainder spread by row order).
118
+
119
+ Deterministic at fixed `seed`. If `n >= len(df)`, returns df shuffled.
120
+ """
121
+ if n >= len(df):
122
+ return df.sample(frac=1.0, random_state=seed).reset_index(drop=True)
123
+
124
+ # Drop rows with NaN in any stratifier column -- they would form a
125
+ # spurious "missing" stratum.
126
+ valid_mask = df[strata_cols].notna().all(axis=1)
127
+ df_valid = df[valid_mask].copy()
128
+ if df_valid.empty:
129
+ # Fall back to uniform random
130
+ return df.sample(n=n, random_state=seed).reset_index(drop=True)
131
+
132
+ df_valid["_stratum"] = df_valid[strata_cols].astype(str).agg("|".join, axis=1)
133
+
134
+ rng = np.random.RandomState(seed)
135
+ out_rows: list[pd.DataFrame] = []
136
+ total = len(df_valid)
137
+
138
+ for stratum, grp in df_valid.groupby("_stratum"):
139
+ # Proportional allocation; at least 1 if stratum has rows.
140
+ q = max(1, round(len(grp) * n / total))
141
+ q = min(q, len(grp))
142
+ out_rows.append(grp.sample(n=q, random_state=rng.randint(0, 2**31 - 1)))
143
+
144
+ out = pd.concat(out_rows, ignore_index=True)
145
+ # Trim or top-up to exactly n
146
+ if len(out) > n:
147
+ out = out.sample(n=n, random_state=seed).reset_index(drop=True)
148
+ elif len(out) < n:
149
+ # Top up with non-selected rows (still stratified by selection above)
150
+ remaining = df_valid.loc[~df_valid.index.isin(out.index)]
151
+ extra = remaining.sample(n=min(n - len(out), len(remaining)), random_state=seed)
152
+ out = pd.concat([out, extra], ignore_index=True)
153
+
154
+ return out.drop(columns=["_stratum"]).reset_index(drop=True)
155
+
156
+
157
+ # ── Per-task generators ───────────────────────────────────────────────────
158
+
159
+
160
+ def _gen_t1(
161
+ granularity: str,
162
+ n_eval: int,
163
+ n_train: int,
164
+ seed: int,
165
+ ) -> dict[Split, pd.DataFrame]:
166
+ """T1 TSF: stratified by sector x market_cap_quartile.
167
+
168
+ Each (ticker, anchor_date) pair must admit a complete
169
+ ``(lookback, max_horizon)`` window inside the corresponding split's panel,
170
+ so every horizon evaluated by every T1 runner reuses the same anchor set.
171
+ Concretely, for a ticker with ``T`` panel rows we keep only anchor dates
172
+ at per-ticker positions ``[lookback, T - max_horizon - 1]``.
173
+
174
+ Returns DataFrames with columns (ticker, anchor_date, sector, mcap_q).
175
+ """
176
+ from .. import config as _cfg
177
+
178
+ # Build the canonical anchor pool against the SHORTEST lookback and
179
+ # the LONGEST horizon. The test panel (post-2024-09-03) is ~378
180
+ # trading days; pairing max_lookback (252) with max_horizon (252)
181
+ # exhausts it. Methods that want a longer lookback can request it
182
+ # at load time (load(..., lookback=252)); anchors with insufficient
183
+ # history will be dropped by _build_t1_x_y and counted in
184
+ # ``meta.attrs["n_canonical_dropped"]``.
185
+ lookback = _cfg.get_lookback_windows(granularity)[0]
186
+ max_horizon = max(_cfg.get_horizons(granularity))
187
+
188
+ bench_dir = config.get_benchmark_dir(granularity)
189
+ train = pd.read_parquet(
190
+ bench_dir / "panel_train.parquet",
191
+ columns=["ticker", "date", "sector", "derived_market_cap"],
192
+ )
193
+ test = pd.read_parquet(
194
+ bench_dir / "panel_test.parquet",
195
+ columns=["ticker", "date", "sector", "derived_market_cap"],
196
+ )
197
+
198
+ # Latest market_cap per ticker for the quartile assignment (across the
199
+ # full panel, so train and eval split on the same definition).
200
+ latest = (
201
+ pd.concat([train, test], ignore_index=True)
202
+ .sort_values("date")
203
+ .groupby("ticker")
204
+ .tail(1)[["ticker", "derived_market_cap"]]
205
+ )
206
+ latest["mcap_q"] = pd.qcut(
207
+ latest["derived_market_cap"].clip(lower=1),
208
+ 4, labels=["Q1", "Q2", "Q3", "Q4"], duplicates="drop",
209
+ )
210
+ mcap_q = dict(zip(latest["ticker"], latest["mcap_q"]))
211
+
212
+ def _restrict_to_valid_anchors(df: pd.DataFrame) -> pd.DataFrame:
213
+ """Keep only rows at per-ticker positions [lookback, T-max_horizon-1]
214
+ so a complete (lookback + max_horizon) window fits."""
215
+ df = df.sort_values(["ticker", "date"]).reset_index(drop=True)
216
+ df["_row_in_ticker"] = df.groupby("ticker", sort=False).cumcount()
217
+ df["_ticker_len"] = df.groupby("ticker", sort=False)["date"].transform("size")
218
+ valid = (df["_row_in_ticker"] >= lookback) & (
219
+ df["_row_in_ticker"] < df["_ticker_len"] - max_horizon
220
+ )
221
+ return df.loc[valid].drop(columns=["_row_in_ticker", "_ticker_len"])
222
+
223
+ out: dict[Split, pd.DataFrame] = {}
224
+ for split, df in (("train", train), ("eval", test)):
225
+ df = _restrict_to_valid_anchors(df)
226
+ df = df.rename(columns={"date": "anchor_date"}).copy()
227
+ df["mcap_q"] = df["ticker"].map(mcap_q)
228
+ n = n_train if split == "train" else n_eval
229
+ sampled = _stratified_sample(df, n, ["sector", "mcap_q"], seed)
230
+ out[split] = sampled[["ticker", "anchor_date", "sector", "mcap_q"]]
231
+ return out
232
+
233
+
234
+ def _gen_t2_t5(
235
+ granularity: str,
236
+ task: str,
237
+ n_eval: int,
238
+ n_train: int,
239
+ seed: int,
240
+ ) -> dict[Split, pd.DataFrame]:
241
+ """T2 (Val-PT) and T5 (Val-Priv): full 30% ticker holdout for eval;
242
+ latest snapshot per non-holdout ticker for train.
243
+
244
+ Returns DataFrames with columns (ticker, date).
245
+ """
246
+ bench_dir = config.get_benchmark_dir(granularity)
247
+ if task == "T2":
248
+ inputs_path = bench_dir / "valuation_inputs.parquet"
249
+ gt_path = bench_dir / "valuation_ground_truth.parquet"
250
+ else:
251
+ inputs_path = bench_dir / "private_valuation_inputs.parquet"
252
+ gt_path = bench_dir / "private_valuation_ground_truth.parquet"
253
+ inputs = pd.read_parquet(inputs_path, columns=["ticker", "date", "sector"])
254
+ gt = pd.read_parquet(gt_path, columns=["ticker", "date"])
255
+
256
+ # Restrict the eval pool to (ticker, date) pairs that are present in
257
+ # BOTH inputs and gt. Without this, ~21 quarter-end snapshots per
258
+ # task have inputs but no gt (close or shares_outstanding missing
259
+ # on that date), and the loader silently dropped them at merge
260
+ # time so canonical-eval N came up short of the budget.
261
+ inputs["date"] = pd.to_datetime(inputs["date"])
262
+ gt["date"] = pd.to_datetime(gt["date"])
263
+ eval_pool = inputs.merge(gt, on=["ticker", "date"], how="inner")
264
+
265
+ train_panel = pd.read_parquet(
266
+ bench_dir / "panel_train.parquet",
267
+ columns=["ticker", "date", "sector"],
268
+ )
269
+
270
+ holdout_tickers = set(inputs["ticker"].unique())
271
+ non_holdout = train_panel[~train_panel["ticker"].isin(holdout_tickers)]
272
+ # Latest snapshot per non-holdout ticker as the train set.
273
+ train_latest = (
274
+ non_holdout.sort_values("date").groupby("ticker").tail(1)
275
+ .reset_index(drop=True)
276
+ )
277
+
278
+ rng = np.random.RandomState(seed)
279
+ train_idx = train_latest.sample(
280
+ n=min(n_train, len(train_latest)), random_state=rng.randint(0, 2**31 - 1),
281
+ ).reset_index(drop=True)
282
+
283
+ eval_idx = eval_pool.sample(
284
+ n=min(n_eval, len(eval_pool)), random_state=rng.randint(0, 2**31 - 1),
285
+ ).reset_index(drop=True)
286
+
287
+ return {"train": train_idx, "eval": eval_idx}
288
+
289
+
290
+ def _gen_t3_t6(
291
+ granularity: str,
292
+ task: str,
293
+ n_eval: int,
294
+ n_train: int,
295
+ seed: int,
296
+ ) -> dict[Split, pd.DataFrame]:
297
+ """T3 (Stmt-Gen) and T6 (Gen-Eval): per-(ticker, fiscal_year) split.
298
+
299
+ Every ticker in the per-task ground-truth file is also in the
300
+ holdout (`*_inputs.parquet` lists holdout tickers only), so a
301
+ plain ``~ticker.isin(holdout)`` train pool would always be empty.
302
+ Instead: per ticker, the **latest** fiscal year is the eval anchor
303
+ and **earlier** fiscal years are train anchors. Train-eval are
304
+ cleanly separated by fiscal year within ticker; both pools are
305
+ non-empty as long as a ticker has >=2 reported fiscal years.
306
+
307
+ Eval = unique (ticker, latest_fiscal_year) pairs across all tickers.
308
+ Train = unique (ticker, prior_fiscal_year) pairs across all tickers.
309
+ """
310
+ bench_dir = config.get_benchmark_dir(granularity)
311
+ if task == "T3":
312
+ gt_path = bench_dir / "generation_ground_truth.parquet"
313
+ else:
314
+ gt_path = bench_dir / "generator_eval_ground_truth.parquet"
315
+
316
+ gt = pd.read_parquet(gt_path)
317
+ if "fiscal_year" not in gt.columns:
318
+ if "filing_date" in gt.columns:
319
+ gt["fiscal_year"] = pd.to_datetime(gt["filing_date"]).dt.year
320
+ else:
321
+ gt["fiscal_year"] = 0
322
+
323
+ pairs = gt[["ticker", "fiscal_year"]].drop_duplicates().reset_index(drop=True)
324
+ pairs["fiscal_year"] = pd.to_numeric(pairs["fiscal_year"], errors="coerce")
325
+ pairs = pairs.dropna(subset=["fiscal_year"]).copy()
326
+ pairs["fiscal_year"] = pairs["fiscal_year"].astype(int)
327
+
328
+ # Per-ticker: latest FY -> eval, earlier FYs -> train
329
+ pairs = pairs.sort_values(["ticker", "fiscal_year"]).reset_index(drop=True)
330
+ pairs["_rank_desc"] = pairs.groupby("ticker")["fiscal_year"].rank(
331
+ method="first", ascending=False,
332
+ )
333
+ eval_pairs = pairs[pairs["_rank_desc"] == 1][["ticker", "fiscal_year"]]
334
+ train_pairs = pairs[pairs["_rank_desc"] > 1][["ticker", "fiscal_year"]]
335
+
336
+ rng = np.random.RandomState(seed)
337
+ eval_idx = eval_pairs.sample(
338
+ n=min(n_eval, len(eval_pairs)), random_state=rng.randint(0, 2**31 - 1),
339
+ ).reset_index(drop=True)
340
+ train_idx = train_pairs.sample(
341
+ n=min(n_train, len(train_pairs)), random_state=rng.randint(0, 2**31 - 1),
342
+ ).reset_index(drop=True)
343
+
344
+ return {"train": train_idx, "eval": eval_idx}
345
+
346
+
347
+ def _gen_t4(
348
+ granularity: str,
349
+ n_eval: int,
350
+ n_train: int,
351
+ seed: int,
352
+ ) -> dict[Split, pd.DataFrame]:
353
+ """T4 Scen-Ret: stratified by sector x mcap_q x event_type.
354
+
355
+ Returns DataFrames with columns (scenario_id, ticker, event_type).
356
+ """
357
+ bench_dir = config.get_benchmark_dir(granularity)
358
+ gt = pd.read_parquet(
359
+ bench_dir / "scenario_forecast_ground_truth.parquet",
360
+ columns=["scenario_id", "ticker", "event_type", "event_date",
361
+ "actual_return_pct"],
362
+ )
363
+ gt = gt.dropna(subset=["actual_return_pct"])
364
+
365
+ # Use the panel-train cutoff as the train/eval split anchor (matches
366
+ # the canonical T1 split semantics).
367
+ panel_train_df = pd.read_parquet(
368
+ bench_dir / "panel_train.parquet", columns=["ticker", "date"],
369
+ )
370
+ panel_test_df = pd.read_parquet(
371
+ bench_dir / "panel_test.parquet", columns=["ticker", "date"],
372
+ )
373
+ panel_train_df["date"] = pd.to_datetime(panel_train_df["date"])
374
+ panel_test_df["date"] = pd.to_datetime(panel_test_df["date"])
375
+ split_date = panel_train_df["date"].max()
376
+ gt["event_date"] = pd.to_datetime(gt["event_date"])
377
+
378
+ # Restrict the eval/train pools to events whose ticker has at least
379
+ # ``min_history`` panel days BEFORE the event date in the combined
380
+ # panel. Without this filter, ~6.5% of train events sampled at the
381
+ # canonical step cannot produce a valid 63-day lookback at load
382
+ # time and were silently zero-padded then dropped.
383
+ min_history = max(_cfg_get_lookback(granularity), 63)
384
+ panel_full = pd.concat([panel_train_df, panel_test_df], ignore_index=True)
385
+ panel_full = panel_full.drop_duplicates(subset=["ticker", "date"])
386
+ panel_dates_per_ticker = (
387
+ panel_full.sort_values(["ticker", "date"]).groupby("ticker")["date"]
388
+ )
389
+ first_panel_date = panel_dates_per_ticker.first().to_dict()
390
+
391
+ def _has_lookback_history(row) -> bool:
392
+ first = first_panel_date.get(row["ticker"])
393
+ if first is None:
394
+ return False
395
+ # need at least min_history trading-day rows prior (use calendar
396
+ # days as a fast upper bound: 252 trading days ~ 365 calendar days).
397
+ return (row["event_date"] - first).days >= int(min_history * 1.45)
398
+
399
+ gt = gt[gt.apply(_has_lookback_history, axis=1)].copy()
400
+
401
+ train_pool = gt[gt["event_date"] <= split_date].copy()
402
+ eval_pool = gt[gt["event_date"] > split_date].copy()
403
+
404
+ # Sector and mcap_q come from the panel (across full date range).
405
+ full_panel = pd.read_parquet(
406
+ bench_dir / "panel_train.parquet",
407
+ columns=["ticker", "sector", "derived_market_cap"],
408
+ )
409
+ latest = full_panel.groupby("ticker").tail(1)[["ticker", "sector", "derived_market_cap"]]
410
+ latest["mcap_q"] = pd.qcut(
411
+ latest["derived_market_cap"].clip(lower=1),
412
+ 4, labels=["Q1", "Q2", "Q3", "Q4"], duplicates="drop",
413
+ )
414
+ sector_map = dict(zip(latest["ticker"], latest["sector"]))
415
+ mcap_map = dict(zip(latest["ticker"], latest["mcap_q"]))
416
+
417
+ out: dict[Split, pd.DataFrame] = {}
418
+ for split, pool in (("train", train_pool), ("eval", eval_pool)):
419
+ pool = pool.copy()
420
+ pool["sector"] = pool["ticker"].map(sector_map)
421
+ pool["mcap_q"] = pool["ticker"].map(mcap_map)
422
+ n = n_train if split == "train" else n_eval
423
+ sampled = _stratified_sample(
424
+ pool, n, ["sector", "mcap_q", "event_type"], seed,
425
+ )
426
+ out[split] = sampled[["scenario_id", "ticker", "event_type"]]
427
+ return out
428
+
429
+
430
+ def _gen_t7(
431
+ granularity: str,
432
+ n_eval: int,
433
+ n_train: int,
434
+ seed: int,
435
+ ) -> dict[Split, pd.DataFrame]:
436
+ """T7 RE-Val: stratified by property_type x state."""
437
+ bench_dir = config.get_benchmark_dir(granularity)
438
+ train = pd.read_parquet(bench_dir / "re_train_properties.parquet")
439
+ eval_in = pd.read_parquet(bench_dir / "re_eval_inputs.parquet")
440
+ # ``re_train_properties`` carries 854 duplicate-address rows from
441
+ # multiple RentCast variants of the same listing. Dedup BEFORE
442
+ # sampling so the canonical eval set has unique addresses (the
443
+ # loader otherwise dedups, leaving the canon n short of budget).
444
+ if "address" in train.columns:
445
+ train = train.drop_duplicates(subset="address", keep="first").reset_index(drop=True)
446
+ if "address" in eval_in.columns:
447
+ eval_in = eval_in.drop_duplicates(subset="address", keep="first").reset_index(drop=True)
448
+
449
+ def _sample(df: pd.DataFrame, n: int) -> pd.DataFrame:
450
+ ptype_col = next(
451
+ (c for c in ("property_type", "propertyType", "type") if c in df.columns),
452
+ None,
453
+ )
454
+ state_col = next(
455
+ (c for c in ("state", "State") if c in df.columns), None,
456
+ )
457
+ addr_col = next(
458
+ (c for c in ("address", "addressLine1", "Address") if c in df.columns),
459
+ None,
460
+ )
461
+ strata = [c for c in (ptype_col, state_col) if c is not None]
462
+ if not strata or addr_col is None:
463
+ return df.sample(n=min(n, len(df)), random_state=seed).reset_index(drop=True)
464
+ sampled = _stratified_sample(df, n, strata, seed)
465
+ cols_to_keep = [addr_col] + strata
466
+ return sampled[cols_to_keep].rename(columns={addr_col: "address"})
467
+
468
+ return {"train": _sample(train, n_train), "eval": _sample(eval_in, n_eval)}
469
+
470
+
471
+ _GENERATORS = {
472
+ "T1": _gen_t1,
473
+ "T2": lambda g, ne, nt, s: _gen_t2_t5(g, "T2", ne, nt, s),
474
+ "T3": lambda g, ne, nt, s: _gen_t3_t6(g, "T3", ne, nt, s),
475
+ "T4": _gen_t4,
476
+ "T5": lambda g, ne, nt, s: _gen_t2_t5(g, "T5", ne, nt, s),
477
+ "T6": lambda g, ne, nt, s: _gen_t3_t6(g, "T6", ne, nt, s),
478
+ "T7": _gen_t7,
479
+ }
480
+
481
+
482
+ # ── Public API ────────────────────────────────────────────────────────────
483
+
484
+
485
+ def get_canonical_indices(
486
+ task: Task,
487
+ split: Split = "eval",
488
+ *,
489
+ granularity: str = "daily",
490
+ n_eval: dict[Task, int] | None = None,
491
+ n_train: dict[Task, int] | None = None,
492
+ seed: int | None = None,
493
+ ) -> pd.DataFrame:
494
+ """Return the canonical index list for `(task, split)`.
495
+
496
+ Reads from cache if available; otherwise generates, persists to cache,
497
+ and returns. The cache key encodes (n_eval, n_train, seed,
498
+ stratifier_version) so non-canonical re-tunes get their own cache dir.
499
+
500
+ Smoke-mode override: when ``MACROLENS_N_TRAIN`` and / or
501
+ ``MACROLENS_N_EVAL`` env vars are set (positive int), they replace the
502
+ default budget for every task in this call. This lets the runner do an
503
+ end-to-end smoke (e.g. n_train=2, n_eval=1 across all 22 methods × 7
504
+ tasks) without touching the canonical cache or the CLI signature.
505
+ Explicit ``n_eval`` / ``n_train`` kwargs still take precedence.
506
+ """
507
+ import os as _os
508
+ env_n_eval = _os.environ.get("MACROLENS_N_EVAL")
509
+ env_n_train = _os.environ.get("MACROLENS_N_TRAIN")
510
+ if n_eval is None and env_n_eval is not None:
511
+ try:
512
+ v = int(env_n_eval)
513
+ if v > 0:
514
+ n_eval = {t: v for t in EVAL_N_PER_TASK}
515
+ except ValueError:
516
+ pass
517
+ if n_train is None and env_n_train is not None:
518
+ try:
519
+ v = int(env_n_train)
520
+ if v > 0:
521
+ n_train = {t: v for t in TRAIN_N_PER_TASK}
522
+ except ValueError:
523
+ pass
524
+ n_eval_map = n_eval or EVAL_N_PER_TASK
525
+ n_train_map = n_train or TRAIN_N_PER_TASK
526
+ s = SEED if seed is None else seed
527
+
528
+ key = budgets.cache_key(n_eval=n_eval_map, n_train=n_train_map, seed=s)
529
+ cache_dir = _cache_dir(granularity, key)
530
+ cache_path = cache_dir / f"{split}_{task}.parquet"
531
+
532
+ if cache_path.exists():
533
+ return pd.read_parquet(cache_path)
534
+
535
+ # Cache miss: generate both splits for this task and persist.
536
+ gen = _GENERATORS[task]
537
+ pair = gen(granularity, n_eval_map[task], n_train_map[task], s)
538
+ cache_dir.mkdir(parents=True, exist_ok=True)
539
+ for sp, df in pair.items():
540
+ df.to_parquet(cache_dir / f"{sp}_{task}.parquet", index=False)
541
+ logger.info(
542
+ "Canonical-indices cache write: %s (%d rows)",
543
+ cache_dir / f"{sp}_{task}.parquet", len(df),
544
+ )
545
+
546
+ return pair[split]
547
+
548
+
549
+ def build_all(
550
+ granularity: str = "daily",
551
+ *,
552
+ n_eval: dict[Task, int] | None = None,
553
+ n_train: dict[Task, int] | None = None,
554
+ seed: int | None = None,
555
+ ) -> dict[str, int]:
556
+ """Build canonical indices for every (task, split) pair.
557
+
558
+ Returns a summary dict mapping `<task>_<split>` -> n_rows. Idempotent:
559
+ re-running with the same budgets is a no-op (cache hits).
560
+ """
561
+ summary: dict[str, int] = {}
562
+ for task in ("T1", "T2", "T3", "T4", "T5", "T6", "T7"):
563
+ for split in ("train", "eval"):
564
+ df = get_canonical_indices(
565
+ task, split, granularity=granularity,
566
+ n_eval=n_eval, n_train=n_train, seed=seed,
567
+ )
568
+ summary[f"{task}_{split}"] = len(df)
569
+ return summary
code/dataloader/load.py ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical data loader for the MacroLens benchmark.
2
+
3
+ Sklearn-style: every call to ``load(task, split)`` returns a
4
+ ``LoadedData = NamedTuple[X, y, meta]`` triple. Train and test schemas are
5
+ identical for every task (the v0.1 T2/T5 schema-mismatch bug is fixed
6
+ here). Methods MUST consume only ``X`` (and at fit time, ``y``); they
7
+ must NOT consume ``meta``. The runner uses ``meta`` to join predictions
8
+ back to canonical keys.
9
+
10
+ Per-task contract (definitive):
11
+
12
+ * T1 (TSF): X = (N, lookback, F) float32, y = (N, horizon) float32
13
+ * T2 (Val-PT): X = pd.DataFrame, y = (N,) float32 actual_market_cap
14
+ * T3 (Stmt-Gen): X = pd.DataFrame keyed by (ticker, fiscal_year),
15
+ y = long-form pd.DataFrame[ticker, fiscal_year, field, value]
16
+ * T4 (Scen-Ret): X = pd.DataFrame[lookback (object), event_type, event_description],
17
+ y = (N,) float32 return_pct
18
+ * T5 (Val-Priv): same shape as T2; price-derived inputs stripped
19
+ * T6 (Gen-Eval): same shape as T3; X has no stmt_*, only NL company_description
20
+ * T7 (RE-Val): X = pd.DataFrame[property attrs],
21
+ y = pd.DataFrame[address, rent, price]
22
+
23
+ ``meta.attrs`` is populated by every loader with::
24
+
25
+ {
26
+ "task": str, "split": str, "granularity": str,
27
+ "lookback": int | None, "horizon": int | None,
28
+ "feature_names": list[str], # T1 / T4 only (lookback panel column names)
29
+ "schema_version": int,
30
+ "data_sha256": dict[str, str], # SHA-256 of every upstream parquet read
31
+ "n_canonical_dropped": int, # canonical anchors lost (T1 only); RuntimeError if > 1%
32
+ }
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ from typing import Any, NamedTuple
38
+
39
+ import numpy as np
40
+ import pandas as pd
41
+
42
+ from .. import config
43
+ from ._provenance import sha256_dataset
44
+ from .canonical_indices import get_canonical_indices
45
+
46
+
47
+ _LOADED_DATA_SCHEMA_VERSION = 2
48
+
49
+
50
+ # Curated dense-field panel for T3 (Stmt-Gen). The released T3 ground truth
51
+ # parquet carries the full XBRL field universe (~10K tags, ~467K rows), but
52
+ # long-tail company-extension tags appear in only 1–2 (ticker, fiscal_year)
53
+ # pairs each, which makes whole-universe scoring scientifically meaningless.
54
+ # We project T3's `y` to the same 11 standard XBRL line items released in
55
+ # T6's curated panel. Projection lives in the loader; the on-disk parquet
56
+ # is untouched.
57
+ _T3_DENSE_FIELDS = frozenset({
58
+ "Assets",
59
+ "Liabilities",
60
+ "StockholdersEquity",
61
+ "Revenues",
62
+ "NetIncomeLoss",
63
+ "OperatingIncomeLoss",
64
+ "CashAndCashEquivalentsAtCarryingValue",
65
+ "PropertyPlantAndEquipmentNet",
66
+ "LongTermDebt",
67
+ "ResearchAndDevelopmentExpense",
68
+ "NetCashProvidedByUsedInOperatingActivities",
69
+ })
70
+
71
+
72
+ # ── Public NamedTuple ─────────────────────────────────────────────────────
73
+
74
+
75
+ class LoadedData(NamedTuple):
76
+ """Sklearn-style ``(X, y, meta)`` triple returned by :func:`load`."""
77
+
78
+ X: Any
79
+ y: Any
80
+ meta: pd.DataFrame
81
+
82
+
83
+ # ── Public entrypoint ─────────────────────────────────────────────────────
84
+
85
+
86
+ def load(
87
+ task: str,
88
+ split: str,
89
+ *,
90
+ granularity: str = "daily",
91
+ lookback: int | None = None,
92
+ horizon: int | None = None,
93
+ setting: str | None = None,
94
+ ) -> LoadedData:
95
+ """Load canonical task data for one ``(task, split)``. Identical across methods.
96
+
97
+ ``setting`` (optional, one of ``"A".."E"``) projects the panel feature
98
+ space to the named ablation tier. Applies only to T1, T2, T4, T5.
99
+ """
100
+ if split not in ("train", "test"):
101
+ raise ValueError(f"split must be 'train' or 'test', got {split!r}")
102
+ canon_split = "eval" if split == "test" else "train"
103
+
104
+ if lookback is None:
105
+ lookback = config.get_lookback_windows(granularity)[0]
106
+ if horizon is None:
107
+ # Use the LONGEST horizon as the default (e.g. daily 63 trading days):
108
+ # the headline T1 evaluation horizon per the project plan.
109
+ horizon = config.get_horizons(granularity)[-1]
110
+
111
+ if task == "T1":
112
+ loaded = _load_t1(canon_split, split, granularity, lookback, horizon)
113
+ elif task in ("T2", "T5"):
114
+ loaded = _load_t2_t5(task, canon_split, split, granularity)
115
+ elif task in ("T3", "T6"):
116
+ loaded = _load_t3_t6(task, canon_split, split, granularity)
117
+ elif task == "T4":
118
+ loaded = _load_t4(canon_split, split, granularity, lookback)
119
+ elif task == "T7":
120
+ loaded = _load_t7(canon_split, split, granularity)
121
+ else:
122
+ raise ValueError(f"Unknown task: {task!r}")
123
+
124
+ if setting is not None:
125
+ from ._ablation import apply_to_loaded, ABLATION_SETTINGS
126
+ if setting not in ABLATION_SETTINGS:
127
+ raise ValueError(
128
+ f"setting must be one of {ABLATION_SETTINGS} or None, "
129
+ f"got {setting!r}"
130
+ )
131
+ if task in ("T3", "T6", "T7"):
132
+ raise ValueError(
133
+ f"Ablation setting={setting!r} not supported for task={task!r}; "
134
+ "ABLATION_TASKS = (T1, T2, T4, T5)"
135
+ )
136
+ loaded = apply_to_loaded(loaded, setting)
137
+ return loaded
138
+
139
+
140
+ # ── Helpers ───────────────────────────────────────────────────────────────
141
+
142
+
143
+ def _panel_path(granularity: str, split: str) -> str:
144
+ bench_dir = config.get_benchmark_dir(granularity)
145
+ return str(bench_dir / f"panel_{split}.parquet")
146
+
147
+
148
+ def _set_meta_attrs(
149
+ meta: pd.DataFrame,
150
+ *,
151
+ task: str,
152
+ split: str,
153
+ granularity: str,
154
+ parquets_read: list,
155
+ lookback: int | None = None,
156
+ horizon: int | None = None,
157
+ feature_names: list[str] | None = None,
158
+ n_canonical_dropped: int = 0,
159
+ ) -> None:
160
+ meta.attrs.update({
161
+ "task": task,
162
+ "split": split,
163
+ "granularity": granularity,
164
+ "lookback": lookback,
165
+ "horizon": horizon,
166
+ "feature_names": list(feature_names) if feature_names is not None else None,
167
+ "schema_version": _LOADED_DATA_SCHEMA_VERSION,
168
+ "data_sha256": sha256_dataset([str(p) for p in parquets_read]),
169
+ "n_canonical_dropped": n_canonical_dropped,
170
+ })
171
+
172
+
173
+ # ── T1 ────────────────────────────────────────────────────────────────────
174
+
175
+
176
+ def _build_t1_x_y(
177
+ panel: pd.DataFrame,
178
+ canon: pd.DataFrame,
179
+ lookback: int,
180
+ horizon: int,
181
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, list[str], np.ndarray]:
182
+ """Build T1 ``(X, y, close_last, feat_names, keep_rows)`` given the
183
+ canonical anchor pairs.
184
+ """
185
+ panel = panel.sort_values(["ticker", "date"]).reset_index(drop=True)
186
+ panel["date"] = pd.to_datetime(panel["date"])
187
+
188
+ exclude = {
189
+ "ticker", "date", "label", "split",
190
+ "nearest_filing_type", "nearest_filing_date", "nearest_filing_path",
191
+ }
192
+ feat_cols = [
193
+ c for c in panel.columns
194
+ if c not in exclude and panel[c].dtype.kind in "fiub"
195
+ ]
196
+
197
+ per_ticker_feats: dict[str, np.ndarray] = {}
198
+ per_ticker_close: dict[str, np.ndarray] = {}
199
+ per_ticker_dates: dict[str, np.ndarray] = {}
200
+ for ticker, grp in panel.groupby("ticker", sort=False):
201
+ per_ticker_feats[str(ticker)] = grp[feat_cols].values.astype(np.float32)
202
+ per_ticker_close[str(ticker)] = grp["close"].values.astype(np.float32)
203
+ per_ticker_dates[str(ticker)] = grp["date"].values.astype("datetime64[ns]")
204
+
205
+ canon = canon.copy()
206
+ canon["ticker"] = canon["ticker"].astype(str)
207
+ canon["anchor_date"] = pd.to_datetime(canon["anchor_date"]).values.astype("datetime64[ns]")
208
+
209
+ X_list, y_list, cl_list, keep_rows = [], [], [], []
210
+ for i, (ticker, anchor) in enumerate(zip(canon["ticker"].values, canon["anchor_date"].values)):
211
+ feats = per_ticker_feats.get(ticker)
212
+ if feats is None:
213
+ continue
214
+ dates = per_ticker_dates[ticker]
215
+ close = per_ticker_close[ticker]
216
+ idx = np.searchsorted(dates, anchor)
217
+ if idx >= len(dates) or dates[idx] != anchor:
218
+ continue
219
+ if idx + 1 < lookback or idx + horizon >= len(dates):
220
+ continue
221
+ lb = feats[idx - lookback + 1 : idx + 1]
222
+ tg = close[idx + 1 : idx + 1 + horizon]
223
+ if lb.shape != (lookback, len(feat_cols)) or tg.shape != (horizon,):
224
+ continue
225
+ X_list.append(lb)
226
+ y_list.append(tg)
227
+ cl_list.append(float(close[idx]))
228
+ keep_rows.append(i)
229
+
230
+ if not X_list:
231
+ raise RuntimeError(
232
+ f"T1 loader produced 0 windows from {len(canon)} canonical anchors; "
233
+ "panel and canonical-index cache are out of sync."
234
+ )
235
+
236
+ X = np.stack(X_list, axis=0)
237
+ y = np.stack(y_list, axis=0)
238
+ cl = np.array(cl_list, dtype=np.float32)
239
+ return X, y, cl, feat_cols, np.array(keep_rows, dtype=np.int64)
240
+
241
+
242
+ def _load_t1(
243
+ canon_split: str,
244
+ out_split: str,
245
+ granularity: str,
246
+ lookback: int,
247
+ horizon: int,
248
+ ) -> LoadedData:
249
+ canon = get_canonical_indices("T1", canon_split, granularity=granularity)
250
+ if canon.empty:
251
+ raise RuntimeError(f"Canonical T1/{canon_split} index set is empty.")
252
+
253
+ panel_path = _panel_path(granularity, out_split)
254
+ panel = pd.read_parquet(panel_path)
255
+ X, y, close_last, feat_cols, keep_rows = _build_t1_x_y(panel, canon, lookback, horizon)
256
+
257
+ n_dropped = len(canon) - len(keep_rows)
258
+ drop_frac = n_dropped / max(1, len(canon))
259
+ if drop_frac > 0.01:
260
+ raise RuntimeError(
261
+ f"T1/{out_split} loader dropped {n_dropped}/{len(canon)} canonical "
262
+ f"anchors ({drop_frac:.1%} > 1% tolerance). The canonical generator "
263
+ "and the benchmark panel are out of sync; rebuild the canonical-indices "
264
+ "cache or fix the benchmark parquet."
265
+ )
266
+
267
+ meta = canon.iloc[keep_rows][["ticker", "anchor_date", "sector", "mcap_q"]].copy()
268
+ meta["close_last"] = close_last
269
+ meta = meta.reset_index(drop=True)
270
+ _set_meta_attrs(
271
+ meta, task="T1", split=out_split, granularity=granularity,
272
+ parquets_read=[panel_path], lookback=lookback, horizon=horizon,
273
+ feature_names=feat_cols, n_canonical_dropped=n_dropped,
274
+ )
275
+ return LoadedData(X=X, y=y, meta=meta)
276
+
277
+
278
+ # ── T2 / T5 ───────────────────────────────────────────────────────────────
279
+
280
+
281
+ def _t2_t5_paths(task: str, granularity: str):
282
+ bench_dir = config.get_benchmark_dir(granularity)
283
+ if task == "T2":
284
+ return bench_dir / "valuation_inputs.parquet", bench_dir / "valuation_ground_truth.parquet"
285
+ return bench_dir / "private_valuation_inputs.parquet", bench_dir / "private_valuation_ground_truth.parquet"
286
+
287
+
288
+ def _load_t2_t5(
289
+ task: str, canon_split: str, out_split: str, granularity: str,
290
+ ) -> LoadedData:
291
+ canon = get_canonical_indices(task, canon_split, granularity=granularity)
292
+ if canon.empty:
293
+ raise RuntimeError(f"Canonical {task}/{canon_split} index set is empty.")
294
+
295
+ inputs_path, gt_path = _t2_t5_paths(task, granularity)
296
+ panel_train_path = _panel_path(granularity, "train")
297
+ panel_test_path = _panel_path(granularity, "test")
298
+
299
+ inputs = pd.read_parquet(inputs_path)
300
+ gt = pd.read_parquet(gt_path)
301
+ inputs["date"] = pd.to_datetime(inputs["date"])
302
+ gt["date"] = pd.to_datetime(gt["date"])
303
+ canon = canon.copy()
304
+ canon["date"] = pd.to_datetime(canon["date"])
305
+
306
+ parquets_read: list = [inputs_path, gt_path]
307
+
308
+ # Schema = inputs-file columns + macro snapshot (fred_*/eia_*) joined
309
+ # from the panel. The construction pipeline emits identical macro
310
+ # columns in panel_train and panel_test, so the train/test schemas
311
+ # match exactly after the merge.
312
+ inputs_feature_cols = [c for c in inputs.columns if c not in {"ticker", "date"}]
313
+ panel_train = pd.read_parquet(panel_train_path)
314
+ panel_train["date"] = pd.to_datetime(panel_train["date"])
315
+ parquets_read.append(panel_train_path)
316
+ macro_cols = sorted([
317
+ c for c in panel_train.columns
318
+ if c.startswith("fred_") or c.startswith("eia_")
319
+ ])
320
+ feature_cols = inputs_feature_cols + macro_cols
321
+
322
+ if out_split == "train":
323
+ # panel_train carries both the inputs-file columns AND the macro
324
+ # snapshot, so a single inner merge populates everything.
325
+ canon_keep = ["ticker", "date"]
326
+ present = [c for c in inputs_feature_cols if c in panel_train.columns]
327
+ missing = [c for c in inputs_feature_cols if c not in panel_train.columns]
328
+
329
+ merged = canon[canon_keep].merge(
330
+ panel_train[["ticker", "date", *present, *macro_cols]],
331
+ on=["ticker", "date"], how="inner",
332
+ )
333
+ for c in missing:
334
+ merged[c] = np.nan
335
+
336
+ # Train labels: derived_market_cap from panel_train (already merged).
337
+ if "derived_market_cap" in panel_train.columns:
338
+ mcap = canon.merge(
339
+ panel_train[["ticker", "date", "derived_market_cap"]],
340
+ on=["ticker", "date"], how="inner",
341
+ )["derived_market_cap"]
342
+ y_series = pd.to_numeric(mcap, errors="coerce").reset_index(drop=True)
343
+ else:
344
+ raise RuntimeError(
345
+ f"{task}/train: panel_train has no derived_market_cap column"
346
+ )
347
+ else:
348
+ # Test side: inputs file does not carry fred_*/eia_*; left-join
349
+ # the macro snapshot from the panel. T2/T5 use a company-level
350
+ # holdout (not chronological), so a holdout-ticker's anchor date
351
+ # can fall in either the pre- or post-cutoff window. Union both
352
+ # panels so the macro lookup covers the full 2021–2026 range.
353
+ panel_test = pd.read_parquet(panel_test_path)
354
+ panel_test["date"] = pd.to_datetime(panel_test["date"])
355
+ parquets_read.append(panel_test_path)
356
+ macro_present_train = [c for c in macro_cols if c in panel_train.columns]
357
+ macro_present_test = [c for c in macro_cols if c in panel_test.columns]
358
+ macro_present = sorted(set(macro_present_train) & set(macro_present_test))
359
+ macro_lookup = pd.concat([
360
+ panel_train[["ticker", "date", *macro_present]],
361
+ panel_test[["ticker", "date", *macro_present]],
362
+ ], ignore_index=True).drop_duplicates(
363
+ subset=["ticker", "date"], keep="first",
364
+ )
365
+ merged = canon[["ticker", "date"]].merge(
366
+ inputs, on=["ticker", "date"], how="inner",
367
+ ).merge(
368
+ gt[["ticker", "date", "actual_market_cap"]],
369
+ on=["ticker", "date"], how="inner",
370
+ ).merge(
371
+ macro_lookup, on=["ticker", "date"], how="left",
372
+ )
373
+ for c in macro_cols:
374
+ if c not in merged.columns:
375
+ merged[c] = np.nan
376
+ y_series = pd.to_numeric(
377
+ merged.pop("actual_market_cap"), errors="coerce",
378
+ ).reset_index(drop=True)
379
+
380
+ if merged.empty:
381
+ raise RuntimeError(
382
+ f"{task}/{out_split} loader: zero rows after canonical join."
383
+ )
384
+
385
+ # Project to the unified schema (inputs cols + macro cols). Train and
386
+ # test now produce the exact same columns.
387
+ feat_cols_present = [c for c in feature_cols if c in merged.columns]
388
+ X = merged[feat_cols_present].copy().reset_index(drop=True)
389
+
390
+ meta_cols = ["ticker", "date"]
391
+ if "sector" in merged.columns:
392
+ meta_cols.append("sector")
393
+ meta = merged[meta_cols].copy().reset_index(drop=True)
394
+
395
+ # mcap_q (market-cap quartile) — derived from y on the held-out test
396
+ # rows so cross-sectional stratification can run without leaking the
397
+ # train distribution. For train rows we still compute quartiles over
398
+ # the train y for parity but downstream callers only stratify test.
399
+ if y_series.size:
400
+ try:
401
+ qs = pd.qcut(y_series, q=4, labels=["Q1", "Q2", "Q3", "Q4"],
402
+ duplicates="drop")
403
+ meta["mcap_q"] = qs.astype(str).values
404
+ except ValueError:
405
+ meta["mcap_q"] = "Q?"
406
+
407
+ _set_meta_attrs(
408
+ meta, task=task, split=out_split, granularity=granularity,
409
+ parquets_read=parquets_read, feature_names=list(X.columns),
410
+ )
411
+ return LoadedData(X=X, y=y_series.to_numpy(dtype=np.float32), meta=meta)
412
+
413
+
414
+ # ── T3 / T6 ───────────────────────────────────────────────────────────────
415
+
416
+
417
+ def _t3_t6_paths(task: str, granularity: str):
418
+ bench_dir = config.get_benchmark_dir(granularity)
419
+ if task == "T3":
420
+ return bench_dir / "generation_inputs.parquet", bench_dir / "generation_ground_truth.parquet", "field"
421
+ return bench_dir / "generator_eval_inputs.parquet", bench_dir / "generator_eval_ground_truth.parquet", "generator_field"
422
+
423
+
424
+ def _load_t3_t6(
425
+ task: str, canon_split: str, out_split: str, granularity: str,
426
+ ) -> LoadedData:
427
+ canon = get_canonical_indices(task, canon_split, granularity=granularity)
428
+ if canon.empty:
429
+ raise RuntimeError(f"Canonical {task}/{canon_split} index set is empty.")
430
+
431
+ inputs_path, gt_path, field_col = _t3_t6_paths(task, granularity)
432
+ inputs = pd.read_parquet(inputs_path)
433
+ gt = pd.read_parquet(gt_path)
434
+ if field_col not in gt.columns and "field" in gt.columns:
435
+ field_col = "field"
436
+ if "fiscal_year" not in gt.columns:
437
+ if "filing_date" in gt.columns:
438
+ gt["fiscal_year"] = pd.to_datetime(gt["filing_date"]).dt.year
439
+ else:
440
+ gt["fiscal_year"] = 0
441
+
442
+ canon = canon.copy()
443
+ canon["fiscal_year"] = pd.to_numeric(canon["fiscal_year"], errors="coerce").astype("Int64")
444
+
445
+ # X: per-(ticker, fiscal_year). For T3 inputs file is per-ticker (one
446
+ # row per holdout ticker); broadcast across the canonical (ticker,
447
+ # fiscal_year) pairs.
448
+ if "fiscal_year" in inputs.columns:
449
+ X = canon.merge(inputs, on=["ticker", "fiscal_year"], how="left")
450
+ else:
451
+ X = canon.merge(inputs, on="ticker", how="left")
452
+
453
+ # y: long-form restricted to canonical (ticker, fiscal_year) pairs.
454
+ canon_keys = set(zip(
455
+ canon["ticker"].astype(str),
456
+ canon["fiscal_year"].astype("Int64").astype(str),
457
+ ))
458
+ gt_filt = gt.copy()
459
+ gt_filt["fiscal_year"] = pd.to_numeric(gt_filt["fiscal_year"], errors="coerce").astype("Int64")
460
+ gt_filt["_key"] = list(zip(
461
+ gt_filt["ticker"].astype(str),
462
+ gt_filt["fiscal_year"].astype(str),
463
+ ))
464
+ gt_filt = gt_filt[gt_filt["_key"].isin(canon_keys)].drop(columns=["_key"]).reset_index(drop=True)
465
+
466
+ if field_col != "field":
467
+ gt_filt = gt_filt.rename(columns={field_col: "field"})
468
+ if task == "T3":
469
+ # T3 evaluates on the dense 11-field panel (same fields T6 uses).
470
+ # The released ``generation_ground_truth.parquet`` ships the full
471
+ # XBRL universe (10,279 unique tags including company-extension
472
+ # tags filed once by one issuer); per-field MAPE on those is noise.
473
+ # Projection happens at load time so the on-disk parquet is
474
+ # preserved; evaluation runs on the meaningful subset.
475
+ gt_filt = gt_filt[gt_filt["field"].astype(str).isin(_T3_DENSE_FIELDS)].reset_index(drop=True)
476
+ y = gt_filt[["ticker", "fiscal_year", "field", "value"]].copy()
477
+
478
+ meta = canon[["ticker", "fiscal_year"]].copy().reset_index(drop=True)
479
+ X = X.reset_index(drop=True)
480
+
481
+ _set_meta_attrs(
482
+ meta, task=task, split=out_split, granularity=granularity,
483
+ parquets_read=[inputs_path, gt_path],
484
+ feature_names=[c for c in X.columns if c not in {"ticker", "fiscal_year"}],
485
+ )
486
+ return LoadedData(X=X, y=y, meta=meta)
487
+
488
+
489
+ # ── T4 ────────────────────────────────────────────────────────────────────
490
+
491
+
492
+ def _load_t4(
493
+ canon_split: str, out_split: str, granularity: str, lookback: int,
494
+ ) -> LoadedData:
495
+ canon = get_canonical_indices("T4", canon_split, granularity=granularity)
496
+ if canon.empty:
497
+ raise RuntimeError(f"Canonical T4/{canon_split} index set is empty.")
498
+
499
+ bench_dir = config.get_benchmark_dir(granularity)
500
+ gt_path = bench_dir / "scenario_forecast_ground_truth.parquet"
501
+ scen_path = bench_dir / "scenarios.parquet"
502
+ # T4 lookback windows can span the train/test split (an event close to
503
+ # the cutoff needs ~63 trading days of history that may sit on the
504
+ # other side). Read both panels and merge for the lookback build.
505
+ panel_train_path = _panel_path(granularity, "train")
506
+ panel_test_path = _panel_path(granularity, "test")
507
+
508
+ gt = pd.read_parquet(gt_path).dropna(subset=["actual_return_pct"])
509
+ gt["event_date"] = pd.to_datetime(gt["event_date"])
510
+
511
+ scen_full = pd.read_parquet(scen_path)
512
+ desc_col = "event_description" if "event_description" in scen_full.columns else None
513
+ keep_scen_cols = ["scenario_id"] + ([desc_col] if desc_col else [])
514
+ scen = scen_full[keep_scen_cols].drop_duplicates("scenario_id")
515
+
516
+ canon = canon.copy()
517
+ canon["scenario_id"] = canon["scenario_id"].astype(str)
518
+ canon["ticker"] = canon["ticker"].astype(str)
519
+ gt["scenario_id"] = gt["scenario_id"].astype(str)
520
+ gt["ticker"] = gt["ticker"].astype(str)
521
+ scen["scenario_id"] = scen["scenario_id"].astype(str)
522
+
523
+ # Filter ground truth to canonical pairs
524
+ canon_keys = set(zip(canon["scenario_id"], canon["ticker"]))
525
+ gt["_key"] = list(zip(gt["scenario_id"], gt["ticker"]))
526
+ gt_filt = gt[gt["_key"].isin(canon_keys)].drop(columns=["_key"]).reset_index(drop=True)
527
+ if gt_filt.empty:
528
+ raise RuntimeError(f"T4/{out_split} loader: zero rows after canonical join.")
529
+
530
+ if desc_col is not None:
531
+ gt_filt = gt_filt.merge(
532
+ scen[["scenario_id", desc_col]], on="scenario_id", how="left",
533
+ )
534
+
535
+ # Lookback windows from the COMBINED panel (train + test) — a T4
536
+ # event near the chronological cutoff needs lookback rows on the
537
+ # other side of the split.
538
+ panel_train_df = pd.read_parquet(panel_train_path)
539
+ panel_test_df = pd.read_parquet(panel_test_path)
540
+ panel = pd.concat([panel_train_df, panel_test_df], ignore_index=True)
541
+ del panel_train_df, panel_test_df
542
+ panel["date"] = pd.to_datetime(panel["date"])
543
+ panel = panel.sort_values(["ticker", "date"]).drop_duplicates(
544
+ subset=["ticker", "date"], keep="first",
545
+ ).reset_index(drop=True)
546
+
547
+ exclude = {
548
+ "ticker", "date", "label", "split",
549
+ "nearest_filing_type", "nearest_filing_date", "nearest_filing_path",
550
+ }
551
+ feat_cols = [
552
+ c for c in panel.columns
553
+ if c not in exclude and panel[c].dtype.kind in "fiub"
554
+ ]
555
+
556
+ per_ticker_feats: dict[str, np.ndarray] = {}
557
+ per_ticker_dates: dict[str, np.ndarray] = {}
558
+ for ticker, grp in panel.groupby("ticker", sort=False):
559
+ per_ticker_feats[str(ticker)] = grp[feat_cols].values.astype(np.float32)
560
+ per_ticker_dates[str(ticker)] = grp["date"].values.astype("datetime64[ns]")
561
+
562
+ lb_list: list[np.ndarray] = []
563
+ valid = np.zeros(len(gt_filt), dtype=bool)
564
+ for i, (ticker, ev_date) in enumerate(zip(
565
+ gt_filt["ticker"].values,
566
+ gt_filt["event_date"].values.astype("datetime64[ns]"),
567
+ )):
568
+ feats = per_ticker_feats.get(str(ticker))
569
+ if feats is None:
570
+ lb_list.append(np.zeros((lookback, len(feat_cols)), dtype=np.float32))
571
+ continue
572
+ dates = per_ticker_dates[str(ticker)]
573
+ idx = np.searchsorted(dates, ev_date, side="right") - 1
574
+ if idx + 1 < lookback:
575
+ lb_list.append(np.zeros((lookback, len(feat_cols)), dtype=np.float32))
576
+ continue
577
+ lb = feats[idx - lookback + 1 : idx + 1]
578
+ if lb.shape != (lookback, len(feat_cols)):
579
+ lb_list.append(np.zeros((lookback, len(feat_cols)), dtype=np.float32))
580
+ continue
581
+ lb_list.append(lb)
582
+ valid[i] = True
583
+
584
+ keep = np.where(valid)[0]
585
+ if len(keep) == 0:
586
+ raise RuntimeError(f"T4/{out_split} loader: no valid lookback windows after panel join.")
587
+ gt_filt = gt_filt.iloc[keep].reset_index(drop=True)
588
+ lb_arr = [lb_list[i] for i in keep]
589
+
590
+ # T4 X is a DataFrame (not a dict): one row per (scenario_id, ticker),
591
+ # with `lookback` as an object-dtype column where each cell is a
592
+ # (lookback, F) np.ndarray. event_type and event_description are string
593
+ # columns. Methods consume X uniformly.
594
+ X = pd.DataFrame({
595
+ "lookback": lb_arr,
596
+ "event_type": gt_filt["event_type"].astype(str).values,
597
+ "event_description": (
598
+ gt_filt[desc_col].astype(str).values if desc_col is not None
599
+ else np.array([""] * len(gt_filt))
600
+ ),
601
+ })
602
+
603
+ y = gt_filt["actual_return_pct"].astype(np.float32).to_numpy()
604
+ meta = gt_filt[["scenario_id", "ticker", "event_type", "event_date"]].copy().reset_index(drop=True)
605
+
606
+ _set_meta_attrs(
607
+ meta, task="T4", split=out_split, granularity=granularity,
608
+ parquets_read=[gt_path, scen_path, panel_train_path, panel_test_path],
609
+ lookback=lookback, feature_names=feat_cols,
610
+ )
611
+ return LoadedData(X=X, y=y, meta=meta)
612
+
613
+
614
+ # ── T7 ────────────────────────────────────────────────────────────────────
615
+
616
+
617
+ def _load_t7(canon_split: str, out_split: str, granularity: str) -> LoadedData:
618
+ canon = get_canonical_indices("T7", canon_split, granularity=granularity)
619
+ if canon.empty:
620
+ raise RuntimeError(f"Canonical T7/{canon_split} index set is empty.")
621
+
622
+ bench_dir = config.get_benchmark_dir(granularity)
623
+ train_src_path = bench_dir / "re_train_properties.parquet"
624
+ test_src_path = bench_dir / "re_eval_inputs.parquet"
625
+ test_gt_path = bench_dir / "re_eval_ground_truth.parquet"
626
+
627
+ # Read BOTH src files to compute the column intersection (the smaller
628
+ # test schema is the canonical one; train rows are projected onto it
629
+ # so train ↔ test are schema-identical).
630
+ test_src = pd.read_parquet(test_src_path)
631
+ train_src = pd.read_parquet(train_src_path)
632
+ common_cols = [c for c in test_src.columns if c in train_src.columns]
633
+ if "address" not in common_cols:
634
+ raise RuntimeError(
635
+ "T7 loader: 'address' missing from re_eval_inputs ∩ re_train_properties columns"
636
+ )
637
+
638
+ if out_split == "train":
639
+ src = train_src[common_cols].copy()
640
+ # Train ground truth comes from re_train_properties' rent/price columns;
641
+ # they're already in train_src.
642
+ gt_cols = [c for c in ("address", "rent", "price") if c in train_src.columns]
643
+ gt = train_src[gt_cols].copy()
644
+ parquets_read = [train_src_path]
645
+ else:
646
+ src = test_src[common_cols].copy()
647
+ gt = pd.read_parquet(test_gt_path)
648
+ parquets_read = [test_src_path, test_gt_path]
649
+
650
+ canon = canon.copy()
651
+ canon["address"] = canon["address"].astype(str)
652
+ src["address"] = src["address"].astype(str)
653
+ gt["address"] = gt["address"].astype(str)
654
+
655
+ # Fix the v0.1 T7 duplicate-address Cartesian product bug. Dedup
656
+ # canon, src, and gt — canon itself can carry duplicates (the T7
657
+ # canonical sampler does not enforce address-uniqueness on the train
658
+ # pool), and an upstream duplicate quietly multiplies on the merge.
659
+ canon_dedup = canon.drop_duplicates(subset="address", keep="first").reset_index(drop=True)
660
+ src_dedup = src.drop_duplicates(subset="address", keep="first").reset_index(drop=True)
661
+ gt_dedup = gt.drop_duplicates(subset="address", keep="first").reset_index(drop=True)
662
+
663
+ X = canon_dedup[["address"]].merge(src_dedup, on="address", how="left")
664
+ y_join = canon_dedup[["address"]].merge(gt_dedup, on="address", how="left")
665
+
666
+ if X.empty:
667
+ raise RuntimeError(
668
+ f"T7/{out_split} loader: zero rows after canonical address join."
669
+ )
670
+
671
+ # Lock the y column order so train and test produce identical column
672
+ # ordering. Methods may rely on positional column access.
673
+ y = y_join.reindex(columns=["address", "rent", "price"]).reset_index(drop=True)
674
+ X = X.reset_index(drop=True)
675
+
676
+ meta_cols = ["address"] + [c for c in ("property_type", "state") if c in canon_dedup.columns]
677
+ meta = canon_dedup[meta_cols].reset_index(drop=True)
678
+
679
+ _set_meta_attrs(
680
+ meta, task="T7", split=out_split, granularity=granularity,
681
+ parquets_read=parquets_read,
682
+ feature_names=[c for c in X.columns if c != "address"],
683
+ )
684
+ return LoadedData(X=X, y=y, meta=meta)
code/enrich_benchmark.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Step 11 – Enrich benchmark panels with news-derived features.
2
+
3
+ Lightweight post-processing that adds columns to the **L3 benchmark**
4
+ panels (not L2 processed) and enriches ``scenarios.parquet`` with
5
+ collected news context.
6
+
7
+ New columns added to ``panel_train.parquet`` / ``panel_test.parquet``:
8
+ * ``filing_8k_count_30d`` (int) – 8-K filings in the past 30 days
9
+ * ``news_count_7d`` (int) – yfinance news articles in past 7 days
10
+ * ``has_press_release_7d`` (bool) – press release in past 7 days
11
+
12
+ New column added to ``scenarios.parquet``:
13
+ * ``news_context`` (str, JSON) – top-5 scenario news articles
14
+
15
+ Resume: skips if columns already exist in parquet files.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import logging
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+ import pandas as pd
26
+
27
+ from . import config
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Helper: rolling-window count via prefix-sum + searchsorted
34
+ # ---------------------------------------------------------------------------
35
+
36
+ def _rolling_window_count(
37
+ panel_dates_i64: np.ndarray,
38
+ panel_groups: dict[str, np.ndarray],
39
+ events: pd.DataFrame,
40
+ window_days: int,
41
+ n_rows: int,
42
+ ) -> np.ndarray:
43
+ """Count events within a rolling calendar-day window per ticker.
44
+
45
+ Uses cumulative-sum differencing with ``np.searchsorted`` – loops
46
+ over tickers that have events (typically a small subset), but each
47
+ iteration is pure numpy O(n log m).
48
+
49
+ Parameters
50
+ ----------
51
+ panel_dates_i64 : int64 nanosecond timestamps for all panel rows
52
+ panel_groups : dict mapping ticker → integer row indices in the panel
53
+ events : DataFrame with columns [ticker, date, n] (daily counts)
54
+ window_days : size of the look-back window (inclusive both ends)
55
+ n_rows : total number of rows in the panel
56
+
57
+ Returns
58
+ -------
59
+ np.ndarray[int64] of length *n_rows*.
60
+ """
61
+ result = np.zeros(n_rows, dtype=np.int64)
62
+
63
+ if events.empty:
64
+ return result
65
+
66
+ window_ns = np.int64((window_days + 1) * 86_400_000_000_000)
67
+
68
+ for ticker, ev_group in events.groupby("ticker"):
69
+ if ticker not in panel_groups:
70
+ continue
71
+
72
+ panel_idx = panel_groups[ticker]
73
+ p_dates = panel_dates_i64[panel_idx]
74
+
75
+ ev_sorted = ev_group.sort_values("date")
76
+ e_dates = ev_sorted["date"].values.astype("int64")
77
+ e_cumsum = ev_sorted["n"].values.cumsum()
78
+
79
+ upper_pos = np.searchsorted(e_dates, p_dates, side="right") - 1
80
+ upper_cs = np.where(upper_pos >= 0, e_cumsum[upper_pos], 0)
81
+
82
+ lower_dates = p_dates - window_ns
83
+ lower_pos = np.searchsorted(e_dates, lower_dates, side="right") - 1
84
+ lower_cs = np.where(lower_pos >= 0, e_cumsum[lower_pos], 0)
85
+
86
+ result[panel_idx] = upper_cs - lower_cs
87
+
88
+ return result
89
+
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # 1. Filing 8-K count
93
+ # ---------------------------------------------------------------------------
94
+
95
+ def _add_8k_counts(panel: pd.DataFrame, corpus_path: Path) -> pd.DataFrame:
96
+ """Add ``filing_8k_count_30d`` (fully vectorised, no calendar reindexing)."""
97
+ if "filing_8k_count_30d" in panel.columns:
98
+ logger.info(" filing_8k_count_30d already present – skipping")
99
+ return panel
100
+
101
+ if not corpus_path.exists():
102
+ logger.warning("filing_corpus.parquet not found – filling 8k count with 0")
103
+ panel["filing_8k_count_30d"] = 0
104
+ return panel
105
+
106
+ corpus = pd.read_parquet(corpus_path)
107
+ eightk = corpus[corpus["filing_type"] == "8-K"].copy()
108
+
109
+ if eightk.empty:
110
+ logger.info(" No 8-K filings in corpus – filling with 0")
111
+ panel["filing_8k_count_30d"] = 0
112
+ return panel
113
+
114
+ panel["date"] = pd.to_datetime(panel["date"])
115
+ eightk["filing_date"] = pd.to_datetime(eightk["filing_date"])
116
+
117
+ daily = (
118
+ eightk.groupby(["ticker", "filing_date"])
119
+ .size()
120
+ .reset_index(name="n")
121
+ .rename(columns={"filing_date": "date"})
122
+ )
123
+
124
+ panel_dates_i64 = panel["date"].values.astype("int64")
125
+ panel_groups = {
126
+ t: idx for t, idx in panel.groupby("ticker", sort=False).indices.items()
127
+ }
128
+
129
+ panel["filing_8k_count_30d"] = _rolling_window_count(
130
+ panel_dates_i64, panel_groups, daily, window_days=30, n_rows=len(panel),
131
+ )
132
+ logger.info(" Added filing_8k_count_30d")
133
+ return panel
134
+
135
+
136
+ # ---------------------------------------------------------------------------
137
+ # 2. News/PR counts from SEC 8-K filings (covers full 2021-2026 period)
138
+ # ---------------------------------------------------------------------------
139
+
140
+ def _add_news_counts(panel: pd.DataFrame) -> pd.DataFrame:
141
+ """Add ``news_count_7d`` and ``has_press_release_7d`` from SEC 8-K filings.
142
+
143
+ 8-K filings are material event disclosures — effectively press releases
144
+ filed with the SEC. For small/micro-cap companies, 8-K filings are the
145
+ most reliable per-ticker news source (mainstream media coverage is sparse).
146
+ """
147
+ if "news_count_7d" in panel.columns:
148
+ logger.info(" news_count_7d already present – skipping")
149
+ return panel
150
+
151
+ panel["date"] = pd.to_datetime(panel["date"])
152
+
153
+ # Collect 8-K filing dates per ticker from the filings directory
154
+ filings_dir = config.FILINGS_DIR
155
+ rows_8k: list[dict] = []
156
+ if filings_dir.exists():
157
+ for ticker_dir in filings_dir.iterdir():
158
+ if not ticker_dir.is_dir():
159
+ continue
160
+ ticker = ticker_dir.name
161
+ for filing in ticker_dir.glob("*.md"):
162
+ # Filing names typically contain the type and date
163
+ # e.g., "8-K_2023-07-26.md" or "8-K_20230726_..."
164
+ fname = filing.stem
165
+ if "8-K" not in fname.upper() and "8K" not in fname.upper():
166
+ continue
167
+ # Extract date from filename
168
+ import re
169
+ date_match = re.search(r"(\d{4}-\d{2}-\d{2})", fname)
170
+ if not date_match:
171
+ date_match = re.search(r"(\d{4})(\d{2})(\d{2})", fname)
172
+ if date_match:
173
+ date_str = f"{date_match.group(1)}-{date_match.group(2)}-{date_match.group(3)}"
174
+ else:
175
+ continue
176
+ else:
177
+ date_str = date_match.group(1)
178
+ try:
179
+ ts = pd.Timestamp(date_str)
180
+ rows_8k.append({"ticker": ticker, "date": ts})
181
+ except Exception:
182
+ continue
183
+
184
+ panel_dates_i64 = panel["date"].values.astype("int64")
185
+ panel_groups = {
186
+ t: idx for t, idx in panel.groupby("ticker", sort=False).indices.items()
187
+ }
188
+
189
+ if rows_8k:
190
+ filing_df = pd.DataFrame(rows_8k)
191
+ filing_df["date"] = pd.to_datetime(filing_df["date"]).dt.normalize()
192
+ daily_8k = filing_df.groupby(["ticker", "date"]).size().reset_index(name="n")
193
+ logger.info(" Found %d 8-K filing events across %d tickers",
194
+ len(daily_8k), filing_df["ticker"].nunique())
195
+ panel["news_count_7d"] = _rolling_window_count(
196
+ panel_dates_i64, panel_groups, daily_8k,
197
+ window_days=7, n_rows=len(panel),
198
+ )
199
+ panel["has_press_release_7d"] = panel["news_count_7d"] > 0
200
+ else:
201
+ logger.warning(" No 8-K filings found – filling with defaults")
202
+ panel["news_count_7d"] = 0
203
+ panel["has_press_release_7d"] = False
204
+
205
+ logger.info(" Added news_count_7d and has_press_release_7d (from 8-K filings)")
206
+ return panel
207
+
208
+
209
+ # ---------------------------------------------------------------------------
210
+ # 3. Scenario news context
211
+ # ---------------------------------------------------------------------------
212
+
213
+ def _enrich_scenarios(scenarios_path: Path) -> None:
214
+ """Add ``news_context`` column to scenarios.parquet."""
215
+ if not scenarios_path.exists():
216
+ logger.warning("scenarios.parquet not found – skipping scenario enrichment")
217
+ return
218
+
219
+ df = pd.read_parquet(scenarios_path)
220
+
221
+ if "news_context" in df.columns:
222
+ logger.info(" news_context already present – skipping")
223
+ return
224
+
225
+ scenarios_dir = config.NEWS_DIR / "scenarios"
226
+ contexts = []
227
+
228
+ for _, row in df.iterrows():
229
+ sc_id = row["scenario_id"]
230
+ news_path = scenarios_dir / f"{sc_id}.json"
231
+ if news_path.exists():
232
+ try:
233
+ articles = json.loads(news_path.read_text(encoding="utf-8"))
234
+ top_articles = [
235
+ {
236
+ "title": a.get("title", ""),
237
+ "snippet": a.get("snippet", ""),
238
+ "date": a.get("date", ""),
239
+ }
240
+ for a in articles
241
+ ]
242
+ contexts.append(json.dumps(top_articles))
243
+ except Exception:
244
+ contexts.append("[]")
245
+ else:
246
+ contexts.append("[]")
247
+
248
+ df["news_context"] = contexts
249
+ df.to_parquet(scenarios_path, index=False)
250
+ logger.info(" Added news_context to %d scenarios", len(df))
251
+
252
+
253
+ # ---------------------------------------------------------------------------
254
+ # Public entry point
255
+ # ---------------------------------------------------------------------------
256
+
257
+ def run(granularity: str | None = None) -> None:
258
+ """Enrich L3 benchmark panels and scenarios with news-derived features."""
259
+ if granularity is None:
260
+ granularity = config.GRANULARITY
261
+
262
+ benchmark_dir = config.get_benchmark_dir(granularity)
263
+ corpus_path = benchmark_dir / "filing_corpus.parquet"
264
+
265
+ for split in ("panel_train.parquet", "panel_test.parquet"):
266
+ panel_path = benchmark_dir / split
267
+ if not panel_path.exists():
268
+ logger.warning("%s not found – skipping", panel_path)
269
+ continue
270
+
271
+ logger.info("Enriching %s …", split)
272
+ panel = pd.read_parquet(panel_path)
273
+
274
+ panel = _add_8k_counts(panel, corpus_path)
275
+ panel.to_parquet(panel_path, index=False)
276
+ logger.info(" Checkpoint: saved after 8-K enrichment")
277
+
278
+ panel = _add_news_counts(panel)
279
+ panel.to_parquet(panel_path, index=False)
280
+ logger.info(
281
+ " Saved enriched %s (%d rows, %d cols)",
282
+ split, len(panel), len(panel.columns),
283
+ )
284
+
285
+ scenarios_path = benchmark_dir / "scenarios.parquet"
286
+ _enrich_scenarios(scenarios_path)
287
+
288
+ logger.info("Benchmark enrichment complete.")
code/eval.py ADDED
@@ -0,0 +1,1556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MacroLens unified-API evaluation layer (Phase 1E).
2
+
3
+ Public API
4
+ ----------
5
+
6
+ >>> import whatif_bench.eval as ev
7
+ >>> metrics = ev.score("T1", y_true, y_pred,
8
+ ... cluster_keys=meta["ticker"].values,
9
+ ... close_last=meta["close_last"].values)
10
+ >>> df = ev.compare_methods("T1", run_records, correction="holm")
11
+
12
+ Hard rules (definitive — see the unified-API plan §5 / §7b):
13
+
14
+ * **Default ``resample="cluster"``** — bootstrap by ``ticker`` for
15
+ T1 / T2 / T3 / T5 / T6 / T7, by ``scenario_id`` for T4. Statistically
16
+ correct on panel data.
17
+ * **Adaptive ``n_boot``** — start at B=1,000; if
18
+ ``(ci_hi - ci_lo) / max(|mean|, 1e-12) > 0.05`` escalate to B=10,000.
19
+ Cap at 10,000. Actual ``B`` recorded on the returned ``MetricValue``.
20
+ * **Close-anchor DA everywhere** — for T1, directional accuracy is
21
+ ``mean(sign(y_pred[t] - close_last) == sign(y_true[t] - close_last))``
22
+ over the horizon. The legacy ``np.diff``-based formula is REMOVED.
23
+ ``close_last`` is supplied via the ``close_last=`` kwarg (or
24
+ ``meta["close_last"]`` by the runner). When unavailable we fall back to
25
+ ``y_pred[:, 0]`` as the anchor and document the fallback in the metric's
26
+ metadata.
27
+ * **APE clip uniformly at 10×.** With ``return_sensitivity=True`` we also
28
+ emit MAPE at clips ``{5, 10, 20, ∞}``.
29
+ * **Multiple-comparisons correction is per-task** (Holm or BH). NO
30
+ cross-task FWER claim.
31
+ * All metric values are wrapped in ``MetricValue`` Pydantic models.
32
+
33
+ The per-task numerical logic is lifted verbatim from the legacy
34
+ ``agents/valuation/evaluate.py`` module (which still passes the
35
+ ``tests/test_evaluator_contract.py`` contract).
36
+
37
+ This module is a leaf — it does NO IO, imports nothing from
38
+ ``methods/``, ``dataloader/`` or ``experiments/``.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import logging
44
+ from typing import Any, Callable, Iterable, Literal
45
+
46
+ import numpy as np
47
+ import pandas as pd
48
+
49
+ from .macrolens._types import MetricValue
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ # ===================================================================
55
+ # Constants
56
+ # ===================================================================
57
+
58
+ _BOOTSTRAP_INITIAL_N = 1_000
59
+ _BOOTSTRAP_MAX_N = 10_000
60
+ _BOOTSTRAP_CI_TOL = 0.05 # widen → escalate threshold
61
+
62
+ _APE_CLIP_DEFAULT = 10.0 # 1000% per-instance cap
63
+ _APE_SENSITIVITY_CLIPS: tuple[float, ...] = (5.0, 10.0, 20.0, float("inf"))
64
+
65
+
66
+ # ===================================================================
67
+ # Cluster bootstrap
68
+ # ===================================================================
69
+
70
+
71
+ def _bootstrap_ci(
72
+ values: np.ndarray,
73
+ *,
74
+ cluster_keys: np.ndarray | None = None,
75
+ agg_fn: Callable[[np.ndarray], float] = np.mean,
76
+ n_boot: int | Literal["adaptive"] = "adaptive",
77
+ alpha: float = 0.05,
78
+ seed: int = 42,
79
+ ) -> tuple[float, float, float, float, int]:
80
+ """Bootstrap confidence interval for ``agg_fn(values)``.
81
+
82
+ Parameters
83
+ ----------
84
+ values
85
+ 1-D float array of per-instance summary statistics.
86
+ cluster_keys
87
+ Optional cluster ID per row. When supplied, performs **cluster
88
+ bootstrap** (resample whole clusters with replacement; aggregate
89
+ all member rows). When ``None``, performs IID bootstrap.
90
+ agg_fn
91
+ Aggregator (default ``np.mean``).
92
+ n_boot
93
+ Either an explicit integer, or ``"adaptive"`` to start at 1,000 and
94
+ escalate to 10,000 if the CI half-width is wider than 5% of the
95
+ point estimate.
96
+ alpha
97
+ Two-sided coverage; default 0.05 → 95% CI.
98
+ seed
99
+ RNG seed.
100
+
101
+ Returns
102
+ -------
103
+ ``(value, ci_lo, ci_hi, std, n_boot_used)``
104
+ """
105
+ values = np.asarray(values, dtype=np.float64).ravel()
106
+ n = values.size
107
+ if n == 0:
108
+ nan = float("nan")
109
+ return nan, nan, nan, nan, 0
110
+
111
+ point = float(agg_fn(values))
112
+
113
+ # Build cluster index lookup once.
114
+ if cluster_keys is not None:
115
+ ck = np.asarray(cluster_keys).ravel()
116
+ if ck.size != n:
117
+ raise ValueError(
118
+ f"cluster_keys length {ck.size} != values length {n}"
119
+ )
120
+ # Map cluster → row indices.
121
+ unique_clusters, inverse = np.unique(ck, return_inverse=True)
122
+ # cluster_idx[c] = np.array of row positions in `values`.
123
+ cluster_rows: list[np.ndarray] = [
124
+ np.where(inverse == c)[0] for c in range(unique_clusters.size)
125
+ ]
126
+ n_clusters = unique_clusters.size
127
+ else:
128
+ cluster_rows = []
129
+ n_clusters = 0
130
+
131
+ rng = np.random.default_rng(seed)
132
+
133
+ def _draw(b: int) -> np.ndarray:
134
+ out = np.empty(b, dtype=np.float64)
135
+ if cluster_keys is not None:
136
+ for i in range(b):
137
+ pick = rng.integers(0, n_clusters, size=n_clusters)
138
+ # Concatenate row indices for all picked clusters.
139
+ idx = np.concatenate([cluster_rows[c] for c in pick])
140
+ out[i] = agg_fn(values[idx])
141
+ else:
142
+ for i in range(b):
143
+ out[i] = agg_fn(values[rng.integers(0, n, size=n)])
144
+ return out
145
+
146
+ # Decide B.
147
+ if n_boot == "adaptive":
148
+ boot = _draw(_BOOTSTRAP_INITIAL_N)
149
+ lo = float(np.quantile(boot, alpha / 2))
150
+ hi = float(np.quantile(boot, 1 - alpha / 2))
151
+ rel_width = (hi - lo) / max(abs(point), 1e-12)
152
+ if rel_width > _BOOTSTRAP_CI_TOL and _BOOTSTRAP_MAX_N > _BOOTSTRAP_INITIAL_N:
153
+ extra = _draw(_BOOTSTRAP_MAX_N - _BOOTSTRAP_INITIAL_N)
154
+ boot = np.concatenate([boot, extra])
155
+ lo = float(np.quantile(boot, alpha / 2))
156
+ hi = float(np.quantile(boot, 1 - alpha / 2))
157
+ b_used = boot.size
158
+ else:
159
+ b_used = int(n_boot)
160
+ boot = _draw(b_used)
161
+ lo = float(np.quantile(boot, alpha / 2))
162
+ hi = float(np.quantile(boot, 1 - alpha / 2))
163
+
164
+ std = float(np.std(boot))
165
+ return point, lo, hi, std, b_used
166
+
167
+
168
+ def _wrap_metric(
169
+ values: np.ndarray,
170
+ *,
171
+ cluster_keys: np.ndarray | None,
172
+ agg_fn: Callable[[np.ndarray], float],
173
+ n_boot: int | Literal["adaptive"],
174
+ alpha: float,
175
+ seed: int,
176
+ resample: Literal["cluster", "iid"],
177
+ ) -> MetricValue:
178
+ """Bootstrap a per-instance vector and box it into a ``MetricValue``.
179
+
180
+ Returns a ``MetricValue`` with all fields ``None`` when ``values`` is
181
+ empty or every entry is non-finite (the metric cannot be defined).
182
+ """
183
+ arr = np.asarray(values, dtype=np.float64).ravel()
184
+ finite_mask = np.isfinite(arr)
185
+ if arr.size == 0 or not finite_mask.any():
186
+ return _none_metric(resample=resample)
187
+ if not finite_mask.all():
188
+ # Drop non-finite entries; align cluster_keys if supplied.
189
+ if cluster_keys is not None:
190
+ ck_arr = np.asarray(cluster_keys).ravel()
191
+ if ck_arr.size == arr.size:
192
+ cluster_keys = ck_arr[finite_mask]
193
+ # else: leave cluster_keys alone — _align_cluster_keys upstream
194
+ # may have already pre-filtered.
195
+ arr = arr[finite_mask]
196
+ if resample == "iid":
197
+ ck = None
198
+ else:
199
+ ck = cluster_keys
200
+ # Cluster bootstrap with one unique cluster collapses to a delta — fall
201
+ # back to IID resampling on that array so the std is still defined.
202
+ if ck is not None:
203
+ unique_ck = np.unique(np.asarray(ck).ravel())
204
+ if unique_ck.size < 2:
205
+ ck = None
206
+ point, lo, hi, std, b_used = _bootstrap_ci(
207
+ arr,
208
+ cluster_keys=ck,
209
+ agg_fn=agg_fn,
210
+ n_boot=n_boot,
211
+ alpha=alpha,
212
+ seed=seed,
213
+ )
214
+ if not np.isfinite(point):
215
+ return _none_metric(resample=resample)
216
+ # CI half-width / std may legitimately collapse to 0 (1-row arrays); keep
217
+ # those numerics rather than substituting None.
218
+ lo_v = lo if np.isfinite(lo) else point
219
+ hi_v = hi if np.isfinite(hi) else point
220
+ std_v = std if np.isfinite(std) else 0.0
221
+ return MetricValue(
222
+ value=float(point), ci_lo=float(lo_v), ci_hi=float(hi_v),
223
+ std=float(std_v), n_boot=int(b_used),
224
+ resample=resample,
225
+ )
226
+
227
+
228
+ def _scalar_metric(
229
+ value: float | None,
230
+ *,
231
+ resample: Literal["cluster", "iid"],
232
+ n_boot: int = 0,
233
+ ) -> MetricValue:
234
+ """Wrap a deterministic scalar (e.g. counts) without a bootstrap.
235
+
236
+ When ``value`` is ``None`` or NaN we emit a ``MetricValue`` whose
237
+ ``value`` / ``ci_lo`` / ``ci_hi`` / ``std`` are all ``None`` so
238
+ consumers can detect "metric not applicable" via ``value is None``
239
+ rather than with a NaN finiteness probe.
240
+ """
241
+ if value is None or (isinstance(value, float) and np.isnan(value)):
242
+ return MetricValue(
243
+ value=None,
244
+ ci_lo=None,
245
+ ci_hi=None,
246
+ std=None,
247
+ n_boot=int(n_boot),
248
+ resample=resample,
249
+ )
250
+ v = float(value)
251
+ return MetricValue(
252
+ value=v,
253
+ ci_lo=v,
254
+ ci_hi=v,
255
+ std=0.0,
256
+ n_boot=int(n_boot),
257
+ resample=resample,
258
+ )
259
+
260
+
261
+ def _none_metric(
262
+ *,
263
+ resample: Literal["cluster", "iid"],
264
+ ) -> MetricValue:
265
+ """Return a ``MetricValue`` indicating "metric not applicable / not computed"."""
266
+ return MetricValue(
267
+ value=None, ci_lo=None, ci_hi=None, std=None,
268
+ n_boot=0, resample=resample,
269
+ )
270
+
271
+
272
+ # ===================================================================
273
+ # Anchored DA helper
274
+ # ===================================================================
275
+
276
+
277
+ def _close_anchor_da(
278
+ y_true: np.ndarray, y_pred: np.ndarray, close_last: np.ndarray,
279
+ ) -> np.ndarray:
280
+ """Per-row close-anchor directional accuracy (T1).
281
+
282
+ For each row ``i`` and horizon step ``t`` we compare
283
+ ``sign(y_true[i, t] - close_last[i])`` to
284
+ ``sign(y_pred[i, t] - close_last[i])``. Per-row DA is the mean over
285
+ the horizon. Returns a length-N float array (NaN allowed for rows
286
+ where ``close_last`` is NaN).
287
+
288
+ NB: the legacy ``np.diff`` formula is intentionally removed.
289
+ """
290
+ y_true = np.asarray(y_true, dtype=np.float64)
291
+ y_pred = np.asarray(y_pred, dtype=np.float64)
292
+ cl = np.asarray(close_last, dtype=np.float64).reshape(-1, 1)
293
+ if y_true.shape != y_pred.shape:
294
+ raise ValueError(
295
+ f"_close_anchor_da: shape mismatch y_true {y_true.shape} vs y_pred {y_pred.shape}"
296
+ )
297
+ if cl.shape[0] != y_true.shape[0]:
298
+ raise ValueError(
299
+ f"_close_anchor_da: close_last length {cl.shape[0]} != y rows {y_true.shape[0]}"
300
+ )
301
+ true_sign = np.sign(y_true - cl)
302
+ pred_sign = np.sign(y_pred - cl)
303
+ agree = (true_sign == pred_sign).astype(np.float64)
304
+ return agree.mean(axis=1)
305
+
306
+
307
+ # ===================================================================
308
+ # Per-task helpers
309
+ # ===================================================================
310
+
311
+
312
+ def _ape_per_instance(
313
+ pred: np.ndarray, actual: np.ndarray, *, clip: float = _APE_CLIP_DEFAULT,
314
+ near_zero: float = 0.0,
315
+ ) -> tuple[np.ndarray, np.ndarray]:
316
+ """Return (ape_vector_pct, kept_row_mask) clipped at ``clip × 100 %``.
317
+
318
+ Rows where ``|actual| <= near_zero`` (or NaN) are dropped from the
319
+ returned vectors; the second return value is the boolean mask of rows
320
+ that survived (in the original ordering).
321
+ """
322
+ pred = np.asarray(pred, dtype=np.float64).ravel()
323
+ actual = np.asarray(actual, dtype=np.float64).ravel()
324
+ mask = (
325
+ np.isfinite(pred)
326
+ & np.isfinite(actual)
327
+ & (np.abs(actual) > near_zero)
328
+ )
329
+ p = pred[mask]
330
+ a = actual[mask]
331
+ ape = np.abs((p - a) / a)
332
+ if np.isfinite(clip):
333
+ ape = np.minimum(ape, clip)
334
+ return ape * 100.0, mask # percent units
335
+
336
+
337
+ def _normalize_field_col(df: pd.DataFrame) -> pd.DataFrame:
338
+ """T6 (Gen-Eval) GT uses ``generator_field``; T3 uses ``field``."""
339
+ if "field" not in df.columns and "generator_field" in df.columns:
340
+ return df.rename(columns={"generator_field": "field"})
341
+ return df
342
+
343
+
344
+ # -------------------------------------------------------------------
345
+ # T1 — Time-Series Forecasting
346
+ # -------------------------------------------------------------------
347
+
348
+
349
+ def _per_task_score_T1(
350
+ y_true: Any,
351
+ y_pred: Any,
352
+ *,
353
+ cluster_keys: np.ndarray | None,
354
+ close_last: np.ndarray | None,
355
+ n_boot: int | Literal["adaptive"],
356
+ alpha: float,
357
+ seed: int,
358
+ resample: Literal["cluster", "iid"],
359
+ return_sensitivity: bool,
360
+ ) -> dict[str, MetricValue]:
361
+ y_true_a = np.asarray(y_true, dtype=np.float64)
362
+ y_pred_a = np.asarray(y_pred, dtype=np.float64).copy()
363
+ if y_true_a.ndim != 2 or y_pred_a.ndim != 2 or y_true_a.shape != y_pred_a.shape:
364
+ raise ValueError(
365
+ f"T1 score: shape mismatch — y_true {y_true_a.shape}, "
366
+ f"y_pred {y_pred_a.shape}; expected matching (N, horizon) arrays."
367
+ )
368
+ n, horizon = y_true_a.shape
369
+ if n == 0:
370
+ raise ValueError("T1 score: empty arrays.")
371
+
372
+ # NaN penalty: substitute any NaN/inf prediction row with ZERO.
373
+ # Failed parses thus get a clear no-signal penalty (MSE ≈ y_true²,
374
+ # MAE = |y_true|) that is distinct from any meaningful model output.
375
+ nan_row_mask = ~np.isfinite(y_pred_a).all(axis=1)
376
+ if nan_row_mask.any():
377
+ y_pred_a[nan_row_mask, :] = 0.0
378
+
379
+ # Per-instance aggregates (the bootstrap unit is the instance, with
380
+ # cluster bootstrap pooling across ticker rows).
381
+ per_inst_mse = ((y_pred_a - y_true_a) ** 2).mean(axis=1)
382
+ per_inst_mae = np.abs(y_pred_a - y_true_a).mean(axis=1)
383
+
384
+ # Close-anchor DA. Fall back to y_pred[:, 0] if unavailable (documented).
385
+ da_fallback = False
386
+ if close_last is None:
387
+ close_last_v = y_pred_a[:, 0].astype(np.float64)
388
+ da_fallback = True
389
+ logger.warning(
390
+ "T1 score: close_last not supplied; falling back to y_pred[:, 0] "
391
+ "as the directional anchor. This degrades the DA interpretation."
392
+ )
393
+ else:
394
+ close_last_v = np.asarray(close_last, dtype=np.float64).ravel()
395
+ per_inst_da = _close_anchor_da(y_true_a, y_pred_a, close_last_v)
396
+
397
+ out: dict[str, MetricValue] = {}
398
+ out["mse"] = _wrap_metric(
399
+ per_inst_mse, cluster_keys=cluster_keys, agg_fn=np.mean,
400
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
401
+ )
402
+ out["mae"] = _wrap_metric(
403
+ per_inst_mae, cluster_keys=cluster_keys, agg_fn=np.mean,
404
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
405
+ )
406
+ # rmse is sqrt(mean(mse_per_inst)) — bootstrap on the same sqrt(mean)
407
+ # aggregator gives an honest CI.
408
+ rmse_ck = cluster_keys if resample == "cluster" else None
409
+ if rmse_ck is not None:
410
+ unique_rmse_ck = np.unique(np.asarray(rmse_ck).ravel())
411
+ if unique_rmse_ck.size < 2:
412
+ rmse_ck = None
413
+ rmse_val, rmse_lo, rmse_hi, rmse_std, rmse_b = _bootstrap_ci(
414
+ per_inst_mse,
415
+ cluster_keys=rmse_ck,
416
+ agg_fn=lambda x: float(np.sqrt(np.mean(x))),
417
+ n_boot=n_boot, alpha=alpha, seed=seed,
418
+ )
419
+ if not np.isfinite(rmse_val):
420
+ out["rmse"] = _none_metric(resample=resample)
421
+ else:
422
+ out["rmse"] = MetricValue(
423
+ value=float(rmse_val),
424
+ ci_lo=float(rmse_lo) if np.isfinite(rmse_lo) else float(rmse_val),
425
+ ci_hi=float(rmse_hi) if np.isfinite(rmse_hi) else float(rmse_val),
426
+ std=float(rmse_std) if np.isfinite(rmse_std) else 0.0,
427
+ n_boot=int(rmse_b), resample=resample,
428
+ )
429
+ out["directional_accuracy"] = _wrap_metric(
430
+ per_inst_da, cluster_keys=cluster_keys, agg_fn=np.nanmean,
431
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
432
+ )
433
+
434
+ # MASE — Mean Absolute Scaled Error. Per-instance MASE divides each
435
+ # row's MAE by the in-sample seasonal-naive MAE (1-step persistence on
436
+ # close_last as the anchor: |y[h+1] - y[h]| averaged over the lookback
437
+ # is approximated by |y_true[i, 0] - close_last[i]| as a proxy when
438
+ # only the last close is available). Cluster-bootstraps over instances.
439
+ denom = np.abs(y_true_a[:, 0] - close_last_v)
440
+ denom_safe = np.where(denom > 1e-9, denom, np.nan)
441
+ per_inst_mase = per_inst_mae / denom_safe
442
+ valid_mase = np.isfinite(per_inst_mase)
443
+ if valid_mase.any():
444
+ ck_mase = (cluster_keys[valid_mase]
445
+ if cluster_keys is not None else None)
446
+ out["mase"] = _wrap_metric(
447
+ per_inst_mase[valid_mase], cluster_keys=ck_mase, agg_fn=np.mean,
448
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
449
+ )
450
+ else:
451
+ out["mase"] = _none_metric(resample=resample)
452
+
453
+ out["n_instances"] = _scalar_metric(n, resample=resample)
454
+
455
+ if da_fallback:
456
+ # Best-effort metadata — store a sentinel so consumers can detect.
457
+ out["directional_accuracy_anchor_fallback"] = _scalar_metric(
458
+ 1.0, resample=resample,
459
+ )
460
+
461
+ if return_sensitivity:
462
+ # T1's natural target is MSE/MAE; APE-style sensitivity is most
463
+ # meaningful relative to ``close_last``. Compute APE between
464
+ # final-step prediction and the realised final close.
465
+ if close_last is not None:
466
+ denom = np.abs(close_last_v)
467
+ denom_mask = denom > 0
468
+ if denom_mask.any():
469
+ final_err = np.abs(y_pred_a[:, -1] - y_true_a[:, -1])
470
+ ape_full = (final_err[denom_mask] / denom[denom_mask]) * 100.0
471
+ for clip in _APE_SENSITIVITY_CLIPS:
472
+ if np.isfinite(clip):
473
+ clipped = np.minimum(ape_full, clip * 100.0)
474
+ else:
475
+ clipped = ape_full
476
+ key = (
477
+ f"mape_at_clip_{int(clip)}x" if np.isfinite(clip)
478
+ else "mape_at_clip_inf"
479
+ )
480
+ out[key] = _wrap_metric(
481
+ clipped,
482
+ cluster_keys=(
483
+ cluster_keys[denom_mask] if cluster_keys is not None
484
+ else None
485
+ ),
486
+ agg_fn=np.mean, n_boot=n_boot, alpha=alpha, seed=seed,
487
+ resample=resample,
488
+ )
489
+ return out
490
+
491
+
492
+ # -------------------------------------------------------------------
493
+ # T2 / T5 — Point-in-time valuation
494
+ # -------------------------------------------------------------------
495
+
496
+
497
+ def _adapt_t2_t5(y_true: Any, y_pred: Any) -> tuple[pd.DataFrame, pd.DataFrame]:
498
+ """Coerce (y_true, y_pred) into (predictions_df, ground_truth_df).
499
+
500
+ Accepts the unified-API loader contract for T2/T5: ``y_true`` is an
501
+ ``np.ndarray (N,)`` of ``actual_market_cap`` values. Also tolerates
502
+ the legacy DataFrame form ``[ticker, date, actual_market_cap]``.
503
+ """
504
+ if isinstance(y_true, pd.DataFrame) and "actual_market_cap" in y_true.columns:
505
+ gt = y_true.reset_index(drop=True)
506
+ elif isinstance(y_true, (np.ndarray, list, pd.Series)):
507
+ arr = np.asarray(y_true).ravel().astype(np.float64)
508
+ gt = pd.DataFrame({
509
+ "ticker": [f"row_{i}" for i in range(len(arr))],
510
+ "date": pd.NaT,
511
+ "actual_market_cap": arr,
512
+ })
513
+ else:
514
+ raise ValueError(
515
+ f"T2/T5 score: y_true must be ndarray (N,) or DataFrame; "
516
+ f"got {type(y_true).__name__}."
517
+ )
518
+
519
+ if isinstance(y_pred, pd.DataFrame):
520
+ if "predicted_equity_value" in y_pred.columns:
521
+ pred = y_pred.reset_index(drop=True)
522
+ else:
523
+ raise ValueError(
524
+ "T2/T5 score: y_pred DataFrame must have 'predicted_equity_value'."
525
+ )
526
+ else:
527
+ arr = np.asarray(y_pred).ravel()
528
+ if len(arr) != len(gt):
529
+ raise ValueError(
530
+ f"T2/T5 score: y_pred length {len(arr)} != y_true rows {len(gt)}."
531
+ )
532
+ pred = pd.DataFrame({
533
+ "ticker": gt["ticker"].values,
534
+ "date": gt["date"].values,
535
+ "predicted_equity_value": arr,
536
+ })
537
+ return pred, gt
538
+
539
+
540
+ def _per_task_score_T2_T5(
541
+ y_true: Any,
542
+ y_pred: Any,
543
+ *,
544
+ cluster_keys: np.ndarray | None,
545
+ n_boot: int | Literal["adaptive"],
546
+ alpha: float,
547
+ seed: int,
548
+ resample: Literal["cluster", "iid"],
549
+ return_sensitivity: bool,
550
+ ) -> dict[str, MetricValue]:
551
+ pred_df, gt_df = _adapt_t2_t5(y_true, y_pred)
552
+ merged = pred_df.merge(gt_df, on=["ticker", "date"], how="inner")
553
+ # NaN predictions: penalize as 100% APE (substitute median of y_true so the
554
+ # ratio is 1.0). Drops only rows with NaN ground truth or non-positive y_true
555
+ # — those are eval-side data issues, not method failures.
556
+ # Ground truth must never be NaN — if it is, that's a data-side bug
557
+ # (loader / preprocessing). Surface it instead of silently dropping.
558
+ gt_nan = merged["actual_market_cap"].isna().sum()
559
+ if gt_nan > 0:
560
+ raise ValueError(
561
+ f"T2/T5 score: {gt_nan} rows have NaN ground truth (actual_market_cap). "
562
+ "This is a loader/preprocessing bug — fix at data source."
563
+ )
564
+ valid = merged[merged["actual_market_cap"] > 0].reset_index(drop=True)
565
+ if valid.empty:
566
+ # No overlap between predictions and ground truth (or no positive
567
+ # ground truth): every gt row is "missing prediction" → fillna(0)
568
+ # penalty rule applies → APE = 100% per row. Saturate so the cell
569
+ # still scores (no silent score_failed).
570
+ gt_act = pd.to_numeric(gt_df["actual_market_cap"], errors="coerce").values.astype(np.float64)
571
+ gt_keep = np.isfinite(gt_act) & (gt_act > 0)
572
+ if gt_keep.any():
573
+ ape_gt = np.minimum(
574
+ np.abs(gt_act[gt_keep]) / np.abs(gt_act[gt_keep]),
575
+ _APE_CLIP_DEFAULT,
576
+ ) * 100.0
577
+ ck = gt_df["ticker"].astype(str).values[gt_keep] if resample == "cluster" else None
578
+ out: dict[str, MetricValue] = {
579
+ "mape": _wrap_metric(ape_gt, cluster_keys=ck, agg_fn=np.mean,
580
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample),
581
+ "median_ape": _wrap_metric(ape_gt, cluster_keys=ck, agg_fn=np.median,
582
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample),
583
+ "rank_correlation": _scalar_metric(None, resample=resample),
584
+ "rank_p_value": _scalar_metric(None, resample=resample),
585
+ "n_predictions": _scalar_metric(0, resample=resample),
586
+ "n_tickers": _scalar_metric(0, resample=resample),
587
+ }
588
+ return out
589
+ # Fully degenerate (no rows at all on either side) — last-resort scalar.
590
+ return {
591
+ "mape": _scalar_metric(100.0, resample=resample),
592
+ "median_ape": _scalar_metric(100.0, resample=resample),
593
+ "rank_correlation": _scalar_metric(None, resample=resample),
594
+ "rank_p_value": _scalar_metric(None, resample=resample),
595
+ "n_predictions": _scalar_metric(0, resample=resample),
596
+ "n_tickers": _scalar_metric(0, resample=resample),
597
+ }
598
+ # NaN penalty: substitute NaN predictions with ZERO (no-signal). APE
599
+ # = |0 - actual| / |actual| = 100% per row, then clipped at clip_default.
600
+ nan_mask = ~np.isfinite(valid["predicted_equity_value"].values)
601
+ n_nan_substituted = int(nan_mask.sum())
602
+ valid.loc[nan_mask, "predicted_equity_value"] = 0.0
603
+
604
+ # APE clipped at 10× = 1000%, returned in percent.
605
+ ape_pct, kept_mask = _ape_per_instance(
606
+ valid["predicted_equity_value"].values,
607
+ valid["actual_market_cap"].values,
608
+ clip=_APE_CLIP_DEFAULT,
609
+ )
610
+ valid_kept = valid.loc[kept_mask].reset_index(drop=True)
611
+ cluster_kept = (
612
+ valid_kept["ticker"].astype(str).values
613
+ if cluster_keys is None
614
+ else _align_cluster_keys(cluster_keys, len(valid), kept_mask)
615
+ )
616
+
617
+ out: dict[str, MetricValue] = {}
618
+ out["mape"] = _wrap_metric(
619
+ ape_pct, cluster_keys=cluster_kept, agg_fn=np.mean,
620
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
621
+ )
622
+ out["median_ape"] = _wrap_metric(
623
+ ape_pct, cluster_keys=cluster_kept, agg_fn=np.median,
624
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
625
+ )
626
+
627
+ # Spearman rank correlation (closed-form). When either input vector is
628
+ # constant (e.g. dry-run engines emit a single placeholder value) scipy
629
+ # returns NaN; emit None so the metric is treated as "not applicable".
630
+ from scipy.stats import spearmanr
631
+
632
+ rho_raw, p_raw = spearmanr(
633
+ valid_kept["predicted_equity_value"].values,
634
+ valid_kept["actual_market_cap"].values,
635
+ )
636
+ rho = float(rho_raw) if rho_raw is not None and not np.isnan(rho_raw) else None
637
+ p_val = float(p_raw) if p_raw is not None and not np.isnan(p_raw) else None
638
+ out["rank_correlation"] = _scalar_metric(rho, resample=resample)
639
+ out["rank_p_value"] = _scalar_metric(p_val, resample=resample)
640
+
641
+ out["n_predictions"] = _scalar_metric(int(len(valid_kept)), resample=resample)
642
+ out["n_tickers"] = _scalar_metric(
643
+ int(valid_kept["ticker"].nunique()), resample=resample,
644
+ )
645
+
646
+ if return_sensitivity:
647
+ raw_pred = valid["predicted_equity_value"].values
648
+ raw_act = valid["actual_market_cap"].values
649
+ for clip in _APE_SENSITIVITY_CLIPS:
650
+ ape_v, mask = _ape_per_instance(raw_pred, raw_act, clip=clip)
651
+ ck_v = _align_cluster_keys(
652
+ cluster_keys if cluster_keys is not None
653
+ else valid["ticker"].astype(str).values,
654
+ len(valid), mask,
655
+ )
656
+ key = (
657
+ f"mape_at_clip_{int(clip)}x" if np.isfinite(clip)
658
+ else "mape_at_clip_inf"
659
+ )
660
+ out[key] = _wrap_metric(
661
+ ape_v, cluster_keys=ck_v, agg_fn=np.mean,
662
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
663
+ )
664
+ return out
665
+
666
+
667
+ # -------------------------------------------------------------------
668
+ # T3 / T6 — Statement-/Generation-eval
669
+ # -------------------------------------------------------------------
670
+
671
+
672
+ def _per_task_score_T3_T6(
673
+ y_true: Any,
674
+ y_pred: Any,
675
+ *,
676
+ task: str,
677
+ cluster_keys: np.ndarray | None,
678
+ n_boot: int | Literal["adaptive"],
679
+ alpha: float,
680
+ seed: int,
681
+ resample: Literal["cluster", "iid"],
682
+ return_sensitivity: bool,
683
+ ) -> dict[str, MetricValue]:
684
+ """Inputs are long-form DataFrames.
685
+
686
+ * y_true: ``[ticker, fiscal_year, field, value]`` (T6 GT may use
687
+ ``generator_field`` instead of ``field``; we normalise).
688
+ * y_pred: ``[ticker, fiscal_year, field, pred]`` (or ``value`` /
689
+ ``predicted_value`` — we accept either).
690
+ """
691
+ if not isinstance(y_true, pd.DataFrame) or not isinstance(y_pred, pd.DataFrame):
692
+ raise ValueError(
693
+ f"{task} score: y_true and y_pred must be long-form DataFrames."
694
+ )
695
+ gt = _normalize_field_col(y_true).copy()
696
+ pred = _normalize_field_col(y_pred).copy()
697
+
698
+ # Normalise the value column on the prediction side (accept both
699
+ # ``pred`` and ``value`` names so T6 short-circuit emitters can use
700
+ # either).
701
+ pred_value_col: str | None = None
702
+ for cand in ("pred", "value", "predicted_value"):
703
+ if cand in pred.columns:
704
+ pred_value_col = cand
705
+ break
706
+ if pred_value_col is None:
707
+ raise ValueError(
708
+ f"{task} score: y_pred must have a 'pred' (or 'value') column."
709
+ )
710
+
711
+ join_keys = ["ticker", "field"]
712
+ if "fiscal_year" in gt.columns and "fiscal_year" in pred.columns:
713
+ join_keys = ["ticker", "fiscal_year", "field"]
714
+
715
+ n_field_misses = 0
716
+ if "fiscal_year" in gt.columns:
717
+ gt_keys = set(zip(*[gt[k] for k in join_keys]))
718
+ pred_keys = set(zip(*[pred[k] for k in join_keys]))
719
+ n_field_misses = len(gt_keys - pred_keys)
720
+
721
+ merged = pred.merge(
722
+ gt, on=join_keys, how="inner",
723
+ suffixes=("_pred", "_actual"),
724
+ )
725
+ n_fields_matched = int(len(merged))
726
+
727
+ out: dict[str, MetricValue] = {
728
+ "n_fields_matched": _scalar_metric(n_fields_matched, resample=resample),
729
+ "n_field_misses": _scalar_metric(int(n_field_misses), resample=resample),
730
+ "n_tickers": _scalar_metric(
731
+ int(merged["ticker"].nunique()) if not merged.empty else 0,
732
+ resample=resample,
733
+ ),
734
+ }
735
+
736
+ if merged.empty:
737
+ # No (ticker, fiscal_year, field) overlap between predictions and
738
+ # ground truth: every y_true row is "missing" → fillna(0) penalty
739
+ # rule applies → APE = min(|0 - actual| / |actual|, clip) on
740
+ # |actual| ≥ 1.0 rows. Treat as a 100%-saturation failure so the
741
+ # cell still scores (no silent score_failed).
742
+ gt_act = pd.to_numeric(gt["value"], errors="coerce").values.astype(np.float64)
743
+ gt_keep = np.isfinite(gt_act) & (np.abs(gt_act) >= 1.0)
744
+ if gt_keep.any():
745
+ ape_gt = np.minimum(
746
+ np.abs(gt_act[gt_keep]) / np.abs(gt_act[gt_keep]),
747
+ _APE_CLIP_DEFAULT,
748
+ ) * 100.0 # =100% on every row (predict-zero penalty)
749
+ ck = gt["ticker"].astype(str).values[gt_keep] if resample == "cluster" else None
750
+ out["overall_mape"] = _wrap_metric(
751
+ ape_gt, cluster_keys=ck, agg_fn=np.mean,
752
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
753
+ )
754
+ else:
755
+ out["overall_mape"] = _scalar_metric(100.0, resample=resample)
756
+ out["per_field_mape"] = _none_metric(resample=resample)
757
+ if task == "T3":
758
+ out["balance_equation_accuracy"] = _scalar_metric(0.0, resample=resample)
759
+ out["success_rate"] = _scalar_metric(0.0, resample=resample)
760
+ return out
761
+
762
+ # Per-row APE in percent (clip 10×, |actual| ≥ 1.0).
763
+ pred_col = f"{pred_value_col}_pred" if pred_value_col != "value" else "value_pred"
764
+ if pred_col not in merged.columns:
765
+ # When pred_value_col == "value", the suffix path above lands at
766
+ # "value_pred"; otherwise the merge keeps the original name.
767
+ pred_col = pred_value_col + "_pred" if pred_value_col + "_pred" in merged.columns else pred_value_col
768
+ actual_col = "value_actual" if "value_actual" in merged.columns else "value"
769
+
770
+ pred_vals = pd.to_numeric(merged[pred_col], errors="coerce").values
771
+ act_vals = pd.to_numeric(merged[actual_col], errors="coerce").values
772
+ pred_arr = np.asarray(pred_vals, dtype=np.float64)
773
+ act_arr = np.asarray(act_vals, dtype=np.float64)
774
+ # NaN penalty: substitute NaN predictions with ZERO (no-signal)
775
+ # so unparseable field-tuples contribute APE=100% (clipped to
776
+ # _APE_CLIP_DEFAULT) rather than being silently excluded.
777
+ pred_nan = ~np.isfinite(pred_arr)
778
+ if pred_nan.any():
779
+ pred_arr[pred_nan] = 0.0
780
+ keep = np.isfinite(pred_arr) & np.isfinite(act_arr) & (np.abs(act_arr) >= 1.0)
781
+
782
+ ape = np.abs((pred_arr[keep] - act_arr[keep]) / act_arr[keep])
783
+ ape = np.minimum(ape, _APE_CLIP_DEFAULT) * 100.0
784
+
785
+ cluster_for_ape = merged.loc[keep, "ticker"].astype(str).values
786
+
787
+ out["overall_mape"] = _wrap_metric(
788
+ ape, cluster_keys=cluster_for_ape if resample == "cluster" else None,
789
+ agg_fn=np.mean, n_boot=n_boot, alpha=alpha, seed=seed,
790
+ resample=resample,
791
+ )
792
+
793
+ # Per-field MAPE table — single deterministic dict, not a Pydantic
794
+ # MetricValue. We expose the *count* of fields and a value-set under
795
+ # a separate key carrying the dict on `value` is awkward; instead
796
+ # we report n_fields_with_mape and the per-field dict is stored on the
797
+ # metric's dict via a stable plain key (caller can look up).
798
+ per_field: dict[str, float] = {}
799
+ field_weights: dict[str, int] = {}
800
+ for f, grp in merged.loc[keep].groupby(merged.loc[keep, "field"]):
801
+ gp = pd.to_numeric(grp[pred_col], errors="coerce")
802
+ ga = pd.to_numeric(grp[actual_col], errors="coerce")
803
+ valid = pd.DataFrame({"gp": gp, "ga": ga}).dropna()
804
+ valid = valid[valid["ga"].abs() >= 1.0]
805
+ if valid.empty:
806
+ continue
807
+ f_ape = np.minimum(
808
+ np.abs((valid["gp"].values - valid["ga"].values) / valid["ga"].values),
809
+ _APE_CLIP_DEFAULT,
810
+ )
811
+ per_field[str(f)] = float(f_ape.mean()) * 100.0
812
+ field_weights[str(f)] = int(len(valid))
813
+ # Surface per_field as a deterministic scalar metric (n_fields_with_mape).
814
+ out["n_fields_with_mape"] = _scalar_metric(
815
+ len(per_field), resample=resample,
816
+ )
817
+ # Stash the dict on a flat namespace key (callers extract via
818
+ # ``score(...)["per_field_mape_dict"].value`` won't work because
819
+ # MetricValue.value is a float — so we expose a side dict on the
820
+ # function's return as ``per_field_mape`` mapped to a degenerate
821
+ # MetricValue carrying the average MAPE. To preserve the legacy field
822
+ # name we expose the weighted-overall here too).
823
+ if per_field:
824
+ total_w = sum(field_weights.values())
825
+ weighted = sum(per_field[f] * field_weights[f] / total_w for f in per_field)
826
+ # We re-expose this under a stable name so legacy consumers can
827
+ # still pick it up.
828
+ out["per_field_mape_weighted_avg"] = _scalar_metric(
829
+ float(weighted), resample=resample,
830
+ )
831
+
832
+ if task in ("T3", "T6"):
833
+ # Balance-sheet equation accuracy (per ticker).
834
+ bs_checked = 0
835
+ bs_pass = 0
836
+ m = merged.loc[keep]
837
+ for tk in m["ticker"].unique():
838
+ tk_data = m[m["ticker"] == tk]
839
+ fields_str = tk_data["field"].astype(str)
840
+ arow = tk_data[fields_str == "Assets"]
841
+ lrow = tk_data[fields_str == "Liabilities"]
842
+ erow = tk_data[fields_str == "StockholdersEquity"]
843
+ if not arow.empty and not lrow.empty and not erow.empty:
844
+ bs_checked += 1
845
+ a = pd.to_numeric(arow[pred_col].iloc[0], errors="coerce")
846
+ l = pd.to_numeric(lrow[pred_col].iloc[0], errors="coerce")
847
+ e = pd.to_numeric(erow[pred_col].iloc[0], errors="coerce")
848
+ if (
849
+ pd.notna(a) and pd.notna(l) and pd.notna(e)
850
+ and float(a) > 0
851
+ and abs(float(a) - float(l) - float(e)) / float(a) < 0.01
852
+ ):
853
+ bs_pass += 1
854
+ out["balance_equation_accuracy"] = _scalar_metric(
855
+ float(bs_pass / bs_checked) if bs_checked > 0 else float("nan"),
856
+ resample=resample,
857
+ )
858
+ out["balance_equation_checked"] = _scalar_metric(
859
+ int(bs_checked), resample=resample,
860
+ )
861
+
862
+ # success_rate = unique tickers with a parseable prediction / total
863
+ # tickers requested (we approximate via the union of GT tickers).
864
+ n_attempted = int(gt["ticker"].nunique()) if "ticker" in gt.columns else 0
865
+ n_succeeded = int(pred["ticker"].nunique()) if "ticker" in pred.columns else 0
866
+ out["success_rate"] = _scalar_metric(
867
+ float(n_succeeded / n_attempted) if n_attempted > 0 else 0.0,
868
+ resample=resample,
869
+ )
870
+
871
+ if return_sensitivity:
872
+ raw_pred = pred_arr[keep]
873
+ raw_act = act_arr[keep]
874
+ for clip in _APE_SENSITIVITY_CLIPS:
875
+ ape_s = np.abs((raw_pred - raw_act) / raw_act)
876
+ if np.isfinite(clip):
877
+ ape_s = np.minimum(ape_s, clip)
878
+ ape_s = ape_s * 100.0
879
+ key = (
880
+ f"mape_at_clip_{int(clip)}x" if np.isfinite(clip)
881
+ else "mape_at_clip_inf"
882
+ )
883
+ out[key] = _wrap_metric(
884
+ ape_s,
885
+ cluster_keys=cluster_for_ape if resample == "cluster" else None,
886
+ agg_fn=np.mean, n_boot=n_boot, alpha=alpha, seed=seed,
887
+ resample=resample,
888
+ )
889
+ return out
890
+
891
+
892
+ # -------------------------------------------------------------------
893
+ # T4 — Scenario-conditioned forecasting
894
+ # -------------------------------------------------------------------
895
+
896
+
897
+ def _adapt_t4(y_true: Any, y_pred: Any) -> tuple[pd.DataFrame, pd.DataFrame]:
898
+ if isinstance(y_true, pd.DataFrame) and "actual_return_pct" in y_true.columns:
899
+ gt = y_true.reset_index(drop=True)
900
+ elif isinstance(y_true, (np.ndarray, list, pd.Series)):
901
+ arr = np.asarray(y_true).ravel().astype(np.float64)
902
+ gt = pd.DataFrame({
903
+ "scenario_id": [f"sc_{i}" for i in range(len(arr))],
904
+ "ticker": [f"row_{i}" for i in range(len(arr))],
905
+ "actual_return_pct": arr,
906
+ })
907
+ else:
908
+ raise ValueError(
909
+ f"T4 score: y_true must be ndarray (N,) or DataFrame; "
910
+ f"got {type(y_true).__name__}."
911
+ )
912
+ if isinstance(y_pred, pd.DataFrame):
913
+ if "predicted_return_pct" in y_pred.columns:
914
+ pred = y_pred.reset_index(drop=True)
915
+ else:
916
+ raise ValueError(
917
+ "T4 score: y_pred DataFrame must have 'predicted_return_pct'."
918
+ )
919
+ else:
920
+ arr = np.asarray(y_pred).ravel()
921
+ if len(arr) != len(gt):
922
+ raise ValueError(
923
+ f"T4 score: y_pred length {len(arr)} != y_true rows {len(gt)}."
924
+ )
925
+ pred_dict: dict[str, Any] = {
926
+ "scenario_id": gt["scenario_id"].values,
927
+ "ticker": gt["ticker"].values,
928
+ "predicted_return_pct": arr,
929
+ }
930
+ if "event_type" in gt.columns:
931
+ pred_dict["event_type"] = gt["event_type"].values
932
+ pred = pd.DataFrame(pred_dict)
933
+ return pred, gt
934
+
935
+
936
+ def _per_task_score_T4(
937
+ y_true: Any,
938
+ y_pred: Any,
939
+ *,
940
+ cluster_keys: np.ndarray | None,
941
+ n_boot: int | Literal["adaptive"],
942
+ alpha: float,
943
+ seed: int,
944
+ resample: Literal["cluster", "iid"],
945
+ ) -> dict[str, MetricValue]:
946
+ pred_df, gt_df = _adapt_t4(y_true, y_pred)
947
+ merged = pred_df.merge(gt_df, on=["scenario_id", "ticker"], how="inner")
948
+ merged = merged.reset_index(drop=True)
949
+ # Ground truth must never be NaN — surface data-side bugs.
950
+ gt_nan = merged["actual_return_pct"].isna().sum()
951
+ if gt_nan > 0:
952
+ raise ValueError(
953
+ f"T4 score: {gt_nan} rows have NaN ground truth (actual_return_pct). "
954
+ "This is a loader/preprocessing bug — fix at data source."
955
+ )
956
+ if merged.empty:
957
+ # No overlap between predictions and ground truth: fillna(0)
958
+ # penalty → MAE = mean(|actual_return_pct|) using gt rows.
959
+ gt_act = pd.to_numeric(gt_df["actual_return_pct"], errors="coerce").values.astype(np.float64)
960
+ gt_keep = np.isfinite(gt_act)
961
+ if gt_keep.any():
962
+ abs_err_gt = np.abs(gt_act[gt_keep]) # |0 - actual| = |actual|
963
+ ck = (
964
+ gt_df["scenario_id"].astype(str).values[gt_keep]
965
+ if resample == "cluster" and "scenario_id" in gt_df.columns else None
966
+ )
967
+ return {
968
+ "return_mae_pct": _wrap_metric(abs_err_gt, cluster_keys=ck, agg_fn=np.mean,
969
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample),
970
+ "directional_accuracy": _scalar_metric(0.0, resample=resample),
971
+ "ci_calibration_95": _none_metric(resample=resample),
972
+ "n_predictions": _scalar_metric(0, resample=resample),
973
+ "n_scenarios": _scalar_metric(0, resample=resample),
974
+ }
975
+ return {
976
+ "return_mae_pct": _scalar_metric(0.0, resample=resample),
977
+ "directional_accuracy": _scalar_metric(0.0, resample=resample),
978
+ "ci_calibration_95": _none_metric(resample=resample),
979
+ "n_predictions": _scalar_metric(0, resample=resample),
980
+ "n_scenarios": _scalar_metric(0, resample=resample),
981
+ }
982
+ # NaN-prediction penalty: substitute with 0.0 (no-signal); MAE = |actual|.
983
+ nan_mask = ~np.isfinite(merged["predicted_return_pct"].values)
984
+ merged.loc[nan_mask, "predicted_return_pct"] = 0.0
985
+
986
+ pred = merged["predicted_return_pct"].values.astype(np.float64)
987
+ actual = merged["actual_return_pct"].values.astype(np.float64)
988
+ abs_err = np.abs(pred - actual)
989
+ dir_agree = (np.sign(pred) == np.sign(actual)).astype(np.float64)
990
+
991
+ # Cluster by scenario_id for T4 (default). Caller may override.
992
+ if cluster_keys is None:
993
+ cluster_v = merged["scenario_id"].astype(str).values
994
+ else:
995
+ cluster_v = np.asarray(cluster_keys).ravel()
996
+ if cluster_v.size != len(merged):
997
+ # Best-effort: rebuild from merged scenario_id if mismatch.
998
+ cluster_v = merged["scenario_id"].astype(str).values
999
+
1000
+ out: dict[str, MetricValue] = {}
1001
+ out["return_mae_pct"] = _wrap_metric(
1002
+ abs_err, cluster_keys=cluster_v if resample == "cluster" else None,
1003
+ agg_fn=np.mean, n_boot=n_boot, alpha=alpha, seed=seed,
1004
+ resample=resample,
1005
+ )
1006
+ out["directional_accuracy"] = _wrap_metric(
1007
+ dir_agree, cluster_keys=cluster_v if resample == "cluster" else None,
1008
+ agg_fn=np.mean, n_boot=n_boot, alpha=alpha, seed=seed,
1009
+ resample=resample,
1010
+ )
1011
+ if {"predicted_ci_low", "predicted_ci_high"}.issubset(merged.columns):
1012
+ in_ci = (
1013
+ (merged["actual_return_pct"] >= merged["predicted_ci_low"])
1014
+ & (merged["actual_return_pct"] <= merged["predicted_ci_high"])
1015
+ ).astype(np.float64).values
1016
+ out["ci_calibration_95"] = _wrap_metric(
1017
+ in_ci, cluster_keys=cluster_v if resample == "cluster" else None,
1018
+ agg_fn=np.mean, n_boot=n_boot, alpha=alpha, seed=seed,
1019
+ resample=resample,
1020
+ )
1021
+ else:
1022
+ # No quantile predictions -> metric not applicable. Emit a
1023
+ # MetricValue with value=None so downstream consumers can detect
1024
+ # this case via `is None` rather than a NaN finiteness probe.
1025
+ out["ci_calibration_95"] = _none_metric(resample=resample)
1026
+
1027
+ out["n_predictions"] = _scalar_metric(int(len(merged)), resample=resample)
1028
+ out["n_scenarios"] = _scalar_metric(
1029
+ int(merged["scenario_id"].nunique()), resample=resample,
1030
+ )
1031
+ return out
1032
+
1033
+
1034
+ # -------------------------------------------------------------------
1035
+ # T7 — Real-estate valuation
1036
+ # -------------------------------------------------------------------
1037
+
1038
+
1039
+ def _per_task_score_T7(
1040
+ y_true: Any,
1041
+ y_pred: Any,
1042
+ *,
1043
+ cluster_keys: np.ndarray | None,
1044
+ n_boot: int | Literal["adaptive"],
1045
+ alpha: float,
1046
+ seed: int,
1047
+ resample: Literal["cluster", "iid"],
1048
+ return_sensitivity: bool,
1049
+ ) -> dict[str, MetricValue]:
1050
+ if not isinstance(y_true, pd.DataFrame) or not isinstance(y_pred, pd.DataFrame):
1051
+ raise ValueError("T7 score: both y_true and y_pred must be DataFrames.")
1052
+
1053
+ if "address" not in y_true.columns or "address" not in y_pred.columns:
1054
+ # Fall back to positional alignment.
1055
+ merged = pd.concat([
1056
+ y_pred.reset_index(drop=True),
1057
+ y_true.reset_index(drop=True).add_suffix("_actual"),
1058
+ ], axis=1)
1059
+ else:
1060
+ merged = y_pred.merge(
1061
+ y_true, on="address", how="inner", suffixes=("_pred", "_actual"),
1062
+ )
1063
+ if merged.empty:
1064
+ # No overlapping addresses: fillna(0) penalty per gt rent + price
1065
+ # column. Saturates to 100% APE per row.
1066
+ out: dict[str, MetricValue] = {
1067
+ "n_predictions": _scalar_metric(0, resample=resample),
1068
+ }
1069
+ for target, actual_cands in [
1070
+ ("rent", ["rent", "rentEstimate", "rent_estimate"]),
1071
+ ("price", ["price", "lastSalePrice", "last_sale_price"]),
1072
+ ]:
1073
+ actual_col = next((c for c in actual_cands if c in y_true.columns), None)
1074
+ if actual_col is None:
1075
+ out[f"{target}_MAPE"] = _scalar_metric(float("nan"), resample=resample)
1076
+ out[f"{target}_median_APE"] = _scalar_metric(float("nan"), resample=resample)
1077
+ out[f"{target}_n_valid"] = _scalar_metric(0, resample=resample)
1078
+ continue
1079
+ gt_act = pd.to_numeric(y_true[actual_col], errors="coerce").values.astype(np.float64)
1080
+ gt_keep = np.isfinite(gt_act) & (np.abs(gt_act) > 0)
1081
+ if gt_keep.any():
1082
+ ape_gt = np.minimum(
1083
+ np.abs(gt_act[gt_keep]) / np.abs(gt_act[gt_keep]),
1084
+ _APE_CLIP_DEFAULT,
1085
+ ) * 100.0
1086
+ ck = (
1087
+ y_true["address"].astype(str).values[gt_keep]
1088
+ if resample == "cluster" and "address" in y_true.columns else None
1089
+ )
1090
+ out[f"{target}_MAPE"] = _wrap_metric(
1091
+ ape_gt, cluster_keys=ck, agg_fn=np.mean,
1092
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
1093
+ )
1094
+ out[f"{target}_median_APE"] = _wrap_metric(
1095
+ ape_gt, cluster_keys=ck, agg_fn=np.median,
1096
+ n_boot=n_boot, alpha=alpha, seed=seed, resample=resample,
1097
+ )
1098
+ out[f"{target}_n_valid"] = _scalar_metric(int(gt_keep.sum()), resample=resample)
1099
+ else:
1100
+ out[f"{target}_MAPE"] = _scalar_metric(100.0, resample=resample)
1101
+ out[f"{target}_median_APE"] = _scalar_metric(100.0, resample=resample)
1102
+ out[f"{target}_n_valid"] = _scalar_metric(0, resample=resample)
1103
+ return out
1104
+
1105
+ out: dict[str, MetricValue] = {
1106
+ "n_predictions": _scalar_metric(int(len(merged)), resample=resample),
1107
+ }
1108
+
1109
+ for target, pred_cands, actual_cands in [
1110
+ ("rent",
1111
+ ["pred_rent", "predicted_rent", "rent_pred"],
1112
+ ["rent_actual", "rent", "rentEstimate_actual", "rent_estimate_actual"]),
1113
+ ("price",
1114
+ ["pred_price", "predicted_price", "price_pred"],
1115
+ ["price_actual", "price", "lastSalePrice_actual", "last_sale_price_actual"]),
1116
+ ]:
1117
+ pred_col = next((c for c in pred_cands if c in merged.columns), None)
1118
+ actual_col = next((c for c in actual_cands if c in merged.columns), None)
1119
+ if pred_col is None or actual_col is None:
1120
+ out[f"{target}_MAPE"] = _scalar_metric(float("nan"), resample=resample)
1121
+ out[f"{target}_median_APE"] = _scalar_metric(
1122
+ float("nan"), resample=resample,
1123
+ )
1124
+ out[f"{target}_n_valid"] = _scalar_metric(0, resample=resample)
1125
+ continue
1126
+
1127
+ pred_vals = pd.to_numeric(merged[pred_col], errors="coerce").values
1128
+ actual_vals = pd.to_numeric(merged[actual_col], errors="coerce").values
1129
+ # NaN penalty: substitute NaN predictions with ZERO (no-signal).
1130
+ # APE = 100% per row, clipped at clip_default.
1131
+ nan_mask = ~np.isfinite(pred_vals)
1132
+ if nan_mask.any():
1133
+ pred_vals = np.where(nan_mask, 0.0, pred_vals)
1134
+ ape_pct, mask = _ape_per_instance(
1135
+ pred_vals, actual_vals, clip=_APE_CLIP_DEFAULT,
1136
+ )
1137
+ if ape_pct.size == 0:
1138
+ out[f"{target}_MAPE"] = _scalar_metric(float("nan"), resample=resample)
1139
+ out[f"{target}_median_APE"] = _scalar_metric(
1140
+ float("nan"), resample=resample,
1141
+ )
1142
+ out[f"{target}_n_valid"] = _scalar_metric(0, resample=resample)
1143
+ continue
1144
+
1145
+ # T7 cluster bootstrap = address-level (one cluster per row, so it
1146
+ # collapses to IID) by convention. If the caller supplied
1147
+ # cluster_keys (e.g. metro / property_type) honour that.
1148
+ if cluster_keys is not None:
1149
+ ck = _align_cluster_keys(cluster_keys, len(merged), mask)
1150
+ else:
1151
+ ck = merged.loc[mask, "address"].astype(str).values if "address" in merged.columns else None
1152
+
1153
+ out[f"{target}_MAPE"] = _wrap_metric(
1154
+ ape_pct, cluster_keys=ck if resample == "cluster" else None,
1155
+ agg_fn=np.mean, n_boot=n_boot, alpha=alpha, seed=seed,
1156
+ resample=resample,
1157
+ )
1158
+ out[f"{target}_median_APE"] = _wrap_metric(
1159
+ ape_pct, cluster_keys=ck if resample == "cluster" else None,
1160
+ agg_fn=np.median, n_boot=n_boot, alpha=alpha, seed=seed,
1161
+ resample=resample,
1162
+ )
1163
+ out[f"{target}_n_valid"] = _scalar_metric(
1164
+ int(ape_pct.size), resample=resample,
1165
+ )
1166
+
1167
+ if return_sensitivity:
1168
+ for clip in _APE_SENSITIVITY_CLIPS:
1169
+ ape_v, mask_v = _ape_per_instance(
1170
+ pred_vals, actual_vals, clip=clip,
1171
+ )
1172
+ ck_v = (
1173
+ _align_cluster_keys(cluster_keys, len(merged), mask_v)
1174
+ if cluster_keys is not None
1175
+ else (
1176
+ merged.loc[mask_v, "address"].astype(str).values
1177
+ if "address" in merged.columns else None
1178
+ )
1179
+ )
1180
+ key = (
1181
+ f"{target}_MAPE_at_clip_{int(clip)}x"
1182
+ if np.isfinite(clip) else f"{target}_MAPE_at_clip_inf"
1183
+ )
1184
+ out[key] = _wrap_metric(
1185
+ ape_v, cluster_keys=ck_v if resample == "cluster" else None,
1186
+ agg_fn=np.mean, n_boot=n_boot, alpha=alpha, seed=seed,
1187
+ resample=resample,
1188
+ )
1189
+ return out
1190
+
1191
+
1192
+ # ===================================================================
1193
+ # Cluster-key alignment helper
1194
+ # ===================================================================
1195
+
1196
+
1197
+ def _align_cluster_keys(
1198
+ cluster_keys: Any,
1199
+ n_total: int,
1200
+ mask: np.ndarray,
1201
+ ) -> np.ndarray | None:
1202
+ """Return cluster_keys masked to the rows kept (or None if no keys).
1203
+
1204
+ Tolerant fallbacks:
1205
+ * If ``cluster_keys`` is shorter than ``n_total`` (the upstream merge
1206
+ dropped rows beyond what the caller knows about), drop cluster_keys
1207
+ and let the bootstrap fall back to IID — better than raising.
1208
+ """
1209
+ if cluster_keys is None:
1210
+ return None
1211
+ arr = np.asarray(cluster_keys).ravel()
1212
+ if arr.size == n_total:
1213
+ return arr[mask]
1214
+ if arr.size == int(mask.sum()):
1215
+ return arr # already masked
1216
+ # Length mismatch: typically because the eval-side merge / dropna
1217
+ # discarded rows the caller didn't know about. Fall back to None
1218
+ # (degenerate IID bootstrap) rather than raising.
1219
+ return None
1220
+
1221
+
1222
+ # ===================================================================
1223
+ # Public API: score
1224
+ # ===================================================================
1225
+
1226
+
1227
+ def score(
1228
+ task: str,
1229
+ y_true: Any,
1230
+ y_pred: Any,
1231
+ *,
1232
+ cluster_keys: Any = None,
1233
+ close_last: Any = None,
1234
+ resample: Literal["cluster", "iid"] = "cluster",
1235
+ n_boot: int | Literal["adaptive"] = "adaptive",
1236
+ alpha: float = 0.05,
1237
+ seed: int = 42,
1238
+ return_sensitivity: bool = False,
1239
+ ) -> dict[str, MetricValue]:
1240
+ """Score a (task, y_true, y_pred) triple.
1241
+
1242
+ Returns
1243
+ -------
1244
+ dict[str, MetricValue]
1245
+ Per-task metric mapping. Keys per task are documented in the module
1246
+ docstring; every value is a Pydantic ``MetricValue`` carrying
1247
+ ``value, ci_lo, ci_hi, std, n_boot, resample``.
1248
+
1249
+ Notes
1250
+ -----
1251
+ * The default resample is ``"cluster"``; on panel data this is the
1252
+ statistically correct choice.
1253
+ * If ``cluster_keys`` is None, the function derives it from the inputs:
1254
+ ``ticker`` for T1/T2/T3/T5/T6/T7, ``scenario_id`` for T4. The caller
1255
+ may override.
1256
+ * ``close_last`` is a 1-D float array aligned to ``y_true`` rows for T1.
1257
+ If unavailable we fall back to ``y_pred[:, 0]`` and emit a warning;
1258
+ the metric ``directional_accuracy_anchor_fallback`` is set to 1.0 so
1259
+ consumers can detect the fallback.
1260
+ * ``n_boot="adaptive"`` starts at 1,000 bootstrap draws and escalates
1261
+ to 10,000 if the relative CI half-width exceeds 5%.
1262
+ """
1263
+ if resample not in ("cluster", "iid"):
1264
+ raise ValueError(f"resample must be 'cluster' or 'iid', got {resample!r}")
1265
+
1266
+ ck_arr: np.ndarray | None
1267
+ if cluster_keys is None:
1268
+ ck_arr = None
1269
+ else:
1270
+ ck_arr = np.asarray(cluster_keys).ravel()
1271
+
1272
+ cl_arr: np.ndarray | None
1273
+ if close_last is None:
1274
+ cl_arr = None
1275
+ else:
1276
+ cl_arr = np.asarray(close_last, dtype=np.float64).ravel()
1277
+
1278
+ if task == "T1":
1279
+ if ck_arr is None and isinstance(y_true, np.ndarray):
1280
+ # No cluster keys — caller didn't pass meta["ticker"]; we cannot
1281
+ # derive ticker from y_true alone. Run cluster bootstrap with a
1282
+ # one-cluster-per-row degenerate (collapses to IID).
1283
+ ck_arr = np.arange(len(y_true))
1284
+ return _per_task_score_T1(
1285
+ y_true, y_pred,
1286
+ cluster_keys=ck_arr, close_last=cl_arr,
1287
+ n_boot=n_boot, alpha=alpha, seed=seed,
1288
+ resample=resample, return_sensitivity=return_sensitivity,
1289
+ )
1290
+
1291
+ if task in ("T2", "T5"):
1292
+ return _per_task_score_T2_T5(
1293
+ y_true, y_pred,
1294
+ cluster_keys=ck_arr,
1295
+ n_boot=n_boot, alpha=alpha, seed=seed,
1296
+ resample=resample, return_sensitivity=return_sensitivity,
1297
+ )
1298
+
1299
+ if task in ("T3", "T6"):
1300
+ return _per_task_score_T3_T6(
1301
+ y_true, y_pred,
1302
+ task=task,
1303
+ cluster_keys=ck_arr,
1304
+ n_boot=n_boot, alpha=alpha, seed=seed,
1305
+ resample=resample, return_sensitivity=return_sensitivity,
1306
+ )
1307
+
1308
+ if task == "T4":
1309
+ return _per_task_score_T4(
1310
+ y_true, y_pred,
1311
+ cluster_keys=ck_arr,
1312
+ n_boot=n_boot, alpha=alpha, seed=seed,
1313
+ resample=resample,
1314
+ )
1315
+
1316
+ if task == "T7":
1317
+ return _per_task_score_T7(
1318
+ y_true, y_pred,
1319
+ cluster_keys=ck_arr,
1320
+ n_boot=n_boot, alpha=alpha, seed=seed,
1321
+ resample=resample, return_sensitivity=return_sensitivity,
1322
+ )
1323
+
1324
+ raise ValueError(f"Unknown task: {task!r}")
1325
+
1326
+
1327
+ # ===================================================================
1328
+ # Multiple-comparisons correction — per task
1329
+ # ===================================================================
1330
+
1331
+
1332
+ def _holm_correction(p_values: np.ndarray, alpha: float = 0.05) -> tuple[np.ndarray, np.ndarray]:
1333
+ """Holm-Bonferroni step-down correction.
1334
+
1335
+ Returns ``(p_adjusted, reject)`` arrays of the same length as
1336
+ ``p_values``, where ``p_adjusted`` is monotone-increasing in original
1337
+ rank and ``reject`` is the boolean rejection vector at family-wise
1338
+ error rate ``alpha``.
1339
+ """
1340
+ p = np.asarray(p_values, dtype=np.float64).ravel()
1341
+ m = p.size
1342
+ if m == 0:
1343
+ return p, np.array([], dtype=bool)
1344
+ order = np.argsort(p)
1345
+ p_sorted = p[order]
1346
+ p_adj_sorted = np.empty(m, dtype=np.float64)
1347
+ running_max = 0.0
1348
+ for i in range(m):
1349
+ adj = (m - i) * p_sorted[i]
1350
+ running_max = max(running_max, adj)
1351
+ p_adj_sorted[i] = min(running_max, 1.0)
1352
+ # Unsort.
1353
+ p_adj = np.empty_like(p_adj_sorted)
1354
+ p_adj[order] = p_adj_sorted
1355
+ return p_adj, p_adj <= alpha
1356
+
1357
+
1358
+ def _bh_correction(p_values: np.ndarray, alpha: float = 0.05) -> tuple[np.ndarray, np.ndarray]:
1359
+ """Benjamini-Hochberg FDR correction."""
1360
+ p = np.asarray(p_values, dtype=np.float64).ravel()
1361
+ m = p.size
1362
+ if m == 0:
1363
+ return p, np.array([], dtype=bool)
1364
+ order = np.argsort(p)
1365
+ p_sorted = p[order]
1366
+ ranks = np.arange(1, m + 1)
1367
+ p_adj_sorted_raw = p_sorted * m / ranks
1368
+ # Enforce monotonicity (running min from the right).
1369
+ p_adj_sorted = np.minimum.accumulate(p_adj_sorted_raw[::-1])[::-1]
1370
+ p_adj_sorted = np.minimum(p_adj_sorted, 1.0)
1371
+ p_adj = np.empty_like(p_adj_sorted)
1372
+ p_adj[order] = p_adj_sorted
1373
+ return p_adj, p_adj <= alpha
1374
+
1375
+
1376
+ def _extract_record(rec: Any) -> dict[str, Any]:
1377
+ """Coerce a record (Pydantic / dict / dataclass) to a plain dict."""
1378
+ if isinstance(rec, dict):
1379
+ return rec
1380
+ if hasattr(rec, "model_dump"):
1381
+ return rec.model_dump()
1382
+ if hasattr(rec, "__dict__"):
1383
+ return dict(rec.__dict__)
1384
+ raise TypeError(f"Cannot extract record of type {type(rec).__name__}")
1385
+
1386
+
1387
+ def _extract_metric_value(metrics: Any, key: str) -> tuple[float, float, float, int]:
1388
+ """Pull (value, std, n_boot, ok) out of a metric dict-or-MetricValue.
1389
+
1390
+ Returns ``ok=0`` when the metric is missing or its ``value`` is ``None``
1391
+ (semantic "not applicable"); finite values pass through with ``ok=1``.
1392
+ """
1393
+ m = metrics.get(key) if isinstance(metrics, dict) else None
1394
+ if m is None:
1395
+ return float("nan"), float("nan"), 0, 0
1396
+ if isinstance(m, MetricValue):
1397
+ if m.value is None:
1398
+ return float("nan"), float("nan"), int(m.n_boot), 0
1399
+ std = float(m.std) if m.std is not None else float("nan")
1400
+ return float(m.value), std, int(m.n_boot), 1
1401
+ if isinstance(m, dict):
1402
+ v = m.get("value", None)
1403
+ if v is None:
1404
+ return float("nan"), float("nan"), int(m.get("n_boot", 0)), 0
1405
+ return (
1406
+ float(v),
1407
+ float(m.get("std", float("nan")) if m.get("std", None) is not None else float("nan")),
1408
+ int(m.get("n_boot", 0)),
1409
+ 1,
1410
+ )
1411
+ return float("nan"), float("nan"), 0, 0
1412
+
1413
+
1414
+ # Default headline metric per task (lower-is-better unless noted).
1415
+ _HEADLINE_METRIC: dict[str, tuple[str, bool]] = {
1416
+ "T1": ("mse", True),
1417
+ "T2": ("mape", True),
1418
+ "T3": ("overall_mape", True),
1419
+ "T4": ("return_mae_pct", True),
1420
+ "T5": ("mape", True),
1421
+ "T6": ("overall_mape", True),
1422
+ "T7": ("rent_MAPE", True),
1423
+ }
1424
+
1425
+
1426
+ def compare_methods(
1427
+ task: str,
1428
+ records: list,
1429
+ *,
1430
+ correction: Literal["holm", "bh"] = "holm",
1431
+ alpha: float = 0.05,
1432
+ headline_metric: str | None = None,
1433
+ ) -> "pd.DataFrame":
1434
+ """Pairwise compare every method on ``task`` against the best baseline.
1435
+
1436
+ Parameters
1437
+ ----------
1438
+ task
1439
+ ``"T1"`` .. ``"T7"``.
1440
+ records
1441
+ Iterable of ``RunRecord``-shaped objects (Pydantic models, dicts,
1442
+ or anything with ``.method_id``, ``.task``, ``.metrics``).
1443
+ correction
1444
+ ``"holm"`` (default; FWER) or ``"bh"`` (FDR). Per-task scope only —
1445
+ no cross-task FWER claim.
1446
+ alpha
1447
+ Family-wise error rate (Holm) or false discovery rate (BH).
1448
+ headline_metric
1449
+ Override the per-task headline metric (default uses
1450
+ ``_HEADLINE_METRIC[task]``). The metric must exist on every
1451
+ record's ``metrics`` dict.
1452
+
1453
+ Returns
1454
+ -------
1455
+ DataFrame
1456
+ One row per method with columns
1457
+ ``[method_id, value, std, n_boot, z, p_value, p_adj, reject_null]``.
1458
+ The lowest-value method (or highest, if ``lower_is_better=False``)
1459
+ is the reference; its ``p_value`` is NaN.
1460
+ """
1461
+ if task not in _HEADLINE_METRIC:
1462
+ raise ValueError(f"Unknown task: {task!r}")
1463
+ metric_key, lower_is_better = _HEADLINE_METRIC[task]
1464
+ if headline_metric is not None:
1465
+ metric_key = headline_metric
1466
+
1467
+ rows: list[dict[str, Any]] = []
1468
+ for rec in records:
1469
+ d = _extract_record(rec)
1470
+ if d.get("task") != task:
1471
+ continue
1472
+ metrics = d.get("metrics")
1473
+ if not metrics:
1474
+ continue
1475
+ v, std, n_b, ok = _extract_metric_value(metrics, metric_key)
1476
+ if not ok or not np.isfinite(v):
1477
+ continue
1478
+ rows.append({
1479
+ "method_id": d.get("method_id", "?"),
1480
+ "value": v,
1481
+ "std": std,
1482
+ "n_boot": n_b,
1483
+ })
1484
+ if not rows:
1485
+ return pd.DataFrame(
1486
+ columns=["method_id", "value", "std", "n_boot",
1487
+ "z", "p_value", "p_adj", "reject_null"]
1488
+ )
1489
+
1490
+ df = pd.DataFrame(rows)
1491
+ # Pick the reference method.
1492
+ if lower_is_better:
1493
+ ref_idx = int(df["value"].idxmin())
1494
+ else:
1495
+ ref_idx = int(df["value"].idxmax())
1496
+ ref_v = float(df.loc[ref_idx, "value"])
1497
+ ref_std = float(df.loc[ref_idx, "std"])
1498
+
1499
+ # Two-sided z test using bootstrap stds; combined under independence
1500
+ # (this is conservative — bootstrap stds are within-method only;
1501
+ # cross-method covariance is unknown without the full bootstrap
1502
+ # distribution, which we don't carry on RunRecord by design).
1503
+ from scipy.stats import norm
1504
+
1505
+ z_vals: list[float] = []
1506
+ p_vals: list[float] = []
1507
+ for i, row in df.iterrows():
1508
+ if i == ref_idx:
1509
+ z_vals.append(float("nan"))
1510
+ p_vals.append(float("nan"))
1511
+ continue
1512
+ denom = float(np.sqrt(row["std"] ** 2 + ref_std ** 2))
1513
+ if denom <= 0 or not np.isfinite(denom):
1514
+ z_vals.append(float("nan"))
1515
+ p_vals.append(float("nan"))
1516
+ continue
1517
+ z = (float(row["value"]) - ref_v) / denom
1518
+ z_vals.append(z)
1519
+ p_vals.append(float(2.0 * (1.0 - norm.cdf(abs(z)))))
1520
+
1521
+ df["z"] = z_vals
1522
+ df["p_value"] = p_vals
1523
+
1524
+ p_arr = np.asarray(df["p_value"].values, dtype=np.float64)
1525
+ finite = np.isfinite(p_arr)
1526
+ p_finite = p_arr[finite]
1527
+ if correction == "holm":
1528
+ p_adj_finite, reject_finite = _holm_correction(p_finite, alpha=alpha)
1529
+ elif correction == "bh":
1530
+ p_adj_finite, reject_finite = _bh_correction(p_finite, alpha=alpha)
1531
+ else:
1532
+ raise ValueError(f"correction must be 'holm' or 'bh', got {correction!r}")
1533
+
1534
+ p_adj = np.full_like(p_arr, np.nan)
1535
+ reject = np.zeros(p_arr.size, dtype=bool)
1536
+ p_adj[finite] = p_adj_finite
1537
+ reject[finite] = reject_finite
1538
+ df["p_adj"] = p_adj
1539
+ df["reject_null"] = reject
1540
+
1541
+ return df.sort_values("value", ascending=lower_is_better).reset_index(drop=True)
1542
+
1543
+
1544
+ # ===================================================================
1545
+ # Convenience re-exports
1546
+ # ===================================================================
1547
+
1548
+ __all__ = [
1549
+ "score",
1550
+ "compare_methods",
1551
+ "MetricValue",
1552
+ "_bootstrap_ci",
1553
+ "_close_anchor_da",
1554
+ "_holm_correction",
1555
+ "_bh_correction",
1556
+ ]
code/experiments/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Experiment orchestration: panel registry, runners, reporting."""
code/experiments/__main__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI entry: ``python -m projects.agent_builder.scripts.whatif_bench.experiments``.
2
+
3
+ Thin wrapper over :func:`experiments.run_all.main` so the package can be
4
+ launched with ``-m experiments``. Argument surface is documented in
5
+ :mod:`experiments.run_all`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+
12
+ from .run_all import main
13
+
14
+
15
+ if __name__ == "__main__":
16
+ sys.exit(main())
code/experiments/adapters/scout_qlora_smoke_20260519T062736Z/fitted_fields.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae04d62bcb8df1cf7c443eb000ad76031ddedd5db5d544664ef1bec4b0f0a961
3
+ size 80985
code/experiments/adapters/scout_qlora_smoke_20260519T070504Z/fitted_fields.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae04d62bcb8df1cf7c443eb000ad76031ddedd5db5d544664ef1bec4b0f0a961
3
+ size 80985
code/experiments/aggregate_results.py ADDED
@@ -0,0 +1,586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Aggregate Phase-4 :class:`RunRecord` JSONs into per-task tables.
2
+
3
+ Reads one or more ``RunRecord``-list JSON files (the canonical artefact
4
+ written by :mod:`experiments.run_all`), validates each via Pydantic, and
5
+ emits a per-task pandas DataFrame keyed by
6
+ ``[method_id, metric_name, value, ci_lo, ci_hi, n_boot]``.
7
+
8
+ Compared to the legacy aggregator (which merged per-family `_results.json`
9
+ dicts), this module:
10
+
11
+ 1. Accepts an input glob (``--input``) defaulting to
12
+ ``experiments/results/canon_*.json``.
13
+ 2. Round-trips JSON through ``pydantic.TypeAdapter[list[RunRecord]]``.
14
+ 3. Skips records with ``status != "ok"`` (footnote count printed).
15
+ 4. Migrates any ``schema_version=1`` records via
16
+ :func:`tools.migrate_results._migrate_one` before validation.
17
+ 5. Groups by ``(task, method_id, granularity, seed)`` and emits one
18
+ DataFrame per task with one row per ``(method, metric)`` pair.
19
+
20
+ CLI::
21
+
22
+ python -m projects.agent_builder.scripts.whatif_bench.experiments.aggregate_results \\
23
+ --input 'experiments/results/canon_*.json' \\
24
+ --output experiments/paper_artifacts/aggregate.parquet
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import glob
31
+ import json
32
+ import logging
33
+ from collections import defaultdict
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+ import pandas as pd
38
+ import pydantic
39
+
40
+ from .. import config
41
+ from ..macrolens import RunRecord
42
+ from ..tools.migrate_results import _migrate_one
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+
47
+ _TASK_ORDER: tuple[str, ...] = ("T1", "T2", "T3", "T4", "T5", "T6", "T7")
48
+
49
+
50
+ def _panel_method_ids() -> tuple[set[str], set[str]]:
51
+ """Return ``(panel_methods, ablation_methods)`` as id sets.
52
+
53
+ Allow-list source of truth: only ``method_id``s in
54
+ :data:`experiments.panel.ALL_METHODS` (the 19 canonical panel methods)
55
+ plus the deferred FT slot (``"scout_ft"``, Family-7) are surfaced in
56
+ aggregation. Anything else (stale ``gpt_oss_120b``, ``gemma4``, etc.)
57
+ is invisible to the aggregator.
58
+
59
+ The ablation allow-list is :data:`panel.ABLATION_MODEL_IDS`
60
+ (``gpt51``, ``gemini3_flash``) ∪ ``{"lightgbm"}`` (Phase 2.1) ∪
61
+ ``{"scout_ft"}`` (Phase 3.1).
62
+ """
63
+ from .panel import ABLATION_MODEL_IDS, ALL_METHODS as _PANEL_METHODS
64
+
65
+ panel = {m.id for m in _PANEL_METHODS}
66
+ panel.add("scout_ft") # deferred Family-7 FT slot (Phase 3.1)
67
+ ablation = set(ABLATION_MODEL_IDS) | {"lightgbm", "scout_ft"}
68
+ return panel, ablation
69
+
70
+
71
+ # Per-task primary metric for the leaderboard view emitted by ``--summary``.
72
+ # Mirrors :data:`experiments.panel.TASK_METADATA` but resolved to the metric
73
+ # *key* the runners emit (matches what aggregate_results writes to the long
74
+ # DataFrame's ``metric_name`` column).
75
+ _PRIMARY_METRIC_KEY: dict[str, str] = {
76
+ "T1": "mse",
77
+ "T2": "median_ape",
78
+ "T3": "overall_mape",
79
+ "T4": "return_mae_pct",
80
+ "T5": "median_ape",
81
+ "T6": "overall_mape",
82
+ "T7": "rent_MAPE",
83
+ }
84
+
85
+ # Whether lower is better (True) or higher is better (False) for each task's
86
+ # primary metric. All current MacroLens primary metrics are loss-style; this
87
+ # table stays explicit for safety in case of future additions.
88
+ _PRIMARY_METRIC_LOWER_IS_BETTER: dict[str, bool] = {
89
+ "T1": True, "T2": True, "T3": True, "T4": True,
90
+ "T5": True, "T6": True, "T7": True,
91
+ }
92
+
93
+
94
+ def _load_records(
95
+ paths: list[Path],
96
+ ) -> tuple[list[tuple[RunRecord, int | None]], int, int, int, int, int]:
97
+ """Read every JSON in ``paths`` and validate as ``list[RunRecord]``.
98
+
99
+ Returns ``(records, n_skipped_non_ok, n_migrated_v1, n_dedup_dropped,
100
+ n_partial_dropped, n_off_panel)``.
101
+
102
+ Validity gates (in order):
103
+ 1. dedupe (method_id, task, granularity, seed) keeping the LATEST
104
+ ``timestamp`` (mtime tiebreaker) — newer reruns supersede older
105
+ tainted records EVEN IF the newer record is ``predict_failed``.
106
+ This ensures a rerun that legitimately fails replaces an old
107
+ silently-tainted "ok" record.
108
+ 2. status == "ok" — drop the record if the latest run failed.
109
+ 3. **All-NaN gate**: drop records whose primary-metric ``value`` is
110
+ ``None`` (eval returned None because every prediction was NaN).
111
+ 4. **Partial-NaN gate**: drop records whose ``n_predictions`` (or
112
+ ``n_instances``) is less than the canonical eval N for that task,
113
+ OR whose ``success_rate`` (T3/T6) is < 1.0. This catches the
114
+ silent-NaN-on-some-rows cells that the all-NaN gate misses.
115
+ """
116
+ import re as _re
117
+ from ..dataloader.budgets import EVAL_N_PER_TASK
118
+
119
+ adapter = pydantic.TypeAdapter(list[RunRecord])
120
+ n_migrated = 0
121
+
122
+ # Filename horizon parser: canon files written by the MH chains carry
123
+ # ``_h<H>_`` in the filename. The RunRecord schema does not store
124
+ # horizon explicitly, so we recover it from the source path so the
125
+ # aggregator can distinguish two horizons on the same (method, task,
126
+ # granularity, seed) tuple instead of collapsing them.
127
+ _H_RE = _re.compile(r"_h(\d+)_")
128
+
129
+ def _file_horizon(path: Path) -> int | None:
130
+ m = _H_RE.search(path.name)
131
+ if m is None:
132
+ return None
133
+ try:
134
+ return int(m.group(1))
135
+ except ValueError:
136
+ return None
137
+
138
+ # Allow-list filter: load the canonical 19-panel + FT-slot ids. Records
139
+ # whose method_id is outside this set are silently dropped here so they
140
+ # never reach dedupe, leaderboard, or coverage stages.
141
+ panel_ids, _ablation_ids = _panel_method_ids()
142
+
143
+ # First pass: gather ALL records (including non-ok) so dedupe can let
144
+ # newer rerun-failures supersede older partial-coverage "ok" records.
145
+ candidates: list[tuple[RunRecord, float, int | None]] = []
146
+ n_off_panel = 0
147
+ for p in paths:
148
+ try:
149
+ raw = json.loads(p.read_text())
150
+ except (OSError, json.JSONDecodeError) as exc:
151
+ logger.warning("Skipping unreadable JSON %s: %s", p, exc)
152
+ continue
153
+ if not isinstance(raw, list):
154
+ logger.warning("Skipping non-list JSON %s", p)
155
+ continue
156
+
157
+ migrated_raw: list[dict[str, Any]] = []
158
+ for rec in raw:
159
+ if isinstance(rec, dict) and rec.get("schema_version") != 2:
160
+ migrated_raw.append(_migrate_one(rec, p))
161
+ n_migrated += 1
162
+ else:
163
+ migrated_raw.append(rec)
164
+
165
+ try:
166
+ recs = adapter.validate_python(migrated_raw)
167
+ except pydantic.ValidationError as exc:
168
+ logger.warning("Skipping %s: validation failed: %s", p, exc)
169
+ continue
170
+
171
+ try:
172
+ mtime = p.stat().st_mtime
173
+ except OSError:
174
+ mtime = 0.0
175
+
176
+ h = _file_horizon(p)
177
+ for r in recs:
178
+ if r.method_id not in panel_ids:
179
+ n_off_panel += 1
180
+ continue
181
+ candidates.append((r, mtime, h))
182
+
183
+ # Second pass: dedupe by latest (timestamp, mtime); newer wins.
184
+ # KEY INCLUDES ``ablation_setting`` AND ``horizon`` (parsed from
185
+ # filename for T1 multi-horizon cells) so the aggregator never collapses
186
+ # different horizons of the same (method, task, granularity, seed)
187
+ # tuple into one row.
188
+ best: dict[
189
+ tuple[str, str, str, int, str | None, int | None],
190
+ tuple[RunRecord, float, int | None],
191
+ ] = {}
192
+ for rec, mtime, h in candidates:
193
+ key = (rec.method_id, rec.task, rec.granularity, rec.seed,
194
+ rec.ablation_setting, h)
195
+ prev = best.get(key)
196
+ if prev is None:
197
+ best[key] = (rec, mtime, h)
198
+ continue
199
+ prev_rec, prev_mtime, _ = prev
200
+ if (rec.timestamp, mtime) > (prev_rec.timestamp, prev_mtime):
201
+ best[key] = (rec, mtime, h)
202
+ n_dedup_dropped = len(candidates) - len(best)
203
+
204
+ # Third + fourth passes: status + coverage gates.
205
+ out: list[tuple[RunRecord, int | None]] = []
206
+ n_skip = 0
207
+ n_partial = 0
208
+ for rec, _mtime, h in best.values():
209
+ if rec.status != "ok":
210
+ n_skip += 1
211
+ continue
212
+ m_dict = rec.metrics or {}
213
+ primary = _PRIMARY_METRIC_KEY.get(rec.task, "mse")
214
+ m = m_dict.get(primary)
215
+ val = m.value if m is not None else None
216
+ if val is None:
217
+ n_partial += 1
218
+ continue
219
+
220
+ # Partial-NaN gate
221
+ # NOTE: For T3/T6, a low success_rate (even 0) is a LEGITIMATE
222
+ # benchmark measurement: it means the method could not produce the
223
+ # canonical 11-field XBRL schema; eval-side fillna(0) -> APE 100%
224
+ # scores it as 100% MAPE per ``feedback_penalize_incomplete``. We
225
+ # only drop when ``success_rate`` is *missing entirely* (None),
226
+ # which signals a recording-side bug, not a real model failure.
227
+ if rec.task in ("T3", "T6"):
228
+ sr = m_dict.get("success_rate")
229
+ sr_v = sr.value if sr is not None else None
230
+ if sr_v is None:
231
+ n_partial += 1
232
+ continue
233
+ else:
234
+ # n_predictions or n_instances must equal canonical eval N.
235
+ expected = EVAL_N_PER_TASK.get(rec.task) # type: ignore[arg-type]
236
+ np_metric = m_dict.get("n_predictions") or m_dict.get("n_instances")
237
+ np_v = np_metric.value if np_metric is not None else None
238
+ if expected is not None and np_v is not None and int(np_v) < int(expected):
239
+ n_partial += 1
240
+ continue
241
+ out.append((rec, h))
242
+ return out, n_skip, n_migrated, n_dedup_dropped, n_partial, n_off_panel
243
+
244
+
245
+ def _records_to_long_df(
246
+ records: list[tuple[RunRecord, int | None]],
247
+ ) -> pd.DataFrame:
248
+ """Flatten records into a long-form DataFrame keyed by metric name.
249
+
250
+ Backfills ``method_family`` from the modal non-null value seen for each
251
+ ``method_id`` so stale re-eval bundles (which strip ``method_family``)
252
+ don't split a method into two leaderboard rows (e.g.,
253
+ ``random_forest (classical)`` and ``random_forest (unknown)``).
254
+ """
255
+ # Seed family map from the live Method registry — covers methods whose
256
+ # writers never tagged ``method_family`` in the RunRecord (closed LLMs
257
+ # gpt51/gpt_oss_120b/gemini3_flash, naive baselines historical_analogue/
258
+ # metro_median/sector_median, etc.).
259
+ family_by_method: dict[str, str] = {}
260
+ try:
261
+ # Import is deferred so the aggregator stays importable in
262
+ # environments without the methods/ tree (e.g. paper-only checkouts).
263
+ from projects.agent_builder.scripts.whatif_bench import methods # noqa: F401
264
+ from projects.agent_builder.scripts.whatif_bench.methods._registry import ALL_METHODS
265
+ for _name, _cls in ALL_METHODS.items():
266
+ _fam = getattr(_cls, "family", None)
267
+ if _fam:
268
+ family_by_method[_name] = _fam
269
+ except Exception:
270
+ # Registry not importable in this environment — fall back to
271
+ # in-record backfill only.
272
+ pass
273
+ for r, _h in records:
274
+ fam = r.method_family
275
+ if fam and fam != "unknown" and r.method_id not in family_by_method:
276
+ family_by_method[r.method_id] = fam
277
+ rows: list[dict[str, Any]] = []
278
+ for r, h in records:
279
+ if r.metrics is None:
280
+ continue
281
+ fam = r.method_family
282
+ if fam in (None, "", "unknown"):
283
+ fam = family_by_method.get(r.method_id, "unknown")
284
+ family = fam
285
+ for metric_name, mv in r.metrics.items():
286
+ rows.append({
287
+ "task": r.task,
288
+ "method_id": r.method_id,
289
+ "method_family": family,
290
+ "granularity": r.granularity,
291
+ "seed": r.seed,
292
+ "ablation_setting": r.ablation_setting,
293
+ "horizon": h,
294
+ "metric_name": metric_name,
295
+ "value": mv.value,
296
+ "ci_lo": mv.ci_lo,
297
+ "ci_hi": mv.ci_hi,
298
+ "std": mv.std,
299
+ "n_boot": mv.n_boot,
300
+ "resample": mv.resample,
301
+ })
302
+ return pd.DataFrame(rows)
303
+
304
+
305
+ def aggregate(
306
+ input_glob: str | None = None,
307
+ *,
308
+ output_path: Path | None = None,
309
+ ) -> dict[str, pd.DataFrame]:
310
+ """Aggregate every JSON matching ``input_glob`` into per-task DataFrames.
311
+
312
+ Parameters
313
+ ----------
314
+ input_glob
315
+ Glob (default: ``experiments/results/canon_*.json``).
316
+ output_path
317
+ Optional Parquet path; when supplied, writes the *long-form* table
318
+ (``[task, method_id, metric_name, value, ci_lo, ci_hi, n_boot, ...]``)
319
+ and the per-task split is reconstructable via groupby.
320
+ """
321
+ if input_glob is None:
322
+ # Results live under experiments/results/, NOT data_small_caps/.
323
+ # data_small_caps/ is the immutable raw-data tree; mixing experiment
324
+ # outputs into it pollutes the data layer.
325
+ input_glob = str(
326
+ Path(__file__).parent / "results" / "canon_*.json"
327
+ )
328
+
329
+ paths = [Path(p) for p in sorted(glob.glob(input_glob))]
330
+ if not paths:
331
+ logger.warning("No JSON matched glob %s", input_glob)
332
+
333
+ records, n_skipped, n_migrated, n_dedup, n_partial, n_off_panel = _load_records(paths)
334
+ logger.info(
335
+ "Loaded %d paper-valid records from %d files "
336
+ "(%d off-panel filtered, %d non-ok skipped, %d v1->v2 migrated, "
337
+ "%d duplicate cells deduped, %d tainted cells dropped)",
338
+ len(records), len(paths), n_off_panel, n_skipped, n_migrated, n_dedup,
339
+ n_partial,
340
+ )
341
+ if n_off_panel:
342
+ print(f"FOOTNOTE: {n_off_panel} record(s) had method_id outside "
343
+ "panel.ALL_METHODS and were filtered (e.g. stale gpt_oss_120b, gemma4).")
344
+ if n_skipped:
345
+ print(f"FOOTNOTE: {n_skipped} record(s) had status != 'ok' and were skipped.")
346
+ if n_migrated:
347
+ print(f"FOOTNOTE: {n_migrated} record(s) migrated from schema_version=1 to 2.")
348
+ if n_dedup:
349
+ print(f"FOOTNOTE: {n_dedup} duplicate (method, task, gran, seed) "
350
+ "cell(s) deduped — kept latest timestamp.")
351
+ if n_partial:
352
+ print(f"FOOTNOTE: {n_partial} cell(s) dropped because primary metric "
353
+ "value was None (silent-NaN tainted; need rerun).")
354
+
355
+ long_df = _records_to_long_df(records)
356
+ per_task: dict[str, pd.DataFrame] = {}
357
+ for task in _TASK_ORDER:
358
+ if long_df.empty:
359
+ per_task[task] = long_df.copy()
360
+ continue
361
+ sub = long_df[long_df["task"] == task].copy()
362
+ per_task[task] = (
363
+ sub.sort_values(["method_id", "metric_name"]).reset_index(drop=True)
364
+ )
365
+
366
+ if output_path is not None:
367
+ output_path = Path(output_path)
368
+ output_path.parent.mkdir(parents=True, exist_ok=True)
369
+ if output_path.suffix == ".parquet":
370
+ long_df.to_parquet(output_path, index=False)
371
+ else:
372
+ long_df.to_csv(output_path, index=False)
373
+ logger.info("Wrote aggregate %s (%d rows)", output_path, len(long_df))
374
+
375
+ return per_task
376
+
377
+
378
+ def _print_leaderboard_for_cells(
379
+ df: pd.DataFrame,
380
+ *,
381
+ label: str,
382
+ eligible_methods: set[str],
383
+ ) -> None:
384
+ """Emit per-task leaderboard restricted to a single cell-set ``df``.
385
+
386
+ No groupby across heterogeneous cells; each method contributes exactly
387
+ one row (single seed). Missing-from-cell methods are listed below the
388
+ ranked block so coverage gaps are explicit.
389
+ """
390
+ print(f"\n=== {label} ===")
391
+ for task in _TASK_ORDER:
392
+ sub_task = df[df["task"] == task]
393
+ eligible_for_task = eligible_methods
394
+ if sub_task.empty:
395
+ present = set()
396
+ else:
397
+ present = set(sub_task["method_id"].unique())
398
+ missing = sorted(eligible_for_task - present)
399
+
400
+ primary = _PRIMARY_METRIC_KEY.get(task, "mse")
401
+ ascending = _PRIMARY_METRIC_LOWER_IS_BETTER.get(task, True)
402
+ ranked = sub_task[sub_task["metric_name"] == primary].dropna(
403
+ subset=["value"]
404
+ ).copy()
405
+ if ranked.empty:
406
+ print(f"\n[{task}] no valid records in this cell-set "
407
+ f"({len(missing)} eligible methods missing).")
408
+ if missing:
409
+ print(f" missing: {missing}")
410
+ continue
411
+ ranked = ranked.sort_values(
412
+ "value", ascending=ascending,
413
+ ).reset_index(drop=True)
414
+ print(f"\n[{task}] primary={primary} "
415
+ f"({'lower' if ascending else 'higher'}=better) — "
416
+ f"{len(ranked)}/{len(eligible_for_task)} methods present:")
417
+ for i, row in ranked.iterrows():
418
+ print(f" {i+1:2d}. {row['method_id']:30s} "
419
+ f"({row['method_family']:14s}) {row['value']:14.4f}")
420
+ if missing:
421
+ print(f" ... missing this cell: {missing}")
422
+
423
+
424
+ def print_summary(
425
+ per_task: dict[str, pd.DataFrame],
426
+ long_df: pd.DataFrame | None = None,
427
+ ) -> None:
428
+ """Three per-cell-set leaderboards: main panel / MH T1 / A-E ablation.
429
+
430
+ Each cell-set restricts both the records considered and the eligible
431
+ method allow-list, so rankings compare like-with-like.
432
+ """
433
+ from .panel import (
434
+ ALL_METHODS as _PANEL_METHODS,
435
+ methods_for_task_panel,
436
+ )
437
+ if long_df is None:
438
+ # Reconstruct from per-task. (Older callers passed only per_task.)
439
+ long_df = pd.concat(per_task.values(), ignore_index=True) if per_task else pd.DataFrame()
440
+ if long_df.empty:
441
+ print("\n(no records to summarise)")
442
+ return
443
+
444
+ panel_ids, ablation_ids = _panel_method_ids()
445
+
446
+ # Cell-set 1: MAIN PANEL — daily, horizon is None (= h=252 main), no ablation.
447
+ main_df = long_df[
448
+ (long_df["granularity"] == "daily")
449
+ & (long_df["horizon"].isna())
450
+ & (long_df["ablation_setting"].isna())
451
+ & (long_df["method_id"].isin(panel_ids))
452
+ ].copy()
453
+ # Eligible methods per task = panel methods whose ``tasks`` include task.
454
+ main_eligible_by_task = {
455
+ t: {m.id for m in methods_for_task_panel(t)}
456
+ for t in _TASK_ORDER
457
+ }
458
+ # Print task-by-task with task-specific eligibility.
459
+ print("\n=== MAIN PANEL (daily, h=252 default, no ablation) ===")
460
+ for task in _TASK_ORDER:
461
+ sub_task = main_df[main_df["task"] == task]
462
+ eligible = main_eligible_by_task[task]
463
+ present = set(sub_task["method_id"].unique()) if not sub_task.empty else set()
464
+ missing = sorted(eligible - present)
465
+ primary = _PRIMARY_METRIC_KEY.get(task, "mse")
466
+ ascending = _PRIMARY_METRIC_LOWER_IS_BETTER.get(task, True)
467
+ ranked = sub_task[sub_task["metric_name"] == primary].dropna(
468
+ subset=["value"]
469
+ ).copy()
470
+ if ranked.empty:
471
+ print(f"\n[{task}] no valid records "
472
+ f"({len(missing)}/{len(eligible)} eligible methods missing).")
473
+ if missing:
474
+ print(f" missing: {missing}")
475
+ continue
476
+ ranked = ranked.sort_values(
477
+ "value", ascending=ascending,
478
+ ).reset_index(drop=True)
479
+ print(f"\n[{task}] primary={primary} "
480
+ f"({'lower' if ascending else 'higher'}=better) — "
481
+ f"{len(ranked)}/{len(eligible)} methods present:")
482
+ for i, row in ranked.iterrows():
483
+ print(f" {i+1:2d}. {row['method_id']:30s} "
484
+ f"({row['method_family']:14s}) {row['value']:14.4f}")
485
+ if missing:
486
+ print(f" ... missing: {missing}")
487
+
488
+ # Cell-set 2: MULTI-HORIZON T1 — one ranking per (granularity, horizon).
489
+ mh_df = long_df[
490
+ (long_df["task"] == "T1")
491
+ & (long_df["horizon"].notna())
492
+ & (long_df["ablation_setting"].isna())
493
+ & (long_df["method_id"].isin(panel_ids))
494
+ ].copy()
495
+ mh_eligible = main_eligible_by_task["T1"] # T1-capable panel methods
496
+ if not mh_df.empty:
497
+ print("\n=== MULTI-HORIZON T1 (per (granularity, horizon)) ===")
498
+ grans_horizons = (
499
+ mh_df[["granularity", "horizon"]].drop_duplicates()
500
+ .sort_values(["granularity", "horizon"])
501
+ .itertuples(index=False, name=None)
502
+ )
503
+ for gran, h in grans_horizons:
504
+ h_int = int(h)
505
+ sub = mh_df[(mh_df["granularity"] == gran) & (mh_df["horizon"] == h)]
506
+ ranked = sub[sub["metric_name"] == "mse"].dropna(
507
+ subset=["value"]
508
+ ).copy()
509
+ present = set(sub["method_id"].unique())
510
+ missing = sorted(mh_eligible - present)
511
+ print(f"\n[T1] {gran}/h={h_int} — "
512
+ f"{len(ranked)}/{len(mh_eligible)} methods present:")
513
+ ranked = ranked.sort_values("value").reset_index(drop=True)
514
+ for i, row in ranked.iterrows():
515
+ print(f" {i+1:2d}. {row['method_id']:30s} "
516
+ f"({row['method_family']:14s}) {row['value']:14.4f}")
517
+ if missing:
518
+ print(f" ... missing: {missing}")
519
+
520
+ # Cell-set 3: A-E ABLATION — per (setting, task) for ablation_ids only.
521
+ abl_df = long_df[
522
+ (long_df["ablation_setting"].notna())
523
+ & (long_df["method_id"].isin(ablation_ids))
524
+ ].copy()
525
+ if not abl_df.empty:
526
+ print("\n=== A→E ABLATION (gpt51, gemini3_flash, lightgbm [+scout_ft when ready]) ===")
527
+ from .panel import ABLATION_TASKS, ABLATION_SETTINGS
528
+ for setting in sorted(ABLATION_SETTINGS.keys()):
529
+ for task in ABLATION_TASKS:
530
+ sub = abl_df[
531
+ (abl_df["ablation_setting"] == setting)
532
+ & (abl_df["task"] == task)
533
+ ]
534
+ if sub.empty:
535
+ print(f"\n[{setting}/{task}] no records "
536
+ f"(eligible: {sorted(ablation_ids)})")
537
+ continue
538
+ primary = _PRIMARY_METRIC_KEY.get(task, "mse")
539
+ ascending = _PRIMARY_METRIC_LOWER_IS_BETTER.get(task, True)
540
+ ranked = sub[sub["metric_name"] == primary].dropna(
541
+ subset=["value"]
542
+ ).copy()
543
+ if ranked.empty:
544
+ print(f"\n[{setting}/{task}] no valid records for {primary}")
545
+ continue
546
+ ranked = ranked.sort_values(
547
+ "value", ascending=ascending,
548
+ ).reset_index(drop=True)
549
+ present = set(sub["method_id"].unique())
550
+ missing = sorted(ablation_ids - present)
551
+ print(f"\n[{setting}/{task}] primary={primary} — "
552
+ f"{len(ranked)}/{len(ablation_ids)} methods:")
553
+ for i, row in ranked.iterrows():
554
+ print(f" {i+1:2d}. {row['method_id']:30s} "
555
+ f"({row['method_family']:14s}) {row['value']:14.4f}")
556
+ if missing:
557
+ print(f" ... missing: {missing}")
558
+
559
+
560
+ def main(argv: list[str] | None = None) -> int:
561
+ parser = argparse.ArgumentParser(description=__doc__)
562
+ parser.add_argument(
563
+ "--input", type=str, default=None,
564
+ help="Glob pointing to RunRecord JSON files "
565
+ "(default: experiments/results/*.json)",
566
+ )
567
+ parser.add_argument(
568
+ "--output", type=Path, default=None,
569
+ help="Optional aggregated table output (.parquet or .csv).",
570
+ )
571
+ parser.add_argument(
572
+ "--summary", action="store_true",
573
+ help="Print per-task method leaderboard sorted by the task's primary metric.",
574
+ )
575
+ args = parser.parse_args(argv)
576
+
577
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
578
+ per_task = aggregate(input_glob=args.input, output_path=args.output)
579
+ if args.summary:
580
+ print_summary(per_task)
581
+ return 0
582
+
583
+
584
+ if __name__ == "__main__": # pragma: no cover
585
+ import sys
586
+ sys.exit(main())
code/experiments/analyses/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Post-hoc analyses for the MacroLens E&D track submission."""
code/experiments/analyses/post_hoc.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Post-hoc analyses + paper artifacts for MacroLens (NeurIPS 2026 E&D track).
2
+
3
+ One pass over the reeval JSON + saved pkls produces every table + figure
4
+ referenced by §6 and the appendix.
5
+
6
+ Outputs (in --output-dir):
7
+ Main-text artifacts:
8
+ tab_t1_leaderboard.tex -- T1 leaderboard
9
+ tab_t2_t5_gap.tex -- T2 vs T5 valuation gap
10
+ fig_ablation_4panel.pdf -- 4-panel ablation figure (4 tasks x 2 models x A-E)
11
+ fig_cross_task_corr.pdf -- cross-task ranking heatmap
12
+ tab_cross_task_corr.tex -- same as table
13
+ Evaluation-research tables:
14
+ tab_baseline_floor.tex -- saturation: methods failing to beat naive
15
+ tab_failure_modes.tex -- per-cell mode (ok/parser_fail/saturation/scale_blowup)
16
+ Appendix per-task tables:
17
+ tab_per_task_T1.tex .. tab_per_task_T7.tex
18
+ Stratifications:
19
+ stratify_T1_sector.csv -- §App.C
20
+ stratify_T2_quartile.csv
21
+ stratify_T5_quartile.csv
22
+ stratify_T4_event_type.csv
23
+ stratify_T7_state.csv
24
+ Raw CSVs (backing every table):
25
+ panel_metrics.csv, ablation_metrics.csv, failure_modes.csv
26
+
27
+ Usage:
28
+ python -m whatif_bench.experiments.analyses.post_hoc \\
29
+ --predictions-dir whatif_bench/experiments/predictions \\
30
+ --reeval whatif_bench/experiments/results/canon_reeval_<TS>.json \\
31
+ --output-dir whatif_bench/experiments/analyses_out
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import json
37
+ import pickle
38
+ from pathlib import Path
39
+
40
+ import numpy as np
41
+ import pandas as pd
42
+
43
+ PANEL = [
44
+ "persistence", "historical_analogue", "sector_median", "metro_median",
45
+ "lightgbm", "random_forest",
46
+ "dlinear", "itransformer", "moderntcn",
47
+ "chronos2", "moirai2", "timesfm",
48
+ "chattime", "time_mqa",
49
+ "gpt_oss_120b", "gpt51", "gemini3_flash", "qwen35",
50
+ ]
51
+ NAIVE = {"persistence", "historical_analogue", "sector_median", "metro_median"}
52
+ TASKS = ["T1", "T2", "T3", "T4", "T5", "T6", "T7"]
53
+ ABL_TASKS = ["T1", "T2", "T4", "T5"]
54
+ ABL_MODELS = ["gpt51", "gemini3_flash"]
55
+ PRIMARY = {
56
+ "T1": "mse", "T2": "median_ape", "T3": "overall_mape",
57
+ "T4": "return_mae_pct", "T5": "median_ape", "T6": "overall_mape",
58
+ "T7": "rent_MAPE",
59
+ }
60
+ LABEL = {
61
+ "mse": "MSE", "median_ape": "medAPE\\%", "overall_mape": "MAPE\\%",
62
+ "return_mae_pct": "MAE\\%", "rent_MAPE": "MAPE\\%",
63
+ }
64
+ SETTINGS = ["A", "B", "C", "D", "E"]
65
+
66
+
67
+ # ── data loading ──────────────────────────────────────────────────────────
68
+
69
+ def load_metrics(reeval_path: Path) -> tuple[pd.DataFrame, pd.DataFrame]:
70
+ """Return (panel_df, abl_df) with primary metric per row."""
71
+ recs = json.loads(reeval_path.read_text())
72
+ if isinstance(recs, dict):
73
+ recs = recs.get("records", recs)
74
+ rows = []
75
+ for r in recs:
76
+ if r.get("status") != "ok":
77
+ continue
78
+ m, t = r.get("method_id"), r.get("task")
79
+ if m not in PANEL or t not in TASKS:
80
+ continue
81
+ key = PRIMARY[t]
82
+ v = (r.get("metrics") or {}).get(key, {}).get("value")
83
+ if v is None:
84
+ continue
85
+ rows.append({
86
+ "method": m, "task": t,
87
+ "setting": r.get("ablation_setting") or "",
88
+ "metric_key": key, "value": float(v),
89
+ })
90
+ df = pd.DataFrame(rows)
91
+ panel = df[df["setting"] == ""].drop(columns=["setting"]).copy()
92
+ abl = df[df["setting"] != ""].copy()
93
+ return panel, abl
94
+
95
+
96
+ def load_pkls(pred_dir: Path) -> list[dict]:
97
+ out = []
98
+ for p in sorted(pred_dir.glob("*.pkl")):
99
+ try:
100
+ with p.open("rb") as f:
101
+ d = pickle.load(f)
102
+ out.append(d)
103
+ except Exception:
104
+ continue
105
+ return out
106
+
107
+
108
+ # ── analyses (each returns a DataFrame) ───────────────────────────────────
109
+
110
+ def cross_task_correlation(panel: pd.DataFrame) -> pd.DataFrame:
111
+ from scipy.stats import spearmanr
112
+ pv = panel.pivot(index="method", columns="task", values="value")
113
+ rho = pd.DataFrame(index=TASKS, columns=TASKS, dtype=float)
114
+ for ta in TASKS:
115
+ for tb in TASKS:
116
+ common = pv[[ta, tb]].dropna() if ta in pv.columns and tb in pv.columns else pd.DataFrame()
117
+ if len(common) >= 4 and ta != tb:
118
+ rho.loc[ta, tb] = spearmanr(common[ta], common[tb])[0]
119
+ elif ta == tb:
120
+ rho.loc[ta, tb] = 1.0
121
+ return rho
122
+
123
+
124
+ def baseline_floor(panel: pd.DataFrame) -> pd.DataFrame:
125
+ """Per-task: naive floor + count of methods beating / failing it."""
126
+ rows = []
127
+ for t in TASKS:
128
+ sub = panel[panel["task"] == t]
129
+ floor = sub[sub["method"].isin(NAIVE)]["value"].min()
130
+ if pd.isna(floor):
131
+ continue
132
+ non_naive = sub[~sub["method"].isin(NAIVE)]
133
+ beat = (non_naive["value"] < floor * 0.99).sum()
134
+ fail = (~(non_naive["value"] < floor * 0.99)).sum()
135
+ rows.append({"task": t, "naive_floor": floor,
136
+ "n_beat": int(beat), "n_fail": int(fail)})
137
+ return pd.DataFrame(rows)
138
+
139
+
140
+ def t2_t5_gap(panel: pd.DataFrame) -> pd.DataFrame:
141
+ from scipy.stats import spearmanr
142
+ pv = panel.pivot(index="method", columns="task", values="value")
143
+ common = pv[["T2", "T5"]].dropna()
144
+ common = common.assign(
145
+ delta=common["T5"] - common["T2"],
146
+ T2_rank=common["T2"].rank().astype(int),
147
+ T5_rank=common["T5"].rank().astype(int),
148
+ ).sort_values("T2").reset_index()
149
+ rho = spearmanr(common["T2"], common["T5"])[0] if len(common) >= 3 else float("nan")
150
+ common.attrs["spearman_rho"] = rho
151
+ common.attrs["mean_delta"] = common["delta"].mean()
152
+ return common
153
+
154
+
155
+ def classify_mode(d: dict) -> str:
156
+ yp = d.get("y_pred")
157
+ if yp is None:
158
+ return "no_pkl"
159
+ if hasattr(yp, "columns"):
160
+ col = next((c for c in ("pred", "value", "predicted_equity_value",
161
+ "predicted_return_pct", "pred_rent", "pred_price")
162
+ if c in yp.columns), None)
163
+ vals = pd.to_numeric(yp[col], errors="coerce").to_numpy() if col else np.array([])
164
+ else:
165
+ vals = np.asarray(yp, dtype=np.float64).ravel()
166
+ if vals.size == 0:
167
+ return "no_pkl"
168
+ finite = vals[np.isfinite(vals)]
169
+ if finite.size / vals.size < 0.5:
170
+ return "parser_fail"
171
+ if finite.size and np.max(np.abs(finite)) > 1e8:
172
+ return "scale_blowup"
173
+ if finite.size and np.std(finite) < 1e-3:
174
+ return "saturation"
175
+ return "ok"
176
+
177
+
178
+ def failure_modes(pkls: list[dict]) -> pd.DataFrame:
179
+ rows = []
180
+ for d in pkls:
181
+ m, t = d.get("method_id"), d.get("task")
182
+ s = d.get("ablation_setting") or ""
183
+ if m in PANEL and t in TASKS and not s:
184
+ rows.append({"method": m, "task": t, "mode": classify_mode(d)})
185
+ return pd.DataFrame(rows)
186
+
187
+
188
+ def stratify(pkls: list[dict], task: str, key_col: str, metric: str) -> pd.DataFrame:
189
+ """Per-(method, stratum) primary metric for one task."""
190
+ rows = []
191
+ for d in pkls:
192
+ if d.get("task") != task or d.get("method_id") not in PANEL:
193
+ continue
194
+ if (d.get("ablation_setting") or ""):
195
+ continue
196
+ meta, yt, yp = d.get("meta_test"), d.get("y_test"), d.get("y_pred")
197
+ if meta is None or key_col not in meta.columns:
198
+ continue
199
+ m = d["method_id"]
200
+ if metric == "mse": # T1 trajectory
201
+ yt_a = np.asarray(yt, dtype=np.float64)
202
+ yp_a = np.asarray(yp, dtype=np.float64).copy()
203
+ if yt_a.ndim == 1: yt_a = yt_a.reshape(-1, 1)
204
+ if yp_a.ndim == 1: yp_a = yp_a.reshape(-1, 1)
205
+ yp_a[~np.isfinite(yp_a).all(axis=1)] = 0.0
206
+ n = min(len(meta), len(yp_a))
207
+ per_inst = ((yp_a[:n] - yt_a[:n]) ** 2).mean(axis=1)
208
+ df = pd.DataFrame({key_col: meta[key_col].astype(str).values[:n],
209
+ "v": per_inst})
210
+ agg = df.groupby(key_col)["v"].mean()
211
+ elif metric == "median_ape": # T2 / T5
212
+ yt_a = np.asarray(yt, dtype=np.float64).ravel()
213
+ yp_a = np.where(np.isfinite(np.asarray(yp, dtype=np.float64).ravel()),
214
+ np.asarray(yp, dtype=np.float64).ravel(), 0.0)
215
+ n = min(len(meta), len(yt_a), len(yp_a))
216
+ keep = np.isfinite(yt_a[:n]) & (np.abs(yt_a[:n]) >= 1.0)
217
+ ape = np.minimum(np.abs(yp_a[:n][keep] - yt_a[:n][keep]) / np.abs(yt_a[:n][keep]),
218
+ 10.0) * 100.0
219
+ df = pd.DataFrame({key_col: meta[key_col].astype(str).values[:n][keep],
220
+ "v": ape})
221
+ agg = df.groupby(key_col)["v"].median()
222
+ elif metric == "return_mae_pct": # T4
223
+ if hasattr(yp, "columns"):
224
+ yp_a = pd.to_numeric(yp.iloc[:, -1], errors="coerce").to_numpy()
225
+ else:
226
+ yp_a = np.asarray(yp, dtype=np.float64).ravel()
227
+ yt_a = np.asarray(yt, dtype=np.float64).ravel()
228
+ yp_a = np.where(np.isfinite(yp_a), yp_a, 0.0)
229
+ n = min(len(meta), len(yt_a), len(yp_a))
230
+ df = pd.DataFrame({key_col: meta[key_col].astype(str).values[:n],
231
+ "v": np.abs(yt_a[:n] - yp_a[:n])})
232
+ agg = df.groupby(key_col)["v"].mean()
233
+ else:
234
+ continue
235
+ for k, v in agg.items():
236
+ rows.append({"method": m, key_col: k, "value": float(v)})
237
+ return pd.DataFrame(rows)
238
+
239
+
240
+ # ── renderers ─────────────────────────────────────────────────────────────
241
+
242
+ def fmt(v) -> str:
243
+ if pd.isna(v):
244
+ return "--"
245
+ if isinstance(v, str):
246
+ return v
247
+ if abs(v) >= 1e6: return f"{v:.2e}"
248
+ if abs(v) >= 100: return f"{v:.0f}"
249
+ if abs(v) >= 1: return f"{v:.2f}"
250
+ return f"{v:.4f}"
251
+
252
+
253
+ def tex_safe(s: str) -> str:
254
+ return str(s).replace("_", r"\_")
255
+
256
+
257
+ def latex_table(df: pd.DataFrame, caption: str, label: str,
258
+ escape: bool = False) -> str:
259
+ """Wrap pd.to_latex with NeurIPS-friendly defaults."""
260
+ body = df.to_latex(
261
+ index=False, escape=escape, na_rep="--",
262
+ column_format="l" + "c" * (len(df.columns) - 1),
263
+ )
264
+ # Strip outer environment, wrap in table+caption.
265
+ return (
266
+ "\\begin{table}[h]\n\\centering\n"
267
+ f"\\caption{{{caption}}}\n\\label{{{label}}}\n\\small\n"
268
+ + body.replace("\\begin{tabular}", "\\begin{tabular}").rstrip()
269
+ + "\n\\end{table}\n"
270
+ )
271
+
272
+
273
+ def render_t1_leaderboard(panel: pd.DataFrame, out: Path) -> None:
274
+ family_map = {
275
+ "persistence": "Naive", "historical_analogue": "Naive",
276
+ "sector_median": "Naive", "metro_median": "Naive",
277
+ "lightgbm": "Classical", "random_forest": "Classical",
278
+ "dlinear": "Sequence", "itransformer": "Sequence", "moderntcn": "Sequence",
279
+ "chronos2": "TSFM", "moirai2": "TSFM", "timesfm": "TSFM",
280
+ "chattime": "TS-LLM", "time_mqa": "TS-LLM",
281
+ "gpt_oss_120b": "LLM-ZS", "gpt51": "LLM-ZS",
282
+ "gemini3_flash": "LLM-ZS", "qwen35": "LLM-ZS",
283
+ }
284
+ t1 = panel[panel["task"] == "T1"].copy()
285
+ t1["family"] = t1["method"].map(family_map)
286
+ t1["method"] = t1["method"].map(tex_safe)
287
+ t1["mse"] = t1["value"].map(fmt)
288
+ t1 = t1[["family", "method", "mse"]]
289
+ t1.columns = ["Family", "Method", "MSE"]
290
+ out.write_text(latex_table(
291
+ t1, caption="T1 contextual time-series forecasting (close-trajectory MSE, "
292
+ "single seed with cluster-bootstrap 95\\% CIs in App.~A).",
293
+ label="tab:t1",
294
+ ))
295
+
296
+
297
+ def render_t2_t5_gap(gap: pd.DataFrame, out: Path) -> None:
298
+ df = gap[["method", "T2", "T5", "delta", "T2_rank", "T5_rank"]].copy()
299
+ df["method"] = df["method"].map(tex_safe)
300
+ for c in ("T2", "T5", "delta"):
301
+ df[c] = df[c].map(fmt)
302
+ df.columns = ["Method", "T2 medAPE", "T5 medAPE", "$\\Delta$(T5--T2)",
303
+ "rank T2", "rank T5"]
304
+ rho = gap.attrs.get("spearman_rho")
305
+ md = gap.attrs.get("mean_delta")
306
+ out.write_text(latex_table(
307
+ df,
308
+ caption=(
309
+ "T2 vs T5 valuation gap. $\\Delta$ is medAPE delta when "
310
+ "market-price features are removed (T5). "
311
+ f"Spearman $\\rho$(T2 ranking, T5 ranking) $= {rho:.3f}$; "
312
+ f"mean $\\Delta = {md:+.2f}$ medAPE pts."
313
+ ),
314
+ label="tab:t2-t5-gap",
315
+ ))
316
+
317
+
318
+ def render_correlation(rho: pd.DataFrame, out_tex: Path, out_pdf: Path) -> None:
319
+ df = rho.round(2).copy()
320
+ df.insert(0, "", df.index)
321
+ out_tex.write_text(latex_table(
322
+ df, caption="Cross-task ranking correlation (Spearman $\\rho$). "
323
+ "Negative cells (boxed) are the multi-task non-redundancy "
324
+ "evidence: methods that win T1 lose T3 and T6.",
325
+ label="tab:cross-task-corr",
326
+ ))
327
+ import matplotlib
328
+ matplotlib.use("Agg")
329
+ import matplotlib.pyplot as plt
330
+ fig, ax = plt.subplots(figsize=(5.5, 4.5))
331
+ arr = rho.to_numpy(dtype=float)
332
+ im = ax.imshow(arr, cmap="RdBu_r", vmin=-1.0, vmax=1.0, aspect="equal")
333
+ ax.set_xticks(range(len(TASKS))); ax.set_xticklabels(TASKS)
334
+ ax.set_yticks(range(len(TASKS))); ax.set_yticklabels(TASKS)
335
+ for i in range(len(TASKS)):
336
+ for j in range(len(TASKS)):
337
+ v = arr[i, j]
338
+ if not np.isnan(v):
339
+ ax.text(j, i, f"{v:.2f}", ha="center", va="center",
340
+ color="white" if abs(v) > 0.5 else "black", fontsize=9)
341
+ fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
342
+ fig.tight_layout()
343
+ fig.savefig(out_pdf, bbox_inches="tight")
344
+ plt.close(fig)
345
+
346
+
347
+ def render_baseline_floor(bf: pd.DataFrame, out: Path) -> None:
348
+ df = bf.copy()
349
+ df["naive_floor"] = df["naive_floor"].map(fmt)
350
+ df.columns = ["Task", "Naive floor", "\\# beating", "\\# failing"]
351
+ out.write_text(latex_table(
352
+ df, caption="Saturation analysis: per-task best-naive baseline value "
353
+ "and counts of non-naive methods beating / failing it.",
354
+ label="tab:baseline-floor",
355
+ ))
356
+
357
+
358
+ def render_failure_modes(fm: pd.DataFrame, out: Path) -> None:
359
+ pv = fm.pivot(index="method", columns="task", values="mode")
360
+ pv = pv.reindex(index=PANEL, columns=TASKS)
361
+ pv = pv.reset_index()
362
+ pv["method"] = pv["method"].map(tex_safe)
363
+ pv.columns = ["Method"] + TASKS
364
+ out.write_text(latex_table(
365
+ pv,
366
+ caption="Per-cell failure-mode taxonomy. ok = reasonable predictions; "
367
+ "parser\\_fail = $>$50\\% NaN after parser; "
368
+ "saturation = constant predictions near zero; "
369
+ "scale\\_blowup = parser-induced extreme values.",
370
+ label="tab:failure-modes",
371
+ ))
372
+
373
+
374
+ def render_per_task_table(panel: pd.DataFrame, task: str, out: Path) -> None:
375
+ df = panel[panel["task"] == task].sort_values("value")[["method", "value"]].copy()
376
+ df["method"] = df["method"].map(tex_safe)
377
+ df["value"] = df["value"].map(fmt)
378
+ metric_label = LABEL.get(PRIMARY[task], PRIMARY[task])
379
+ df.columns = ["Method", metric_label]
380
+ out.write_text(latex_table(
381
+ df, caption=f"{task} per-method primary metric ({metric_label}).",
382
+ label=f"tab:per-task-{task}",
383
+ ))
384
+
385
+
386
+ def render_ablation_4panel(abl: pd.DataFrame, out: Path) -> None:
387
+ """4 panels (T1, T2, T4, T5); two lines per panel (gpt51, gemini3_flash)."""
388
+ import matplotlib
389
+ matplotlib.use("Agg")
390
+ import matplotlib.pyplot as plt
391
+ fig, axes = plt.subplots(1, 4, figsize=(13, 3.0))
392
+ colors = {"gpt51": "#1f77b4", "gemini3_flash": "#d62728"}
393
+ nice = {"gpt51": "GPT-5.1", "gemini3_flash": "Gemini-3-Flash"}
394
+ for ax, t in zip(axes, ABL_TASKS):
395
+ for m in ABL_MODELS:
396
+ sub = abl[(abl["method"] == m) & (abl["task"] == t)]
397
+ sub = sub.set_index("setting").reindex(SETTINGS)["value"]
398
+ ax.plot(SETTINGS, sub.values, marker="o", color=colors[m],
399
+ label=nice[m], linewidth=1.6, markersize=5)
400
+ ax.set_title(f"{t} ({LABEL[PRIMARY[t]].replace(chr(92)+'%', '%')})", fontsize=10)
401
+ ax.set_xlabel("Context setting (A→E)", fontsize=9)
402
+ ax.tick_params(axis="both", labelsize=8)
403
+ ax.grid(True, alpha=0.3, linewidth=0.4)
404
+ if t == "T1":
405
+ ax.set_yscale("log")
406
+ ax.set_ylabel("MSE (log)", fontsize=9)
407
+ else:
408
+ ax.set_ylabel(LABEL[PRIMARY[t]].replace("\\%", "%"), fontsize=9)
409
+ axes[0].legend(loc="best", fontsize=8, frameon=True)
410
+ fig.tight_layout()
411
+ fig.savefig(out, bbox_inches="tight")
412
+ plt.close(fig)
413
+
414
+
415
+ # ── main ─────────────────────────────────────────────────────────────────
416
+
417
+ def main() -> int:
418
+ p = argparse.ArgumentParser()
419
+ p.add_argument("--predictions-dir", required=True, type=Path)
420
+ p.add_argument("--reeval", required=True, type=Path)
421
+ p.add_argument("--output-dir", required=True, type=Path)
422
+ args = p.parse_args()
423
+ args.output_dir.mkdir(parents=True, exist_ok=True)
424
+ O = args.output_dir
425
+
426
+ panel, abl = load_metrics(args.reeval)
427
+ pkls = load_pkls(args.predictions_dir)
428
+
429
+ panel.to_csv(O / "panel_metrics.csv", index=False)
430
+ abl.to_csv(O / "ablation_metrics.csv", index=False)
431
+
432
+ # Main-text artifacts
433
+ render_t1_leaderboard(panel, O / "tab_t1_leaderboard.tex")
434
+ gap = t2_t5_gap(panel); gap.to_csv(O / "t2_t5_gap.csv", index=False)
435
+ render_t2_t5_gap(gap, O / "tab_t2_t5_gap.tex")
436
+ rho = cross_task_correlation(panel); rho.to_csv(O / "cross_task_correlation.csv")
437
+ render_correlation(rho, O / "tab_cross_task_corr.tex", O / "fig_cross_task_corr.pdf")
438
+ render_ablation_4panel(abl, O / "fig_ablation_4panel.pdf")
439
+
440
+ # Evaluation-research tables
441
+ bf = baseline_floor(panel); bf.to_csv(O / "baseline_floor.csv", index=False)
442
+ render_baseline_floor(bf, O / "tab_baseline_floor.tex")
443
+ fm = failure_modes(pkls); fm.to_csv(O / "failure_modes.csv", index=False)
444
+ render_failure_modes(fm, O / "tab_failure_modes.tex")
445
+
446
+ # Per-task headline tables (appendix)
447
+ for t in TASKS:
448
+ render_per_task_table(panel, t, O / f"tab_per_task_{t}.tex")
449
+
450
+ # Stratifications (T7 omitted: two-output rent/price doesn't fit the
451
+ # single-metric stratify shape; appendix table is rendered direct from pkl).
452
+ # T2/T5 stratify by market-cap quartile (mcap_q) per the draft
453
+ # protocol; T1 by GICS sector; T4 by scenario event_type.
454
+ for task, key, metric, name in [
455
+ ("T1", "sector", "mse", "T1_sector"),
456
+ ("T2", "mcap_q", "median_ape", "T2_mcap_q"),
457
+ ("T5", "mcap_q", "median_ape", "T5_mcap_q"),
458
+ ("T4", "event_type", "return_mae_pct", "T4_event_type"),
459
+ ]:
460
+ s = stratify(pkls, task, key, metric)
461
+ if not s.empty:
462
+ s.to_csv(O / f"stratify_{name}.csv", index=False)
463
+
464
+ print(f"\nOK — wrote {len(list(O.iterdir()))} artifacts to {O}")
465
+ return 0
466
+
467
+
468
+ if __name__ == "__main__":
469
+ raise SystemExit(main())
code/experiments/analysis.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Post-hoc analysis scripts for MacroLens paper §4.4.
2
+
3
+ Generates:
4
+ 1. Per-category ScenRet breakdown (Table in appendix)
5
+ 2. Cross-sectional heterogeneity (by sector, market-cap quartile, filing density)
6
+ 3. Cross-frequency robustness summary
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import logging
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ from .. import config
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ # ── Per-Category ScenRet Breakdown ──────────────────────────────────────
25
+
26
+ def scenret_per_category(
27
+ granularity: str = "daily",
28
+ ) -> dict[str, Any]:
29
+ """Stratify ScenRet ground truth by scenario category.
30
+
31
+ Computes per-category statistics: mean return, std, count,
32
+ and the baseline (cross-ticker mean) MAE per category.
33
+ """
34
+ bench_dir = config.get_benchmark_dir(granularity)
35
+ gt_path = bench_dir / "scenario_forecast_ground_truth.parquet"
36
+
37
+ if not gt_path.exists():
38
+ return {"error": "scenario_forecast_ground_truth.parquet not found"}
39
+
40
+ gt = pd.read_parquet(gt_path)
41
+ gt = gt.dropna(subset=["actual_return_pct"])
42
+
43
+ if "event_type" not in gt.columns:
44
+ return {"error": "No event_type column"}
45
+
46
+ # Map event_type to category
47
+ category_map = _build_category_map()
48
+ gt["category"] = gt["event_type"].map(
49
+ lambda et: category_map.get(et, "other")
50
+ )
51
+
52
+ # Per-category stats
53
+ categories = {}
54
+ for cat, group in gt.groupby("category"):
55
+ returns = group["actual_return_pct"]
56
+ # Cross-ticker mean baseline MAE
57
+ scenario_means = group.groupby("scenario_id")["actual_return_pct"].transform("mean")
58
+ baseline_mae = float(np.mean(np.abs(returns - scenario_means)))
59
+
60
+ categories[cat] = {
61
+ "n_instances": len(group),
62
+ "n_scenarios": group["scenario_id"].nunique(),
63
+ "mean_return_pct": round(float(returns.mean()), 3),
64
+ "std_return_pct": round(float(returns.std()), 3),
65
+ "median_return_pct": round(float(returns.median()), 3),
66
+ "baseline_mae_pct": round(baseline_mae, 3),
67
+ "pct_positive": round(float((returns > 0).mean()), 3),
68
+ }
69
+
70
+ # Overall
71
+ overall_returns = gt["actual_return_pct"]
72
+ scenario_means_all = gt.groupby("scenario_id")["actual_return_pct"].transform("mean")
73
+ overall_baseline_mae = float(np.mean(np.abs(overall_returns - scenario_means_all)))
74
+
75
+ result = {
76
+ "granularity": granularity,
77
+ "total_instances": len(gt),
78
+ "total_scenarios": gt["scenario_id"].nunique(),
79
+ "overall_baseline_mae_pct": round(overall_baseline_mae, 3),
80
+ "per_category": categories,
81
+ }
82
+
83
+ logger.info("ScenRet per-category: %d categories, %d total instances",
84
+ len(categories), len(gt))
85
+ return result
86
+
87
+
88
+ def _build_category_map() -> dict[str, str]:
89
+ """Map event_type -> high-level category.
90
+
91
+ Event-type strings come from `generate_scenarios.py`'s detector functions.
92
+ Whenever a detector is added or renamed there, update this map and the
93
+ `tests/test_scenario_categories.py` coverage assertion.
94
+ """
95
+ mapping = {}
96
+ rates = [
97
+ "fed_rate_change", "sofr_shock", "treasury_move",
98
+ "treasury_acute_shock", # short-window 10Y move
99
+ "long_bond_shock", # DGS30
100
+ "yield_curve_event", # 10Y-2Y inversion
101
+ "yield_curve_3m10y_inversion",
102
+ "yield_curve_3m10y_uninversion",
103
+ "mortgage_rate_shock",
104
+ "real_yield_shift", "term_premium_change",
105
+ ]
106
+ equity = [
107
+ "sp500_drawdown", "sp500_acute_shock", # short-window crash
108
+ "nasdaq_move", "nasdaq_acute_shock",
109
+ "djia_move",
110
+ "vix_spike", "volatility_regime",
111
+ "sector_rotation", # SP500 vs NASDAQ divergence
112
+ "market_drawdown",
113
+ ]
114
+ commodities = [
115
+ "oil_shock", "oil_acute_shock",
116
+ "wti_oil_shock", "henry_hub_shock",
117
+ "natgas_shock",
118
+ ]
119
+ fx = ["fx_shock", "usd_shock"]
120
+ inflation = [
121
+ "inflation_shock", "ppi_shock", "pce_inflation_shock",
122
+ "breakeven_inflation_shock",
123
+ ]
124
+ labor = [
125
+ "unemployment_shock", "payroll_shock", "jolts_shock",
126
+ "earnings_shock",
127
+ ]
128
+ credit = [
129
+ "hy_spread_event", "ig_spread_event", "credit_compression",
130
+ "ted_spread_spike",
131
+ ]
132
+ housing = [
133
+ "housing_starts_shock", "home_price_event",
134
+ "building_permit_shock", "existing_home_sales_shock",
135
+ ]
136
+ money = [
137
+ "m2_contraction", "m2_surge", # split from m2_shock
138
+ "monetary_base_shock", "fed_balance_sheet",
139
+ "business_loans_shock",
140
+ "nfci_event", # Chicago Fed NFCI
141
+ ]
142
+
143
+ for et in rates: mapping[et] = "rates"
144
+ for et in equity: mapping[et] = "equity"
145
+ for et in commodities: mapping[et] = "commodities"
146
+ for et in fx: mapping[et] = "fx"
147
+ for et in inflation: mapping[et] = "inflation"
148
+ for et in labor: mapping[et] = "labor"
149
+ for et in credit: mapping[et] = "credit"
150
+ for et in housing: mapping[et] = "housing"
151
+ for et in money: mapping[et] = "money_supply"
152
+ return mapping
153
+
154
+
155
+ # ── Cross-Sectional Heterogeneity ───────────────────────────────────────
156
+
157
+ def cross_sectional_analysis(
158
+ granularity: str = "daily",
159
+ ) -> dict[str, Any]:
160
+ """Stratify TSF and ScenRet by sector, market-cap quartile, filing density."""
161
+ bench_dir = config.get_benchmark_dir(granularity)
162
+ test_path = bench_dir / "panel_test.parquet"
163
+ gt_path = bench_dir / "scenario_forecast_ground_truth.parquet"
164
+
165
+ if not test_path.exists():
166
+ return {"error": "panel_test.parquet not found"}
167
+
168
+ panel = pd.read_parquet(test_path)
169
+ result: dict[str, Any] = {"granularity": granularity}
170
+
171
+ # ── By Sector ──
172
+ if "sector" in panel.columns and "close" in panel.columns:
173
+ # Compute per-ticker daily returns first, THEN aggregate by sector,
174
+ # so we don't take pct_change across ticker boundaries (which would
175
+ # produce a spurious return at every (ticker_a, ticker_b) seam).
176
+ panel_sorted = panel.sort_values(["ticker", "date"])
177
+ per_ticker_ret = panel_sorted.groupby("ticker", sort=False)["close"].pct_change()
178
+ panel_sorted["_ret"] = per_ticker_ret
179
+
180
+ sector_stats = {}
181
+ for sector, grp in panel_sorted.groupby("sector"):
182
+ close = grp["close"].dropna()
183
+ if len(close) < 10:
184
+ continue
185
+ returns = grp["_ret"].dropna()
186
+ sector_stats[sector] = {
187
+ "n_rows": len(grp),
188
+ "n_tickers": grp["ticker"].nunique(),
189
+ "mean_close": round(float(close.mean()), 2),
190
+ "volatility": round(float(returns.std()), 4),
191
+ "mean_return": round(float(returns.mean()), 6),
192
+ }
193
+ result["by_sector"] = sector_stats
194
+
195
+ # ── By Market-Cap Quartile ──
196
+ if "derived_market_cap" in panel.columns:
197
+ latest = panel.sort_values("date").groupby("ticker").last()
198
+ # `duplicates="drop"` keeps qcut robust to small / degenerate
199
+ # market-cap distributions (e.g., synthetic fixtures or tiny
200
+ # universes where many tickers share the same derived_market_cap
201
+ # round number). On the real R2K + S&P 600 universe it has no
202
+ # effect because the bin edges are dense.
203
+ try:
204
+ latest["mcap_quartile"] = pd.qcut(
205
+ latest["derived_market_cap"].clip(lower=1),
206
+ 4, labels=["Q1_small", "Q2", "Q3", "Q4_large"],
207
+ duplicates="drop",
208
+ )
209
+ except ValueError as e:
210
+ logger.warning("mcap qcut failed (%s); skipping by_mcap_quartile", e)
211
+ latest["mcap_quartile"] = pd.NA
212
+ ticker_quartile = latest["mcap_quartile"].to_dict()
213
+ # Compute returns per-ticker BEFORE assigning quartile labels, otherwise
214
+ # pct_change() taken inside `groupby(mcap_quartile)` would compute a
215
+ # return at every cross-ticker seam.
216
+ panel_sorted = panel.sort_values(["ticker", "date"]).copy()
217
+ panel_sorted["_ret"] = panel_sorted.groupby("ticker", sort=False)["close"].pct_change()
218
+ panel_sorted["mcap_quartile"] = panel_sorted["ticker"].map(ticker_quartile)
219
+
220
+ mcap_stats = {}
221
+ for q, grp in panel_sorted.groupby("mcap_quartile"):
222
+ returns = grp["_ret"].dropna()
223
+ mcap_stats[str(q)] = {
224
+ "n_tickers": grp["ticker"].nunique(),
225
+ "mean_mcap": round(float(grp["derived_market_cap"].mean()), 0),
226
+ "volatility": round(float(returns.std()), 4),
227
+ }
228
+ result["by_mcap_quartile"] = mcap_stats
229
+
230
+ # ── By Filing Density ──
231
+ corpus_path = bench_dir / "filing_corpus.parquet"
232
+ if corpus_path.exists():
233
+ corpus = pd.read_parquet(corpus_path)
234
+ filings_per_ticker = corpus.groupby("ticker").size()
235
+ ticker_filing_density = filings_per_ticker.to_dict()
236
+
237
+ # Split into terciles
238
+ all_tickers = panel["ticker"].unique()
239
+ densities = pd.Series({
240
+ t: ticker_filing_density.get(t, 0) for t in all_tickers
241
+ })
242
+ terciles = pd.qcut(densities.clip(lower=0), 3,
243
+ labels=["low_filing", "mid_filing", "high_filing"],
244
+ duplicates="drop")
245
+
246
+ # As above: take pct_change PER ticker first, then aggregate by tercile,
247
+ # so we don't mix returns across ticker boundaries.
248
+ panel_sorted_fd = panel.sort_values(["ticker", "date"]).copy()
249
+ panel_sorted_fd["_ret"] = panel_sorted_fd.groupby("ticker", sort=False)["close"].pct_change()
250
+
251
+ filing_stats = {}
252
+ for t_label in terciles.unique():
253
+ tickers_in = set(terciles[terciles == t_label].index)
254
+ grp = panel_sorted_fd[panel_sorted_fd["ticker"].isin(tickers_in)]
255
+ returns = grp["_ret"].dropna()
256
+ filing_stats[str(t_label)] = {
257
+ "n_tickers": len(tickers_in),
258
+ "mean_filings": round(float(densities[terciles == t_label].mean()), 1),
259
+ "volatility": round(float(returns.std()), 4),
260
+ }
261
+ result["by_filing_density"] = filing_stats
262
+
263
+ # ── ScenRet by sector ──
264
+ if gt_path.exists():
265
+ gt = pd.read_parquet(gt_path).dropna(subset=["actual_return_pct"])
266
+ # Get ticker→sector from panel
267
+ ticker_sector = panel.drop_duplicates("ticker").set_index("ticker")["sector"].to_dict()
268
+ gt["sector"] = gt["ticker"].map(ticker_sector)
269
+
270
+ scenret_by_sector = {}
271
+ for sector, grp in gt.groupby("sector"):
272
+ if pd.isna(sector):
273
+ continue
274
+ returns = grp["actual_return_pct"]
275
+ scenret_by_sector[sector] = {
276
+ "n_instances": len(grp),
277
+ "mean_return_pct": round(float(returns.mean()), 3),
278
+ "std_return_pct": round(float(returns.std()), 3),
279
+ }
280
+ result["scenret_by_sector"] = scenret_by_sector
281
+
282
+ return result
283
+
284
+
285
+ # ── Cross-Frequency Summary ─────────────────────────────────────────────
286
+
287
+ def cross_frequency_summary() -> dict[str, Any]:
288
+ """Collect best baseline results across daily/weekly/monthly."""
289
+ result: dict[str, Any] = {}
290
+
291
+ legacy_dir = Path(__file__).resolve().parent / "results" / "legacy_per_family"
292
+ for gran in ["daily", "weekly", "monthly"]:
293
+ # ``all_results.json`` is the legacy per-family aggregate. It used
294
+ # to live under ``data_small_caps/benchmark/<g>/`` but moved to
295
+ # ``experiments/results/legacy_per_family/`` once experiment
296
+ # outputs were separated from the benchmark tree. The new
297
+ # canonical aggregate is ``experiments/paper_artifacts/aggregate.parquet``.
298
+ full_path = legacy_dir / "all_results.json"
299
+ quick_path = legacy_dir / "all_results_quick.json"
300
+ path = full_path if full_path.exists() else quick_path
301
+ if not path.exists():
302
+ result[gran] = {"status": "no_results"}
303
+ continue
304
+
305
+ data = json.loads(path.read_text())
306
+ summary: dict[str, Any] = {"status": "available"}
307
+
308
+ # Extract best TSF MAE across models
309
+ best_tsf_mae = {}
310
+ for key, val in data.items():
311
+ if isinstance(val, dict):
312
+ for sub_key, sub_val in val.items():
313
+ if isinstance(sub_val, dict) and "overall" in sub_val:
314
+ overall = sub_val["overall"]
315
+ if "mae" in overall:
316
+ h = sub_val.get("horizon", sub_key)
317
+ if h not in best_tsf_mae or overall["mae"] < best_tsf_mae[h]["mae"]:
318
+ best_tsf_mae[h] = {
319
+ "model": sub_key,
320
+ "mae": overall["mae"],
321
+ "da": overall.get("directional_accuracy", 0),
322
+ }
323
+
324
+ summary["best_tsf"] = best_tsf_mae
325
+ result[gran] = summary
326
+
327
+ return result
328
+
329
+
330
+ # ── Main ────────────────────────────────────────────────────────────────
331
+
332
+ def run_all_analyses(granularity: str = "daily") -> dict[str, Any]:
333
+ """Run all §4.4 analyses and save results."""
334
+ results: dict[str, Any] = {}
335
+
336
+ logger.info("Running per-category ScenRet analysis...")
337
+ results["scenret_per_category"] = scenret_per_category(granularity)
338
+
339
+ logger.info("Running cross-sectional analysis...")
340
+ results["cross_sectional"] = cross_sectional_analysis(granularity)
341
+
342
+ logger.info("Running cross-frequency summary...")
343
+ results["cross_frequency"] = cross_frequency_summary()
344
+
345
+ # Save
346
+ out_dir = config.get_benchmark_dir(granularity)
347
+ out_path = out_dir / "analysis_results.json"
348
+ out_path.write_text(json.dumps(results, indent=2, default=str))
349
+ logger.info("Analysis saved to %s", out_path)
350
+
351
+ return results
352
+
353
+
354
+ if __name__ == "__main__":
355
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
356
+ run_all_analyses()
code/experiments/build_paper_artifacts.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One-shot paper-artifact builder for the MacroLens NeurIPS 2026 D&B paper.
2
+
3
+ After every method has finished running and ``experiments/results/`` is
4
+ populated with ``RunRecord`` JSONs, this script bundles every downstream
5
+ artefact the paper consumes:
6
+
7
+ * **Aggregation** -- ``aggregate_results.aggregate(...)`` writes a long-form
8
+ parquet to ``paper_artifacts/aggregate.parquet``.
9
+ * **Tables** -- ``gen_tables.gen_tab_*`` writes 8 ``tab_<name>.tex``
10
+ files into ``paper_artifacts/tables/``. Both the legacy nested-dict
11
+ ``all_results[_quick].json`` (when present) and the new RunRecord glob are
12
+ searched; whichever is available is used.
13
+ * **Figures** -- ``gen_figures.render_all`` writes 5 ``fig_<name>.pdf``
14
+ + ``fig_<name>.png`` pairs into ``paper_artifacts/figures/``.
15
+ * **Analysis** -- ``analysis.run_all_analyses`` writes an
16
+ ``analysis_results.json`` into the benchmark dir AND copies it to
17
+ ``paper_artifacts/analysis/``.
18
+
19
+ CLI::
20
+
21
+ python -m projects.agent_builder.scripts.whatif_bench.experiments.build_paper_artifacts \\
22
+ --results-glob 'experiments/results/canon_*.json' \\
23
+ --granularity daily
24
+
25
+ Output tree (experiments/paper_artifacts/ -- experiment artifacts, NOT
26
+ under data_small_caps/, which is reserved for raw + derived data)::
27
+
28
+ experiments/paper_artifacts/
29
+ aggregate.parquet
30
+ leaderboard.txt (per-task primary-metric leaderboard)
31
+ tables/ tab_*.tex
32
+ figures/ fig_*.pdf, fig_*.png
33
+ analysis/ analysis_results.json
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import argparse
39
+ import glob
40
+ import json
41
+ import logging
42
+ import shutil
43
+ from pathlib import Path
44
+ from typing import Any
45
+
46
+ from .. import config
47
+ from . import analysis as analysis_mod
48
+ from . import gen_figures
49
+ from . import gen_tables
50
+ from . import panel
51
+ from .aggregate_results import (
52
+ _PRIMARY_METRIC_KEY,
53
+ _PRIMARY_METRIC_LOWER_IS_BETTER,
54
+ aggregate,
55
+ print_summary,
56
+ )
57
+
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ def _legacy_results_dict(granularity: str) -> dict[str, Any]:
63
+ """Return the legacy nested-dict ``all_results[_quick].json`` if present.
64
+
65
+ These files used to live under ``data_small_caps/benchmark/<g>/`` but
66
+ moved to ``experiments/results/legacy_per_family/`` once experiment
67
+ outputs were separated from the benchmark tree. The granularity
68
+ argument is kept for API compatibility with older callers; the
69
+ legacy aggregates are not per-granularity (the file was overwritten
70
+ by each granularity's runner).
71
+ """
72
+ del granularity # legacy aggregates are not per-granularity on disk
73
+ legacy_dir = Path(__file__).resolve().parent / "results" / "legacy_per_family"
74
+ for cand in ("all_results.json", "all_results_quick.json"):
75
+ p = legacy_dir / cand
76
+ if p.exists():
77
+ try:
78
+ return json.loads(p.read_text())
79
+ except (OSError, json.JSONDecodeError) as exc:
80
+ logger.warning("could not read %s: %s", p, exc)
81
+ return {}
82
+
83
+
84
+ def _write_leaderboard(per_task, output_path: Path) -> None:
85
+ lines: list[str] = []
86
+ lines.append("=== MacroLens leaderboard (per-task, primary-metric ranked) ===\n")
87
+ for task in panel.ALL_TASKS:
88
+ df = per_task.get(task)
89
+ primary = _PRIMARY_METRIC_KEY.get(task, "?")
90
+ if df is None or df.empty:
91
+ lines.append(f"\n[{task}] (no records)\n")
92
+ continue
93
+ sub = df[df["metric_name"] == primary].dropna(subset=["value"]).copy()
94
+ if sub.empty:
95
+ lines.append(f"\n[{task}] primary metric '{primary}' missing.\n")
96
+ continue
97
+ agg = (sub.groupby(["method_id", "method_family"])["value"]
98
+ .mean().reset_index())
99
+ ascending = _PRIMARY_METRIC_LOWER_IS_BETTER.get(task, True)
100
+ agg = agg.sort_values("value", ascending=ascending).reset_index(drop=True)
101
+ direction = "lower" if ascending else "higher"
102
+ lines.append(f"\n[{task}] primary={primary} ({direction}=better):\n")
103
+ for i, row in agg.iterrows():
104
+ lines.append(f" {i+1:2d}. {row['method_id']:30s} "
105
+ f"({row['method_family']:18s}) {row['value']:10.4f}\n")
106
+ output_path.write_text("".join(lines))
107
+
108
+
109
+ def build(
110
+ *,
111
+ results_glob: str,
112
+ granularity: str,
113
+ output_dir: Path,
114
+ quick: bool = False,
115
+ ) -> dict[str, Any]:
116
+ """Build every paper artefact under *output_dir*.
117
+
118
+ Returns a manifest dict with the on-disk paths of the produced
119
+ artefacts (handy for downstream LaTeX-build orchestration / CI).
120
+ """
121
+ output_dir = Path(output_dir)
122
+ tables_dir = output_dir / "tables"
123
+ figs_dir = output_dir / "figures"
124
+ analysis_dir = output_dir / "analysis"
125
+ for d in (output_dir, tables_dir, figs_dir, analysis_dir):
126
+ d.mkdir(parents=True, exist_ok=True)
127
+
128
+ manifest: dict[str, Any] = {
129
+ "results_glob": results_glob,
130
+ "granularity": granularity,
131
+ "tables": {},
132
+ "figures": {},
133
+ "analysis": None,
134
+ "leaderboard": None,
135
+ "aggregate_parquet": None,
136
+ }
137
+
138
+ # 1. Aggregate RunRecord JSONs.
139
+ parquet_path = output_dir / "aggregate.parquet"
140
+ per_task = aggregate(input_glob=results_glob, output_path=parquet_path)
141
+ manifest["aggregate_parquet"] = str(parquet_path) if parquet_path.exists() else None
142
+
143
+ # 2. Per-task leaderboard.
144
+ leaderboard_path = output_dir / "leaderboard.txt"
145
+ _write_leaderboard(per_task, leaderboard_path)
146
+ manifest["leaderboard"] = str(leaderboard_path)
147
+ print_summary(per_task)
148
+
149
+ # 3. LaTeX tables (use legacy nested-dict if available; tables degrade
150
+ # gracefully to "--" otherwise).
151
+ legacy = _legacy_results_dict(granularity)
152
+ table_calls: list[tuple[str, Any]] = [
153
+ ("tsf", gen_tables.gen_tab_tsf(legacy, granularity)),
154
+ ("valuation", gen_tables.gen_tab_valuation(legacy)),
155
+ ("generation", gen_tables.gen_tab_generation(legacy)),
156
+ ("scenario", gen_tables.gen_tab_scenario(legacy)),
157
+ ("re", gen_tables.gen_tab_re(legacy)),
158
+ ("zs_vs_ft", gen_tables.gen_tab_zs_vs_ft(legacy, granularity)),
159
+ ("ablation", gen_tables.gen_tab_ablation(legacy)),
160
+ ("panel", gen_tables.gen_tab_panel_summary()),
161
+ ]
162
+ for name, body in table_calls:
163
+ path = tables_dir / f"tab_{name}.tex"
164
+ path.write_text(body)
165
+ manifest["tables"][name] = str(path)
166
+
167
+ # 4. Figures.
168
+ long_df = None
169
+ try:
170
+ # Reuse the long-form DataFrame already produced by aggregate(); we
171
+ # have to re-build it because aggregate() returns per-task split.
172
+ from .aggregate_results import _load_records, _records_to_long_df
173
+ paths = [Path(p) for p in sorted(glob.glob(results_glob))]
174
+ recs, _, _ = _load_records(paths)
175
+ long_df = _records_to_long_df(recs)
176
+ except Exception as exc: # pragma: no cover -- defensive
177
+ logger.warning("could not build long-form DF for figures: %s", exc)
178
+ if long_df is None:
179
+ import pandas as pd
180
+ long_df = pd.DataFrame()
181
+ fig_outputs = gen_figures.render_all(
182
+ long_df, figs_dir, granularity=granularity, quick=quick,
183
+ )
184
+ manifest["figures"] = {
185
+ n: {"pdf": str(pdf), "png": str(png)} for n, (pdf, png) in fig_outputs.items()
186
+ }
187
+
188
+ # 5. Stratified analysis.
189
+ try:
190
+ analysis_results = analysis_mod.run_all_analyses(granularity)
191
+ analysis_out = analysis_dir / "analysis_results.json"
192
+ analysis_out.write_text(json.dumps(analysis_results, indent=2, default=str))
193
+ manifest["analysis"] = str(analysis_out)
194
+ except Exception as exc:
195
+ logger.warning("analysis pipeline failed: %s", exc)
196
+ manifest["analysis_error"] = str(exc)
197
+
198
+ # 6. Manifest.
199
+ manifest_path = output_dir / "manifest.json"
200
+ manifest_path.write_text(json.dumps(manifest, indent=2, default=str))
201
+ return manifest
202
+
203
+
204
+ def main(argv: list[str] | None = None) -> int:
205
+ parser = argparse.ArgumentParser(description=__doc__)
206
+ parser.add_argument(
207
+ "--results-glob", type=str,
208
+ # Results live under experiments/results/, NOT data_small_caps/.
209
+ default=str(Path(__file__).parent / "results" / "canon_*.json"),
210
+ )
211
+ parser.add_argument(
212
+ "--granularity", default="daily",
213
+ choices=["daily", "weekly", "monthly"],
214
+ )
215
+ parser.add_argument(
216
+ "--output-dir", type=Path,
217
+ default=Path(__file__).parent / "paper_artifacts",
218
+ )
219
+ parser.add_argument("--quick", action="store_true",
220
+ help="Downsample inputs to keep CI runs fast.")
221
+ args = parser.parse_args(argv)
222
+
223
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
224
+ manifest = build(
225
+ results_glob=args.results_glob,
226
+ granularity=args.granularity,
227
+ output_dir=args.output_dir,
228
+ quick=args.quick,
229
+ )
230
+ logger.info("paper artefacts manifest: %s", manifest.get("aggregate_parquet"))
231
+ return 0
232
+
233
+
234
+ if __name__ == "__main__": # pragma: no cover
235
+ import sys
236
+ sys.exit(main())
code/experiments/gen_figures.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paper figure generator.
2
+
3
+ Produces four PDF figures for the MacroLens NeurIPS 2026 D&B paper.
4
+ Source of truth: aggregated long-DataFrame from
5
+ :mod:`experiments.aggregate_results` (or load directly from a results JSON
6
+ glob via the CLI below).
7
+
8
+ Figures (all panel-driven; method ordering follows the registry's
9
+ ``family -> name`` sort):
10
+
11
+ * ``fig_panel_overview`` - Figure 1 (page-1 schematic): grid of 7 tasks
12
+ x 7 families with counts where the family covers the task. Plus the
13
+ benchmark headline numbers (4,416 tickers, 131 features, 1,130 events).
14
+ * ``fig_primary_metric_per_task`` - One subplot per task; horizontal bar
15
+ chart of method primary-metric values with bootstrap-CI error bars; methods
16
+ ordered by primary metric (best at top).
17
+ * ``fig_per_family_box`` - One subplot per task; box-and-whisker of
18
+ primary metric grouped by family (n=members in that family that cover the
19
+ task). Shows family-level distribution.
20
+ * ``fig_zs_vs_ft`` - Bar chart: ZS vs FT for the LLM family
21
+ (the 3 frontier models), only on T1.
22
+
23
+ (Single-horizon experiment design — no horizon-curve figure; horizon is
24
+ fixed to the longest configured value per granularity, e.g. 252 daily.)
25
+
26
+ CLI::
27
+
28
+ python -m projects.agent_builder.scripts.whatif_bench.experiments.gen_figures \
29
+ --results-glob 'experiments/results/canon_*.json' \
30
+ --output-dir 'experiments/paper_artifacts/figures/' \
31
+ --granularity daily
32
+
33
+ Headless: matplotlib is forced to the ``Agg`` backend so the script runs on a
34
+ GPU box / CI without an X server. Each figure is saved as both ``.pdf``
35
+ (vector, for LaTeX) and ``.png`` (raster, for previews / quicklook).
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import argparse
41
+ import glob
42
+ import logging
43
+ from pathlib import Path
44
+ from typing import Iterable
45
+
46
+ import matplotlib
47
+
48
+ matplotlib.use("Agg") # headless
49
+ import matplotlib.pyplot as plt # noqa: E402
50
+ import numpy as np # noqa: E402
51
+ import pandas as pd # noqa: E402
52
+
53
+ from .. import config # noqa: E402
54
+ from . import panel # noqa: E402
55
+ from .aggregate_results import ( # noqa: E402
56
+ _PRIMARY_METRIC_KEY,
57
+ _PRIMARY_METRIC_LOWER_IS_BETTER,
58
+ _load_records,
59
+ _records_to_long_df,
60
+ aggregate,
61
+ )
62
+
63
+
64
+ logger = logging.getLogger(__name__)
65
+
66
+
67
+ # Friendly family display name + plot colour. Stable across all figures so
68
+ # the same family always reads as the same hue.
69
+ _FAMILY_ORDER: tuple[str, ...] = (
70
+ "naive", "classical", "sequence",
71
+ "tsfm",
72
+ "llm_ts",
73
+ "llm",
74
+ )
75
+ _FAMILY_DISPLAY: dict[str, str] = {
76
+ "naive": "Naive",
77
+ "classical": "Classical",
78
+ "sequence": "Deep Seq",
79
+ "tsfm": "TSFM",
80
+ "llm_ts": "LLM-TS",
81
+ "llm": "LLM",
82
+ }
83
+ _FAMILY_COLOR: dict[str, str] = {
84
+ "naive": "tab:gray",
85
+ "classical": "tab:olive",
86
+ "sequence": "tab:blue",
87
+ "tsfm": "tab:cyan",
88
+ "llm_ts": "tab:purple",
89
+ "llm": "tab:orange",
90
+ }
91
+
92
+ # Registry-family aliases used by the runner inside the long DataFrame's
93
+ # ``method_family`` column. Panel and registry now use the same canonical
94
+ # family names ("tsfm", "llm", "llm_ts"); the alias map is a no-op kept
95
+ # only so adding a new family later is a one-line change.
96
+ _FAMILY_ALIASES: dict[str, str] = {}
97
+
98
+
99
+ def _canonical_family(family: str) -> str:
100
+ return _FAMILY_ALIASES.get(family, family)
101
+
102
+
103
+ def _save_fig(fig: plt.Figure, output_path: Path) -> tuple[Path, Path]:
104
+ """Save *fig* as both ``output_path.pdf`` and ``output_path.png``."""
105
+ output_path = Path(output_path)
106
+ output_path.parent.mkdir(parents=True, exist_ok=True)
107
+ pdf = output_path.with_suffix(".pdf")
108
+ png = output_path.with_suffix(".png")
109
+ fig.savefig(pdf, bbox_inches="tight", dpi=300)
110
+ fig.savefig(png, bbox_inches="tight", dpi=200)
111
+ plt.close(fig)
112
+ return pdf, png
113
+
114
+
115
+ def _method_display(method_id: str) -> str:
116
+ """Display name for *method_id* (panel-aware, registry-fallback)."""
117
+ for m in panel.ALL_METHODS:
118
+ if m.id == method_id:
119
+ return m.name
120
+ return method_id
121
+
122
+
123
+ def _primary_view(df: pd.DataFrame, task: str) -> pd.DataFrame:
124
+ """Per-method mean-over-seeds view of the task's primary metric."""
125
+ metric = _PRIMARY_METRIC_KEY.get(task)
126
+ if metric is None or df.empty:
127
+ return pd.DataFrame()
128
+ sub = df[(df["task"] == task) & (df["metric_name"] == metric)].copy()
129
+ if sub.empty:
130
+ return sub
131
+ grouped = (
132
+ sub.groupby(["method_id", "method_family"], as_index=False)
133
+ .agg(value=("value", "mean"),
134
+ ci_lo=("ci_lo", "mean"),
135
+ ci_hi=("ci_hi", "mean"),
136
+ std=("std", "mean"))
137
+ )
138
+ grouped["family"] = grouped["method_family"].map(_canonical_family)
139
+ grouped["display"] = grouped["method_id"].map(_method_display)
140
+ grouped = grouped.dropna(subset=["value"])
141
+ return grouped
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # Figure 1: panel overview (task x family coverage matrix)
146
+ # ---------------------------------------------------------------------------
147
+
148
+ def fig_panel_overview(df: pd.DataFrame, output_path: Path) -> tuple[Path, Path]:
149
+ """Page-1 schematic: 7 tasks x 7 families coverage grid + headline numbers.
150
+
151
+ *df* is unused for the static schematic; accepted to keep the figure-API
152
+ uniform across the five generators.
153
+ """
154
+ tasks = list(panel.ALL_TASKS)
155
+ families = list(_FAMILY_ORDER)
156
+
157
+ # Build coverage matrix from panel.ALL_METHODS (canonical 18-method panel).
158
+ coverage = np.zeros((len(families), len(tasks)), dtype=int)
159
+ for m in panel.ALL_METHODS:
160
+ if m.family not in _FAMILY_DISPLAY:
161
+ continue # unknown family – skip
162
+ i = families.index(m.family)
163
+ for t in m.tasks:
164
+ if t in tasks:
165
+ j = tasks.index(t)
166
+ coverage[i, j] += 1
167
+
168
+ fig, ax = plt.subplots(figsize=(8.5, 4.0))
169
+ # Heatmap with a reversed grayscale palette so 0 = white, n>0 = darker.
170
+ im = ax.imshow(coverage, aspect="auto", cmap="Blues",
171
+ vmin=0, vmax=max(1, int(coverage.max())))
172
+ ax.set_xticks(range(len(tasks)))
173
+ ax.set_xticklabels(tasks, fontsize=10)
174
+ ax.set_yticks(range(len(families)))
175
+ ax.set_yticklabels([_FAMILY_DISPLAY[f] for f in families], fontsize=10)
176
+ for i in range(len(families)):
177
+ for j in range(len(tasks)):
178
+ n = coverage[i, j]
179
+ if n > 0:
180
+ ax.text(j, i, str(n), ha="center", va="center",
181
+ color="white" if n >= 2 else "black", fontsize=10)
182
+ ax.set_title("MacroLens method-x-task coverage "
183
+ "(4,416 tickers; 131 features; 1,130 events)",
184
+ fontsize=11)
185
+ fig.colorbar(im, ax=ax, label="# methods")
186
+ fig.tight_layout()
187
+ return _save_fig(fig, output_path)
188
+
189
+
190
+ # ---------------------------------------------------------------------------
191
+ # Figure 2: primary metric per task
192
+ # ---------------------------------------------------------------------------
193
+
194
+ def fig_primary_metric_per_task(df: pd.DataFrame, output_path: Path) -> tuple[Path, Path]:
195
+ """One horizontal-bar subplot per task; bars sorted best-on-top."""
196
+ tasks = list(panel.ALL_TASKS)
197
+ n_tasks = len(tasks)
198
+ ncols = 2
199
+ nrows = (n_tasks + ncols - 1) // ncols
200
+ fig, axes = plt.subplots(nrows, ncols, figsize=(11, 2.4 * nrows + 1.0),
201
+ squeeze=False)
202
+ axes_flat = axes.flatten()
203
+
204
+ any_data = False
205
+ for k, t in enumerate(tasks):
206
+ ax = axes_flat[k]
207
+ view = _primary_view(df, t)
208
+ primary = _PRIMARY_METRIC_KEY[t]
209
+ ascending = _PRIMARY_METRIC_LOWER_IS_BETTER[t]
210
+
211
+ if view.empty:
212
+ ax.set_axis_off()
213
+ ax.set_title(f"{t} — no records")
214
+ continue
215
+ any_data = True
216
+ view = view.sort_values("value", ascending=ascending).reset_index(drop=True)
217
+ # Reverse so best-on-top after barh paints bottom-up.
218
+ view = view.iloc[::-1].reset_index(drop=True)
219
+
220
+ y = np.arange(len(view))
221
+ # Symmetric error length from CI; fall back to std if CI absent.
222
+ lo = view["value"].to_numpy() - view["ci_lo"].to_numpy()
223
+ hi = view["ci_hi"].to_numpy() - view["value"].to_numpy()
224
+ lo = np.where(np.isnan(lo), view["std"].fillna(0).to_numpy(), lo)
225
+ hi = np.where(np.isnan(hi), view["std"].fillna(0).to_numpy(), hi)
226
+ lo = np.clip(lo, 0, None)
227
+ hi = np.clip(hi, 0, None)
228
+ colors = [_FAMILY_COLOR.get(f, "tab:gray") for f in view["family"]]
229
+ ax.barh(y, view["value"], xerr=[lo, hi], color=colors,
230
+ edgecolor="black", linewidth=0.4, capsize=2)
231
+ ax.set_yticks(y)
232
+ ax.set_yticklabels(view["display"], fontsize=8)
233
+ ax.set_title(f"{t} ({primary})", fontsize=10)
234
+ ax.tick_params(axis="x", labelsize=8)
235
+
236
+ # Hide unused axes
237
+ for k in range(len(tasks), len(axes_flat)):
238
+ axes_flat[k].set_axis_off()
239
+
240
+ # Family legend – only families that actually appear.
241
+ seen_fams = sorted({_canonical_family(f) for f in df["method_family"].unique()
242
+ if isinstance(f, str)}) if not df.empty else []
243
+ handles = [plt.Rectangle((0, 0), 1, 1, color=_FAMILY_COLOR[f])
244
+ for f in seen_fams if f in _FAMILY_COLOR]
245
+ labels = [_FAMILY_DISPLAY[f] for f in seen_fams if f in _FAMILY_COLOR]
246
+ if handles:
247
+ fig.legend(handles, labels, ncol=min(len(handles), 4),
248
+ loc="lower center", bbox_to_anchor=(0.5, -0.01),
249
+ fontsize=8, frameon=False)
250
+ fig.suptitle(
251
+ "Per-task primary-metric leaderboard (mean across seeds; "
252
+ "error bars = bootstrap 95% CI)" if any_data
253
+ else "Per-task primary-metric leaderboard (no data)",
254
+ fontsize=11,
255
+ )
256
+ fig.tight_layout(rect=[0, 0.03, 1, 0.97])
257
+ return _save_fig(fig, output_path)
258
+
259
+
260
+ # ---------------------------------------------------------------------------
261
+ # Figure 3: T1 horizon curves
262
+ # ---------------------------------------------------------------------------
263
+
264
+ # ---------------------------------------------------------------------------
265
+ # Figure 4: per-family box plot
266
+ # ---------------------------------------------------------------------------
267
+
268
+ def fig_per_family_box(df: pd.DataFrame, output_path: Path) -> tuple[Path, Path]:
269
+ """One box-plot subplot per task; primary metric grouped by family."""
270
+ tasks = list(panel.ALL_TASKS)
271
+ n_tasks = len(tasks)
272
+ ncols = 2
273
+ nrows = (n_tasks + ncols - 1) // ncols
274
+ fig, axes = plt.subplots(nrows, ncols, figsize=(11, 2.4 * nrows + 1.0),
275
+ squeeze=False)
276
+ axes_flat = axes.flatten()
277
+
278
+ for k, t in enumerate(tasks):
279
+ ax = axes_flat[k]
280
+ view = _primary_view(df, t)
281
+ primary = _PRIMARY_METRIC_KEY[t]
282
+ if view.empty:
283
+ ax.set_axis_off()
284
+ ax.set_title(f"{t} — no records")
285
+ continue
286
+ # Group values by family, drop empties, preserve canonical order.
287
+ groups: list[tuple[str, np.ndarray]] = []
288
+ for fam in _FAMILY_ORDER:
289
+ arr = view.loc[view["family"] == fam, "value"].to_numpy()
290
+ arr = arr[~np.isnan(arr)]
291
+ if arr.size:
292
+ groups.append((fam, arr))
293
+ if not groups:
294
+ ax.set_axis_off()
295
+ ax.set_title(f"{t} — no data")
296
+ continue
297
+ positions = np.arange(len(groups))
298
+ bp = ax.boxplot([g[1] for g in groups], positions=positions, widths=0.55,
299
+ patch_artist=True)
300
+ for box, (fam, _) in zip(bp["boxes"], groups):
301
+ box.set_facecolor(_FAMILY_COLOR.get(fam, "tab:gray"))
302
+ box.set_alpha(0.7)
303
+ for med in bp["medians"]:
304
+ med.set_color("black")
305
+ ax.set_xticks(positions)
306
+ ax.set_xticklabels([_FAMILY_DISPLAY[g[0]] for g in groups],
307
+ rotation=30, ha="right", fontsize=8)
308
+ ax.set_title(f"{t} ({primary})", fontsize=10)
309
+ ax.tick_params(axis="y", labelsize=8)
310
+
311
+ for k in range(len(tasks), len(axes_flat)):
312
+ axes_flat[k].set_axis_off()
313
+ fig.suptitle("Per-family primary-metric distribution by task", fontsize=11)
314
+ fig.tight_layout(rect=[0, 0.0, 1, 0.97])
315
+ return _save_fig(fig, output_path)
316
+
317
+
318
+ # ---------------------------------------------------------------------------
319
+ # Figure 5: ZS vs FT (T1)
320
+ # ---------------------------------------------------------------------------
321
+
322
+ def fig_zs_vs_ft(df: pd.DataFrame, output_path: Path) -> tuple[Path, Path]:
323
+ """Single-panel bar chart comparing ZS vs FT on T1 for the LLM family."""
324
+ fig, ax = plt.subplots(1, 1, figsize=(6.5, 4.0))
325
+
326
+ if df.empty:
327
+ ax.text(0.5, 0.5, "no records", ha="center", va="center",
328
+ transform=ax.transAxes); ax.set_axis_off()
329
+ return _save_fig(fig, output_path)
330
+
331
+ sub = df[(df["task"] == "T1") & (df["metric_name"] == "mse")].copy()
332
+ sub["family"] = sub["method_family"].map(_canonical_family)
333
+ sub["display"] = sub["method_id"].map(_method_display)
334
+ sub["base_id"] = sub["method_id"].str.replace(r"_(zs|ft)$", "", regex=True)
335
+
336
+ # ZS-vs-FT pair: zero-shot LLMs ("llm") vs fine-tuned LLMs ("llm_ft").
337
+ # The current panel reports zero-shot only, so the FT side stays empty
338
+ # and the deferred-placeholder branch below handles the no-data case.
339
+ title, fam_pair = "LLM", ["llm", "llm_ft"]
340
+ zs = sub[sub["family"] == fam_pair[0]]
341
+ ft = sub[sub["family"] == fam_pair[1]]
342
+ if zs.empty and ft.empty:
343
+ ax.text(0.5, 0.5, f"{title}: no data", ha="center", va="center",
344
+ transform=ax.transAxes); ax.set_axis_off()
345
+ fig.suptitle("Zero-shot vs fine-tuned, T1 only", fontsize=11)
346
+ fig.tight_layout(rect=[0, 0, 1, 0.97])
347
+ return _save_fig(fig, output_path)
348
+
349
+ zs_avg = (zs.groupby("base_id", as_index=False)["value"].mean()
350
+ .rename(columns={"value": "zs"}))
351
+ ft_avg = (ft.groupby("base_id", as_index=False)["value"].mean()
352
+ .rename(columns={"value": "ft"}))
353
+ merged = zs_avg.merge(ft_avg, on="base_id", how="outer")
354
+ if merged.empty:
355
+ ax.text(0.5, 0.5, f"{title}: no data", ha="center", va="center",
356
+ transform=ax.transAxes); ax.set_axis_off()
357
+ fig.suptitle("Zero-shot vs fine-tuned, T1 only", fontsize=11)
358
+ fig.tight_layout(rect=[0, 0, 1, 0.97])
359
+ return _save_fig(fig, output_path)
360
+
361
+ merged = merged.sort_values("base_id").reset_index(drop=True)
362
+ x = np.arange(len(merged))
363
+ w = 0.36
364
+ ax.bar(x - w/2, merged["zs"].fillna(np.nan), width=w,
365
+ color=_FAMILY_COLOR[fam_pair[0]], label="ZS",
366
+ edgecolor="black", linewidth=0.4)
367
+ ax.bar(x + w/2, merged["ft"].fillna(np.nan), width=w,
368
+ color=_FAMILY_COLOR[fam_pair[1]], label="FT",
369
+ edgecolor="black", linewidth=0.4)
370
+ ax.set_xticks(x)
371
+ ax.set_xticklabels(merged["base_id"], rotation=30, ha="right", fontsize=8)
372
+ ax.set_title(f"{title} family — T1 MSE (lower = better)", fontsize=10)
373
+ ax.set_ylabel("MSE", fontsize=9)
374
+ ax.legend(fontsize=8, frameon=False)
375
+
376
+ fig.suptitle("Zero-shot vs fine-tuned, T1 only", fontsize=11)
377
+ fig.tight_layout(rect=[0, 0, 1, 0.97])
378
+ return _save_fig(fig, output_path)
379
+
380
+
381
+ # ---------------------------------------------------------------------------
382
+ # Driver
383
+ # ---------------------------------------------------------------------------
384
+
385
+ ALL_FIGURES: tuple[str, ...] = (
386
+ "panel_overview",
387
+ "primary_metric_per_task",
388
+ "per_family_box",
389
+ "zs_vs_ft",
390
+ )
391
+
392
+
393
+ def render_all(
394
+ df: pd.DataFrame,
395
+ output_dir: Path,
396
+ *,
397
+ granularity: str = "daily",
398
+ quick: bool = False,
399
+ ) -> dict[str, tuple[Path, Path]]:
400
+ """Render every paper figure from the long-form aggregator output.
401
+
402
+ *quick* downsamples the long-form input to the first 32 rows of each
403
+ (task, method) group to keep CI runs fast.
404
+ """
405
+ output_dir = Path(output_dir)
406
+ output_dir.mkdir(parents=True, exist_ok=True)
407
+ out: dict[str, tuple[Path, Path]] = {}
408
+
409
+ if quick and not df.empty:
410
+ df = (
411
+ df.groupby(["task", "method_id"], as_index=False, group_keys=False)
412
+ .head(32)
413
+ )
414
+
415
+ out["panel_overview"] = fig_panel_overview(df, output_dir / "fig_panel_overview")
416
+ out["primary_metric_per_task"] = fig_primary_metric_per_task(
417
+ df, output_dir / "fig_primary_metric_per_task")
418
+ out["per_family_box"] = fig_per_family_box(df, output_dir / "fig_per_family_box")
419
+ out["zs_vs_ft"] = fig_zs_vs_ft(df, output_dir / "fig_zs_vs_ft")
420
+ return out
421
+
422
+
423
+ def _df_from_glob(input_glob: str) -> pd.DataFrame:
424
+ paths = [Path(p) for p in sorted(glob.glob(input_glob))]
425
+ records, n_skip, n_mig = _load_records(paths)
426
+ logger.info("loaded %d records (%d non-ok, %d migrated v1->v2)",
427
+ len(records), n_skip, n_mig)
428
+ return _records_to_long_df(records)
429
+
430
+
431
+ def main(argv: list[str] | None = None) -> int:
432
+ parser = argparse.ArgumentParser(description=__doc__)
433
+ parser.add_argument(
434
+ "--results-glob", type=str,
435
+ default=str(Path(__file__).resolve().parent / "results" / "canon_*.json"),
436
+ help="Glob pointing to RunRecord JSON files.",
437
+ )
438
+ parser.add_argument(
439
+ "--output-dir", type=Path,
440
+ default=Path(__file__).resolve().parent / "paper_artifacts" / "figures",
441
+ help="Directory to write fig_*.pdf / fig_*.png pairs.",
442
+ )
443
+ parser.add_argument(
444
+ "--granularity", default="daily",
445
+ choices=["daily", "weekly", "monthly"],
446
+ )
447
+ parser.add_argument(
448
+ "--quick", action="store_true",
449
+ help="Downsample long-form input for faster CI runs.",
450
+ )
451
+ args = parser.parse_args(argv)
452
+
453
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
454
+ df = _df_from_glob(args.results_glob)
455
+ out = render_all(df, args.output_dir, granularity=args.granularity, quick=args.quick)
456
+ for name, (pdf, png) in out.items():
457
+ logger.info("wrote %s -> %s", name, pdf)
458
+ return 0
459
+
460
+
461
+ if __name__ == "__main__": # pragma: no cover
462
+ import sys
463
+ sys.exit(main())
code/experiments/gen_tables.py ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate LaTeX tables from MacroLens benchmark results.
2
+
3
+ Panel-driven: the method list comes from `experiments/panel.py` (the canonical
4
+ 18-method registry: 4 naive + 2 classical + 3 sequence + 3 TSFM + 3 LLM
5
+ + 2 LLM-TS-Multi + 1 LLM-FT), where the LLM-FT entry is a deferred-selection
6
+ slot resolved post-hoc (winner of the Family-6 ZS sweep) and rendered in
7
+ tab:zs_vs_ft / tab:ablation. Adding / removing methods updates the tables
8
+ without touching this file.
9
+
10
+ Tables produced (in dependency order, all driven by `panel.ALL_METHODS`):
11
+ 1. tab:tsf - T1 results: methods covering T1 x horizons {5, 21, 63}
12
+ 2. tab:valuation - T2 (Val-PT) + T5 (Priv-Val) side by side
13
+ 3. tab:generation - T3 (Stmt-Gen) + T6 (Gen-Eval) side by side
14
+ 4. tab:scenario - T4 (Scen-Ret)
15
+ 5. tab:re - T7 (RE-Val)
16
+ 6. tab:zs_vs_ft - ZS vs FT for the deferred-FT cell (LLM-FT)
17
+ 7. tab:ablation - 5 settings x 4 tasks for the deferred-selection model
18
+
19
+ Usage:
20
+ uv run python -m projects.agent_builder.scripts.whatif_bench.experiments.gen_tables
21
+ uv run python -m projects.agent_builder.scripts.whatif_bench.experiments.gen_tables --full
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import json
28
+ import sys
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ import pandas as pd
33
+
34
+ from .. import config
35
+ from . import panel
36
+
37
+
38
+ # ----------------------------------------------------------------------------
39
+ # Result loading
40
+ # ----------------------------------------------------------------------------
41
+ # Canonical results live in ``experiments/paper_artifacts/aggregate.parquet``
42
+ # (one long-form row per (task, method_id, metric_name) with value + CIs).
43
+ # The legacy ``experiments/results/legacy_per_family/all_results.json``
44
+ # path is still consulted as a fallback (the file used to live under
45
+ # ``data_small_caps/benchmark/<g>/`` but moved to experiments/ once
46
+ # experiment outputs were separated from the benchmark tree); for new
47
+ # submissions the parquet is the single source of truth.
48
+
49
+
50
+ def _aggregate_path() -> Path:
51
+ return Path(__file__).resolve().parent / "paper_artifacts" / "aggregate.parquet"
52
+
53
+
54
+ def _load_aggregate() -> pd.DataFrame | None:
55
+ p = _aggregate_path()
56
+ if not p.exists():
57
+ return None
58
+ try:
59
+ return pd.read_parquet(p)
60
+ except Exception as exc: # pragma: no cover -- IO-level failure
61
+ print(f"warning: could not read {p}: {exc}", file=sys.stderr)
62
+ return None
63
+
64
+
65
+ def _load_results(granularity: str = "daily", quick: bool = True) -> dict[str, Any]:
66
+ """Legacy nested-dict results loader.
67
+
68
+ Retained so the ``--legacy-json`` path that pre-dates the canon
69
+ aggregate keeps working. The primary table-generation path now
70
+ consumes :func:`_load_aggregate` and only falls back to the legacy
71
+ JSON when the parquet is missing. The legacy aggregates used to live
72
+ under ``data_small_caps/benchmark/<g>/all_results*.json`` but moved
73
+ to ``experiments/results/legacy_per_family/`` once experiment
74
+ outputs were separated from the benchmark tree; ``granularity`` is
75
+ kept for API compatibility (legacy aggregates are not per-granularity
76
+ on disk).
77
+ """
78
+ del granularity # legacy aggregates are not per-granularity on disk
79
+ suffix = "_quick" if quick else ""
80
+ legacy_dir = Path(__file__).resolve().parent / "results" / "legacy_per_family"
81
+ path = legacy_dir / f"all_results{suffix}.json"
82
+ if not path.exists():
83
+ return {}
84
+ return json.loads(path.read_text())
85
+
86
+
87
+ # ----------------------------------------------------------------------------
88
+ # Family routing: which family JSON does each method's results live under?
89
+ # ----------------------------------------------------------------------------
90
+ # Panel families and the orchestrator's per-family JSON keys are aligned
91
+ # 1:1 on the canonical names ("tsfm", "llm", "llm_ts"). The legacy panel
92
+ # ("tsfm_zs", "llm_zs", "llm_ts_multitask") was reconciled with the
93
+ # canon RunRecord families in experiments/panel.py; this map is now a
94
+ # trivial pass-through and is retained only so that adding a new family
95
+ # remains a one-line change.
96
+
97
+ _PANEL_FAMILY_TO_JSON_KEY: dict[str, str] = {
98
+ "naive": "naive",
99
+ "classical": "classical",
100
+ "sequence": "sequence",
101
+ "tsfm": "tsfm",
102
+ "llm_ts": "llm_ts_reason",
103
+ "llm": "llm",
104
+ }
105
+
106
+
107
+ # Each family's key-naming convention for the per-task result key. Kept here
108
+ # so the table generator never has to hardcode method-by-method.
109
+
110
+ def _result_key(method: panel.Method, task: panel.Task, horizon: int | None = None) -> list[str]:
111
+ """Candidate result keys to try for (method, task) under that family's JSON.
112
+
113
+ Returns a list because some families historically used multiple naming
114
+ schemes; we try them in order and use the first that matches.
115
+ """
116
+ mid = method.id
117
+ family = method.family
118
+ keys: list[str] = []
119
+
120
+ if task == "T1":
121
+ if family in ("naive", "classical", "sequence", "tsfm"):
122
+ keys.append(f"tsf_{mid}_h{horizon}")
123
+ elif family in ("llm_ts", "llm"):
124
+ keys.append(f"tsf_llm_{mid}_h{horizon}")
125
+ keys.append(f"tsf_{mid}_h{horizon}")
126
+ # llm_ts uses chattime_task_1 style:
127
+ keys.append(f"{mid}_task_1_h{horizon}")
128
+ keys.append(f"{mid}_task_1")
129
+ elif task == "T2":
130
+ keys.append(f"task_2_{mid}")
131
+ if family == "llm":
132
+ keys.append(f"task_2_llm_{mid}")
133
+ if family == "llm_ts":
134
+ keys.append(f"{mid}_task_2")
135
+ elif task == "T3":
136
+ keys.append(f"task_3_{mid}")
137
+ if family == "llm":
138
+ keys.append(f"task_3_llm_{mid}")
139
+ if family == "llm_ts":
140
+ keys.append(f"{mid}_task_3")
141
+ elif task == "T4":
142
+ keys.append(f"task_4_{mid}")
143
+ if family == "naive":
144
+ # historical_analogue lives under the alias "task_4_analogue"
145
+ keys.append("task_4_analogue")
146
+ if family == "llm":
147
+ keys.append(f"task_4_llm_{mid}")
148
+ if family == "llm_ts":
149
+ keys.append(f"{mid}_task_4")
150
+ elif task == "T5":
151
+ keys.append(f"task_5_{mid}")
152
+ if family == "llm":
153
+ keys.append(f"task_5_llm_{mid}")
154
+ if family == "llm_ts":
155
+ keys.append(f"{mid}_task_5")
156
+ elif task == "T6":
157
+ keys.append(f"task_6_{mid}")
158
+ if family == "llm":
159
+ keys.append(f"task_6_llm_{mid}")
160
+ if family == "llm_ts":
161
+ keys.append(f"{mid}_task_6")
162
+ elif task == "T7":
163
+ keys.append(f"task_7_{mid}")
164
+ if family == "llm":
165
+ keys.append(f"task_7_llm_{mid}")
166
+ if family == "llm_ts":
167
+ keys.append(f"{mid}_task_7")
168
+
169
+ return keys
170
+
171
+
172
+ def _get_family_data(data: dict, method: panel.Method) -> dict:
173
+ """Navigate `data` to the family dict for `method`."""
174
+ json_key = _PANEL_FAMILY_TO_JSON_KEY.get(method.family, method.family)
175
+ fam = data.get(json_key, {})
176
+ if not isinstance(fam, dict):
177
+ return {}
178
+ return fam
179
+
180
+
181
+ def _lookup(data: dict, method: panel.Method, task: panel.Task,
182
+ horizon: int | None = None) -> dict:
183
+ """Find the result dict for (method, task[, horizon]); empty dict if missing.
184
+
185
+ When ``data`` is the long-form parquet DataFrame (preferred path), the
186
+ return dict is a flat mapping ``metric_name -> value`` augmented with
187
+ paired ``<metric>_ci_lo`` / ``<metric>_ci_hi`` keys so existing
188
+ per-table functions keep their ``r.get("mse")`` shape but can opt
189
+ into CI rendering with ``r.get("mse_ci_lo")`` / ``_ci_hi``.
190
+
191
+ When ``data`` is the legacy nested dict, the lookup returns the cell
192
+ as-is (no CIs available).
193
+ """
194
+ if isinstance(data, pd.DataFrame):
195
+ df = data[(data["method_id"] == method.id) & (data["task"] == task)]
196
+ # Main-table lookups exclude ablation cells (the A--E settings
197
+ # live in tab:ablation, not the per-task headline tables).
198
+ df = df[df["ablation_setting"].isna()]
199
+ if df.empty:
200
+ return {}
201
+ # Most cells have a single granularity/seed; pick the latest
202
+ # timestamp deterministically.
203
+ df = df.sort_values("timestamp").groupby("metric_name").tail(1)
204
+ out: dict[str, Any] = {}
205
+ for _, row in df.iterrows():
206
+ name = row["metric_name"]
207
+ out[name] = row["value"]
208
+ if pd.notna(row.get("ci_lo")):
209
+ out[f"{name}_ci_lo"] = row["ci_lo"]
210
+ if pd.notna(row.get("ci_hi")):
211
+ out[f"{name}_ci_hi"] = row["ci_hi"]
212
+ if pd.notna(row.get("n_boot")):
213
+ out[f"{name}_n_boot"] = int(row["n_boot"])
214
+ return out
215
+ fam = _get_family_data(data, method)
216
+ if not fam:
217
+ return {}
218
+ for key in _result_key(method, task, horizon):
219
+ result = fam.get(key)
220
+ if isinstance(result, dict) and "error" not in result:
221
+ return result
222
+ return {}
223
+
224
+
225
+ # ----------------------------------------------------------------------------
226
+ # Number formatting
227
+ # ----------------------------------------------------------------------------
228
+
229
+ def _f(v, fmt: str = ".2f", default: str = "--") -> str:
230
+ if v is None:
231
+ return default
232
+ try:
233
+ if isinstance(v, (int, float)) and v != v: # NaN check
234
+ return default
235
+ return format(float(v), fmt)
236
+ except (TypeError, ValueError):
237
+ return default
238
+
239
+
240
+ def _f_ci(value, ci_lo, ci_hi, fmt: str = ".2f", default: str = "--") -> str:
241
+ """Format ``value [lo, hi]`` if CI is present; fall back to ``value``."""
242
+ point = _f(value, fmt, default)
243
+ if point == default:
244
+ return default
245
+ if ci_lo is None or ci_hi is None:
246
+ return point
247
+ try:
248
+ if (isinstance(ci_lo, float) and ci_lo != ci_lo) or (
249
+ isinstance(ci_hi, float) and ci_hi != ci_hi
250
+ ):
251
+ return point
252
+ except TypeError:
253
+ return point
254
+ return (
255
+ rf"{point}\,{{\scriptsize [{_f(ci_lo, fmt, default)},"
256
+ rf"\,{_f(ci_hi, fmt, default)}]}}"
257
+ )
258
+
259
+
260
+ def _pct(v) -> str:
261
+ """Format a fraction (0..1) as `xx.x` percent."""
262
+ if v is None:
263
+ return "--"
264
+ try:
265
+ return f"{float(v) * 100:.1f}"
266
+ except (TypeError, ValueError):
267
+ return "--"
268
+
269
+
270
+ # ----------------------------------------------------------------------------
271
+ # Tables
272
+ # ----------------------------------------------------------------------------
273
+
274
+ def gen_tab_tsf(data: dict, granularity: str = "daily") -> str:
275
+ """T1 (TSF) results across panel methods x horizons."""
276
+ horizons = config.get_horizons(granularity)
277
+ methods_t1 = [m for m in panel.ALL_METHODS if "T1" in m.tasks]
278
+
279
+ n_h = len(horizons)
280
+ col_spec = "ll " + " ".join(["rr"] * n_h)
281
+
282
+ lines: list[str] = []
283
+ lines.append(r"\begin{table}[t]")
284
+ lines.append(r"\centering")
285
+ lines.append(
286
+ r"\caption{Task 1 (TSF) results, "
287
+ f"{granularity}, lookback={config.get_lookback_windows(granularity)[0]}. "
288
+ r"Best per-column \textbf{bold}.}")
289
+ lines.append(r"\label{tab:tsf}")
290
+ lines.append(r"\resizebox{\textwidth}{!}{%")
291
+ lines.append(r"\begin{tabular}{" + col_spec + "}")
292
+ lines.append(r"\toprule")
293
+ headers = " & ".join(
294
+ rf"\multicolumn{{2}}{{c}}{{\textbf{{H={h}}}}}" for h in horizons
295
+ )
296
+ lines.append(rf"& & {headers} \\")
297
+ cmidrules = " ".join(
298
+ rf"\cmidrule(lr){{{3 + 2*i}-{4 + 2*i}}}" for i in range(n_h)
299
+ )
300
+ lines.append(cmidrules)
301
+ metric_hdr = " & ".join(["MSE", r"DA\%"] * n_h)
302
+ lines.append(rf"\textbf{{Family}} & \textbf{{Method}} & {metric_hdr} \\")
303
+ lines.append(r"\midrule")
304
+
305
+ last_family: str | None = None
306
+ for m in methods_t1:
307
+ # Group by family with a midrule between groups.
308
+ if last_family is not None and m.family != last_family:
309
+ lines.append(r"\midrule")
310
+ fam_label = m.family.replace("_", " ") if m.family != last_family else ""
311
+ last_family = m.family
312
+ row = [fam_label, m.name]
313
+ for h in horizons:
314
+ r = _lookup(data, m, "T1", horizon=h)
315
+ if "overall" in r and isinstance(r["overall"], dict):
316
+ mse = r["overall"].get("mse")
317
+ mse_lo = mse_hi = None
318
+ da = r["overall"].get("directional_accuracy")
319
+ else:
320
+ mse = r.get("mse")
321
+ mse_lo = r.get("mse_ci_lo")
322
+ mse_hi = r.get("mse_ci_hi")
323
+ da = r.get("directional_accuracy")
324
+ row += [_f_ci(mse, mse_lo, mse_hi, ".1f"), _pct(da)]
325
+ lines.append(" & ".join(row) + r" \\")
326
+
327
+ lines.append(r"\bottomrule")
328
+ lines.append(r"\end{tabular}}")
329
+ lines.append(r"\end{table}")
330
+ return "\n".join(lines)
331
+
332
+
333
+ def gen_tab_valuation(data: dict) -> str:
334
+ """T2 (Val-PT) + T5 (Priv-Val) side by side. MedAPE% / Spearman."""
335
+ methods = [m for m in panel.ALL_METHODS if "T2" in m.tasks or "T5" in m.tasks]
336
+ lines: list[str] = []
337
+ lines.append(r"\begin{table}[t]")
338
+ lines.append(r"\centering")
339
+ lines.append(
340
+ r"\caption{Valuation: Task~2 (Val-PT) vs Task~5 (Priv-Val). "
341
+ r"MedAPE\%$\downarrow$, Spearman~$\rho\uparrow$.}")
342
+ lines.append(r"\label{tab:valuation}")
343
+ lines.append(r"\resizebox{\textwidth}{!}{%")
344
+ lines.append(r"\begin{tabular}{ll cc cc}")
345
+ lines.append(r"\toprule")
346
+ lines.append(
347
+ r"& & \multicolumn{2}{c}{\textbf{T2 Val-PT}} & "
348
+ r"\multicolumn{2}{c}{\textbf{T5 Priv-Val}} \\")
349
+ lines.append(r"\cmidrule(lr){3-4} \cmidrule(lr){5-6}")
350
+ lines.append(
351
+ r"\textbf{Family} & \textbf{Method} & "
352
+ r"MedAPE\%$\downarrow$ & $\rho\uparrow$ & "
353
+ r"MedAPE\%$\downarrow$ & $\rho\uparrow$ \\")
354
+ lines.append(r"\midrule")
355
+
356
+ last_family: str | None = None
357
+ for m in methods:
358
+ if last_family is not None and m.family != last_family:
359
+ lines.append(r"\midrule")
360
+ fam_label = m.family.replace("_", " ") if m.family != last_family else ""
361
+ last_family = m.family
362
+ row = [fam_label, m.name]
363
+ for task in ("T2", "T5"):
364
+ if task in m.tasks:
365
+ r = _lookup(data, m, task)
366
+ row += [
367
+ _f_ci(r.get("median_ape"),
368
+ r.get("median_ape_ci_lo"),
369
+ r.get("median_ape_ci_hi"), ".1f"),
370
+ _f(r.get("rank_correlation"), ".3f"),
371
+ ]
372
+ else:
373
+ row += ["--", "--"]
374
+ lines.append(" & ".join(row) + r" \\")
375
+
376
+ lines.append(r"\bottomrule")
377
+ lines.append(r"\end{tabular}}")
378
+ lines.append(r"\end{table}")
379
+ return "\n".join(lines)
380
+
381
+
382
+ def gen_tab_generation(data: dict) -> str:
383
+ """T3 (Stmt-Gen) + T6 (Gen-Eval) side by side. Per-field MAPE%, Bal-Eq%."""
384
+ methods = [m for m in panel.ALL_METHODS if "T3" in m.tasks or "T6" in m.tasks]
385
+ lines: list[str] = []
386
+ lines.append(r"\begin{table}[t]")
387
+ lines.append(r"\centering")
388
+ lines.append(
389
+ r"\caption{Generation: Task~3 (Stmt-Gen) vs Task~6 (Gen-Eval). "
390
+ r"per-field MAPE\%$\downarrow$, balance-equation accuracy\%$\uparrow$.}")
391
+ lines.append(r"\label{tab:generation}")
392
+ lines.append(r"\resizebox{\textwidth}{!}{%")
393
+ lines.append(r"\begin{tabular}{ll cc cc}")
394
+ lines.append(r"\toprule")
395
+ lines.append(
396
+ r"& & \multicolumn{2}{c}{\textbf{T3 Stmt-Gen}} & "
397
+ r"\multicolumn{2}{c}{\textbf{T6 Gen-Eval}} \\")
398
+ lines.append(r"\cmidrule(lr){3-4} \cmidrule(lr){5-6}")
399
+ lines.append(
400
+ r"\textbf{Family} & \textbf{Method} & "
401
+ r"MAPE\%$\downarrow$ & Bal-Eq\%$\uparrow$ & "
402
+ r"MAPE\%$\downarrow$ & Bal-Eq\%$\uparrow$ \\")
403
+ lines.append(r"\midrule")
404
+
405
+ last_family: str | None = None
406
+ for m in methods:
407
+ if last_family is not None and m.family != last_family:
408
+ lines.append(r"\midrule")
409
+ fam_label = m.family.replace("_", " ") if m.family != last_family else ""
410
+ last_family = m.family
411
+ row = [fam_label, m.name]
412
+ for task in ("T3", "T6"):
413
+ if task in m.tasks:
414
+ r = _lookup(data, m, task)
415
+ row += [
416
+ _f_ci(r.get("overall_mape"),
417
+ r.get("overall_mape_ci_lo"),
418
+ r.get("overall_mape_ci_hi"), ".1f"),
419
+ _pct(r.get("balance_equation_accuracy")),
420
+ ]
421
+ else:
422
+ row += ["--", "--"]
423
+ lines.append(" & ".join(row) + r" \\")
424
+
425
+ lines.append(r"\bottomrule")
426
+ lines.append(r"\end{tabular}}")
427
+ lines.append(r"\end{table}")
428
+ return "\n".join(lines)
429
+
430
+
431
+ def gen_tab_scenario(data: dict) -> str:
432
+ """T4 (Scen-Ret): MAE%, DA%, CI calibration."""
433
+ methods = [m for m in panel.ALL_METHODS if "T4" in m.tasks]
434
+ lines: list[str] = []
435
+ lines.append(r"\begin{table}[t]")
436
+ lines.append(r"\centering")
437
+ lines.append(
438
+ r"\caption{Task~4 (Scen-Ret). Predict post-event return. "
439
+ r"Best per-column \textbf{bold}.}")
440
+ lines.append(r"\label{tab:scenario}")
441
+ lines.append(r"\resizebox{0.85\textwidth}{!}{%")
442
+ lines.append(r"\begin{tabular}{ll ccc}")
443
+ lines.append(r"\toprule")
444
+ lines.append(
445
+ r"\textbf{Family} & \textbf{Method} & "
446
+ r"MAE\%$\downarrow$ & DA\%$\uparrow$ & CI Cal.\%$\uparrow$ \\")
447
+ lines.append(r"\midrule")
448
+
449
+ last_family: str | None = None
450
+ for m in methods:
451
+ if last_family is not None and m.family != last_family:
452
+ lines.append(r"\midrule")
453
+ fam_label = m.family.replace("_", " ") if m.family != last_family else ""
454
+ last_family = m.family
455
+ r = _lookup(data, m, "T4")
456
+ row = [
457
+ fam_label, m.name,
458
+ _f_ci(r.get("return_mae_pct"),
459
+ r.get("return_mae_pct_ci_lo"),
460
+ r.get("return_mae_pct_ci_hi"), ".2f"),
461
+ _pct(r.get("directional_accuracy")),
462
+ _pct(r.get("ci_calibration_95")),
463
+ ]
464
+ lines.append(" & ".join(row) + r" \\")
465
+
466
+ lines.append(r"\bottomrule")
467
+ lines.append(r"\end{tabular}}")
468
+ lines.append(r"\end{table}")
469
+ return "\n".join(lines)
470
+
471
+
472
+ def gen_tab_re(data: dict) -> str:
473
+ """T7 (RE-Val): Rent MAPE / Price MAPE."""
474
+ methods = [m for m in panel.ALL_METHODS if "T7" in m.tasks]
475
+ lines: list[str] = []
476
+ lines.append(r"\begin{table}[t]")
477
+ lines.append(r"\centering")
478
+ lines.append(
479
+ r"\caption{Task~7 (RE-Val). Rent and price prediction across 100 metros.}")
480
+ lines.append(r"\label{tab:re}")
481
+ lines.append(r"\resizebox{0.7\textwidth}{!}{%")
482
+ lines.append(r"\begin{tabular}{ll cc}")
483
+ lines.append(r"\toprule")
484
+ lines.append(
485
+ r"\textbf{Family} & \textbf{Method} & "
486
+ r"Rent MAPE\%$\downarrow$ & Price MAPE\%$\downarrow$ \\")
487
+ lines.append(r"\midrule")
488
+
489
+ last_family: str | None = None
490
+ for m in methods:
491
+ if last_family is not None and m.family != last_family:
492
+ lines.append(r"\midrule")
493
+ fam_label = m.family.replace("_", " ") if m.family != last_family else ""
494
+ last_family = m.family
495
+ r = _lookup(data, m, "T7")
496
+ row = [
497
+ fam_label, m.name,
498
+ _f_ci(r.get("rent_MAPE"),
499
+ r.get("rent_MAPE_ci_lo"),
500
+ r.get("rent_MAPE_ci_hi"), ".1f"),
501
+ _f_ci(r.get("price_MAPE"),
502
+ r.get("price_MAPE_ci_lo"),
503
+ r.get("price_MAPE_ci_hi"), ".1f"),
504
+ ]
505
+ lines.append(" & ".join(row) + r" \\")
506
+
507
+ lines.append(r"\bottomrule")
508
+ lines.append(r"\end{tabular}}")
509
+ lines.append(r"\end{table}")
510
+ return "\n".join(lines)
511
+
512
+
513
+ def gen_tab_zs_vs_ft(data: dict, granularity: str = "daily") -> str:
514
+ """ZS vs FT comparison for the deferred-FT cell.
515
+
516
+ Empty stub when `panel.LLM_FT_PANEL_HF_IDS` is empty. Once the
517
+ deferred-selection rule populates that tuple, the table will resolve
518
+ to the chosen FT cell automatically.
519
+ """
520
+ horizons = config.get_horizons(granularity)
521
+ lines: list[str] = []
522
+ lines.append(r"\begin{table}[t]")
523
+ lines.append(r"\centering")
524
+ lines.append(
525
+ r"\caption{Zero-shot vs fine-tuned comparison. "
526
+ r"Deferred-selection: a single FT cell for the panel-best "
527
+ r"Family-6 ZS LLM (see paper \S6 / panel.py).}")
528
+ lines.append(r"\label{tab:zs_vs_ft}")
529
+
530
+ if not panel.LLM_FT_PANEL_HF_IDS:
531
+ lines.append(
532
+ r"\textit{Deferred -- target not yet selected from the full ZS sweep. "
533
+ r"Selection rule pre-registered in \texttt{experiments/panel.py}.}")
534
+ lines.append(r"\end{table}")
535
+ return "\n".join(lines)
536
+
537
+ # Both deferred slots resolved -> full table. Currently unreached.
538
+ lines.append(
539
+ r"\resizebox{\textwidth}{!}{%"
540
+ r"\begin{tabular}{l " + " ".join(["rrr"] * len(horizons)) + "}")
541
+ lines.append(r"\toprule")
542
+ h_hdr = " & ".join(
543
+ rf"\multicolumn{{3}}{{c}}{{\textbf{{H={h}}}}}" for h in horizons
544
+ )
545
+ lines.append(rf"& {h_hdr} \\")
546
+ cmid = " ".join(
547
+ rf"\cmidrule(lr){{{2 + 3*i}-{4 + 3*i}}}" for i in range(len(horizons))
548
+ )
549
+ lines.append(cmid)
550
+ metric_hdr = " & ".join([r"ZS & FT & $\Delta$\%"] * len(horizons))
551
+ lines.append(rf"\textbf{{Model}} & {metric_hdr} \\")
552
+ lines.append(r"\midrule")
553
+ # Rows resolved post-hoc once the deferred panels populate; left empty.
554
+ lines.append(r"\bottomrule")
555
+ lines.append(r"\end{tabular}}")
556
+ lines.append(r"\end{table}")
557
+ return "\n".join(lines)
558
+
559
+
560
+ def gen_tab_ablation(data: dict) -> str:
561
+ """Family-9 ablation: 5 settings x 4 tasks for the deferred-selection model."""
562
+ lines: list[str] = []
563
+ lines.append(r"\begin{table}[t]")
564
+ lines.append(r"\centering")
565
+ lines.append(
566
+ r"\caption{Context ablation. 5 feature settings (A-E) "
567
+ r"$\times$ 4 tasks for the deferred-FT target.}")
568
+ lines.append(r"\label{tab:ablation}")
569
+
570
+ if not panel.ABLATION_MODEL_IDS:
571
+ lines.append(
572
+ r"\textit{Deferred -- ablation model resolves to the same target as "
573
+ r"\texttt{LLM\_FT\_PANEL\_HF\_IDS} (post-hoc Family-7 ZS winner). "
574
+ r"Selection rule pre-registered in \texttt{experiments/panel.py}.}")
575
+ lines.append(r"\end{table}")
576
+ return "\n".join(lines)
577
+
578
+ # Once ABLATION_MODEL_IDS populates, render the 2 modes x 5 settings x 4 tasks.
579
+ abl = data.get("ablation", {}) if isinstance(data.get("ablation"), dict) else {}
580
+ settings = ["A", "B", "C", "D", "E"]
581
+
582
+ # 4 tasks x 2 modes (ZS, FT) = 8 columns.
583
+ col_spec = "ll " + " ".join(["rr"] * len(panel.ABLATION_TASKS))
584
+ lines.append(r"\resizebox{\textwidth}{!}{%")
585
+ lines.append(r"\begin{tabular}{" + col_spec + "}")
586
+ lines.append(r"\toprule")
587
+ task_hdr = " & ".join(
588
+ rf"\multicolumn{{2}}{{c}}{{\textbf{{{t}}}}}" for t in panel.ABLATION_TASKS
589
+ )
590
+ lines.append(rf"& & {task_hdr} \\")
591
+ cmid = " ".join(
592
+ rf"\cmidrule(lr){{{3 + 2*i}-{4 + 2*i}}}" for i in range(len(panel.ABLATION_TASKS))
593
+ )
594
+ lines.append(cmid)
595
+ mode_hdr = " & ".join(["ZS & FT"] * len(panel.ABLATION_TASKS))
596
+ lines.append(rf"\textbf{{Setting}} & \textbf{{\#Feat}} & {mode_hdr} \\")
597
+ lines.append(r"\midrule")
598
+
599
+ for s in settings:
600
+ s_meta = panel.ABLATION_SETTINGS[s]
601
+ row = [s, str(s_meta["n_features"])]
602
+ for t in panel.ABLATION_TASKS:
603
+ for mode in panel.ABLATION_MODES:
604
+ cell = abl.get(f"setting_{s}_{mode}_{t}", {})
605
+ # Use the task's primary metric defined in panel.TASK_METADATA
606
+ primary = panel.TASK_METADATA[t]["primary_metric"]
607
+ key_map = {
608
+ "MSE": "mse",
609
+ "MedAPE": "median_ape",
610
+ "Return MAE": "return_mae_pct",
611
+ "per-field MAPE": "overall_mape",
612
+ "Rent + Price MAPE": "rent_MAPE",
613
+ }
614
+ k = key_map.get(primary, "mse")
615
+ v = cell.get(k) if isinstance(cell, dict) else None
616
+ row.append(_f(v, ".1f"))
617
+ lines.append(" & ".join(row) + r" \\")
618
+
619
+ lines.append(r"\bottomrule")
620
+ lines.append(r"\end{tabular}}")
621
+ lines.append(r"\end{table}")
622
+ return "\n".join(lines)
623
+
624
+
625
+ def gen_tab_panel_summary() -> str:
626
+ """Static appendix table: the 18-method panel from panel.py (incl. 1 deferred FT cell)."""
627
+ lines: list[str] = []
628
+ lines.append(r"\begin{table}[t]")
629
+ lines.append(r"\centering")
630
+ lines.append(
631
+ r"\caption{MacroLens baseline panel. 17 fixed methods + 1 deferred-selection LLM-FT cell (post-hoc Family-6 ZS winner) = 18 entries.}")
632
+ lines.append(r"\label{tab:panel}")
633
+ lines.append(r"\begin{tabular}{lll l l}")
634
+ lines.append(r"\toprule")
635
+ lines.append(
636
+ r"\textbf{Family} & \textbf{Method} & \textbf{HF id / source} & "
637
+ r"\textbf{Tasks} & \textbf{Notes} \\")
638
+ lines.append(r"\midrule")
639
+
640
+ last_family: str | None = None
641
+ for m in panel.ALL_METHODS:
642
+ if last_family is not None and m.family != last_family:
643
+ lines.append(r"\midrule")
644
+ fam_label = m.family.replace("_", " ") if m.family != last_family else ""
645
+ last_family = m.family
646
+ tasks_str = ",".join(sorted(m.tasks))
647
+ hf = m.hf_id or "--"
648
+ # Truncate notes for table layout.
649
+ note = m.notes.replace("\n", " ").strip()
650
+ if len(note) > 60:
651
+ note = note[:57] + "..."
652
+ # Escape underscores for LaTeX in HF ids.
653
+ hf_tex = hf.replace("_", r"\_")
654
+ lines.append(
655
+ f"{fam_label} & {m.name} & \\texttt{{{hf_tex}}} & {tasks_str} & {note} \\\\"
656
+ )
657
+
658
+ lines.append(r"\midrule")
659
+ lines.append(
660
+ r"\multicolumn{5}{l}{"
661
+ r"\textit{Deferred: 1 LLM-FT cell (post-hoc Family-6 ZS winner).}} \\")
662
+
663
+ lines.append(r"\bottomrule")
664
+ lines.append(r"\end{tabular}")
665
+ lines.append(r"\end{table}")
666
+ return "\n".join(lines)
667
+
668
+
669
+ # ----------------------------------------------------------------------------
670
+ # Main
671
+ # ----------------------------------------------------------------------------
672
+
673
+ def _emit_all(data, granularity: str, output_dir: Path | None) -> None:
674
+ print("% === MacroLens Paper Tables (panel-driven) ===")
675
+ print(f"% panel summary: {panel.summary()}\n")
676
+
677
+ tables = [
678
+ ("tsf", gen_tab_tsf(data, granularity)),
679
+ ("valuation", gen_tab_valuation(data)),
680
+ ("generation", gen_tab_generation(data)),
681
+ ("scenario", gen_tab_scenario(data)),
682
+ ("re", gen_tab_re(data)),
683
+ ("zs_vs_ft", gen_tab_zs_vs_ft(data, granularity)),
684
+ ("ablation", gen_tab_ablation(data)),
685
+ ("panel", gen_tab_panel_summary()),
686
+ ]
687
+ for name, body in tables:
688
+ print(f"\n% --- tab:{name} ---")
689
+ print(body)
690
+ if output_dir is not None:
691
+ (output_dir / f"tab_{name}.tex").write_text(body)
692
+
693
+
694
+ def main():
695
+ parser = argparse.ArgumentParser(
696
+ description="Emit LaTeX tables for the MacroLens paper from aggregated results.",
697
+ )
698
+ parser.add_argument("--granularity", default="daily",
699
+ choices=["daily", "weekly", "monthly"])
700
+ parser.add_argument("--legacy-json", action="store_true",
701
+ help=("Read the legacy nested-dict all_results.json "
702
+ "instead of the canon-aggregate parquet."))
703
+ parser.add_argument("--full", action="store_true",
704
+ help=("Read full-run all_results.json instead of the "
705
+ "_quick variant (only meaningful with "
706
+ "--legacy-json)."))
707
+ parser.add_argument("--out-dir", type=Path, default=None,
708
+ help="If provided, write each table to <out>/tab_<name>.tex.")
709
+ args = parser.parse_args()
710
+
711
+ if args.legacy_json:
712
+ data: Any = _load_results(args.granularity, quick=not args.full)
713
+ else:
714
+ df = _load_aggregate()
715
+ if df is None:
716
+ print(
717
+ f"error: aggregate.parquet not found at {_aggregate_path()}; "
718
+ "run experiments/build_paper_artifacts.py or pass --legacy-json.",
719
+ file=sys.stderr,
720
+ )
721
+ sys.exit(2)
722
+ data = df
723
+
724
+ if args.out_dir is not None:
725
+ args.out_dir.mkdir(parents=True, exist_ok=True)
726
+ _emit_all(data, args.granularity, args.out_dir)
727
+
728
+
729
+ if __name__ == "__main__":
730
+ main()
code/experiments/panel.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical MacroLens baseline panel for the NeurIPS 2026 D&B submission.
2
+
3
+ Single source of truth for:
4
+ - Which methods are in the panel (18 method classes across 7 families)
5
+ - Which tasks each method covers (T1..T7)
6
+ - HuggingFace model IDs for LLM/TSFM checkpoints (FP8 native MLLMs)
7
+ - GPU parallelism hints (tensor-parallel size)
8
+ - Seed strategy (primary seed vs headline T1 subset)
9
+ - Ablation subset (5 models x 5 settings on T1 h=21 + T4)
10
+
11
+ Any change to the panel MUST happen here first; all family runners import from
12
+ this module. If a method is not in `ALL_METHODS`, the orchestrators will not
13
+ run it. If a HuggingFace ID changes, update this file only.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+ from typing import Literal
20
+
21
+ # ── Task IDs ──────────────────────────────────────────────────────────────
22
+
23
+ Task = Literal["T1", "T2", "T3", "T4", "T5", "T6", "T7"]
24
+
25
+ ALL_TASKS: tuple[Task, ...] = ("T1", "T2", "T3", "T4", "T5", "T6", "T7")
26
+
27
+ TASK_METADATA: dict[Task, dict] = {
28
+ "T1": {"name": "TSF", "long": "Contextual Time-Series Forecasting",
29
+ "primary_metric": "MSE"},
30
+ "T2": {"name": "Val-PT", "long": "Point-in-Time Equity Valuation",
31
+ "primary_metric": "MedAPE"},
32
+ "T3": {"name": "Stmt-Gen", "long": "Statement Generation",
33
+ "primary_metric": "per-field MAPE"},
34
+ "T4": {"name": "Scen-Ret", "long": "Scenario-Conditioned Return Forecasting",
35
+ "primary_metric": "Return MAE"},
36
+ "T5": {"name": "Priv-Val", "long": "Private-Company Valuation",
37
+ "primary_metric": "MedAPE"},
38
+ "T6": {"name": "Gen-Eval", "long": "Generator Evaluation",
39
+ "primary_metric": "per-field MAPE"},
40
+ "T7": {"name": "RE-Val", "long": "Real-Estate Valuation",
41
+ "primary_metric": "Rent + Price MAPE"},
42
+ }
43
+
44
+
45
+ # ── Method definitions ────────────────────────────────────────────────────
46
+
47
+ Family = Literal[
48
+ "naive", "classical", "sequence",
49
+ "tsfm",
50
+ "llm_ts",
51
+ "llm",
52
+ ]
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Method:
57
+ """Single entry in the baseline panel."""
58
+ id: str # e.g. "persistence", "chronos2_zs"
59
+ name: str # display name, e.g. "Persistence"
60
+ family: Family
61
+ tasks: frozenset[Task] # tasks this method runs on
62
+ hf_id: str | None = None # HuggingFace repo id (for LLM/TSFM)
63
+ notes: str = "" # free-form context (size, quant, TP)
64
+
65
+
66
+ # ── Family 1: Naive (4 methods) ───────────────────────────────────────────
67
+ # Deterministic heuristics and non-parametric lookups (no fitted parameters).
68
+
69
+ NAIVE_METHODS: tuple[Method, ...] = (
70
+ Method("persistence", "Persistence", "naive",
71
+ frozenset({"T1"}),
72
+ notes="Repeat last close (T1); repeat pre-event level (T4)."),
73
+ Method("sector_median", "Sector-Median", "naive",
74
+ frozenset({"T3", "T6"}),
75
+ notes="Predict each XBRL field as its sector median."),
76
+ Method("metro_median", "Metro-Median", "naive",
77
+ frozenset({"T7"}),
78
+ notes="Median rent/price in the same metro."),
79
+ Method("historical_analogue", "Historical Analogue", "naive",
80
+ frozenset({"T4"}),
81
+ notes="Find nearest past scenario by type; reuse its post-event return."),
82
+ )
83
+
84
+
85
+ # ── Family 2: Classical ML (2 methods) ────────────────────────────────────
86
+ # Fitted parametric models (OLS regression, gradient-boosted trees).
87
+
88
+ CLASSICAL_METHODS: tuple[Method, ...] = (
89
+ Method("random_forest", "RandomForest", "classical",
90
+ frozenset(ALL_TASKS),
91
+ notes="200 trees, max_depth=16, min_samples_leaf=5; sklearn RandomForestRegressor with per-task adapters mirroring LightGBM (log-return target on T1, log-target pipeline on T2/T5/T7, sparse field one-hot on T3/T6, flatten+event-type one-hot on T4)."),
92
+ Method("lightgbm", "LightGBM", "classical",
93
+ frozenset(ALL_TASKS),
94
+ notes=(
95
+ "300 trees, num_leaves=63, histogram binning; trained on "
96
+ "137-feature panel. Chosen over XGBoost for 2-5x training "
97
+ "speedup with essentially identical accuracy on financial "
98
+ "tabular data."
99
+ )),
100
+ )
101
+
102
+
103
+ # ── Family 3: Deep Sequence (3 methods) ───────────────────────────────────
104
+
105
+ SEQUENCE_METHODS: tuple[Method, ...] = (
106
+ Method("dlinear", "DLinear", "sequence",
107
+ frozenset({"T1", "T4"}),
108
+ notes="Linear decomposition baseline."),
109
+ Method("itransformer", "iTransformer", "sequence",
110
+ frozenset({"T1", "T4"}),
111
+ notes=(
112
+ "Inverted transformer (variables-as-tokens); d=128, 4 heads. "
113
+ "Chosen over PatchTST as the transformer representative: "
114
+ "its cross-variable attention matches the 137-feature "
115
+ "multivariate structure of MacroLens better than PatchTST's "
116
+ "channel-independent formulation."
117
+ )),
118
+ Method("moderntcn", "ModernTCN", "sequence",
119
+ frozenset({"T1", "T4"}),
120
+ notes="Modern pure-convolution backbone."),
121
+ )
122
+
123
+
124
+ # ── Family 4: TSFM Zero-Shot (3 methods) ──────────────────────────────────
125
+ # Sundial was dropped from the panel because its modeling code (HF Hub
126
+ # `thuml/sundial-base-128m`, vendored via `trust_remote_code`) requires
127
+ # transformers==4.40.x and is incompatible with transformers>=4.45 (used here
128
+ # for vLLM 0.20 + Llama-4 / Gemma-4 / Qwen-3.5 FP8 LLMs); the cascade includes
129
+ # DynamicCache.get_usable_length removal, _prepare_4d_causal_attention_mask
130
+ # shape mismatch under Sundial's patching, apply_rotary_pos_emb position-id
131
+ # scale mismatch, and TSGenerationMixin._extract_past_from_model_output
132
+ # removal in GenerationMixin >=4.45. Documented and removed rather than
133
+ # patched into a parallel transformers env.
134
+
135
+ TSFM_ZS_METHODS: tuple[Method, ...] = (
136
+ Method("chronos2", "Chronos-2", "tsfm",
137
+ frozenset({"T1"}),
138
+ hf_id="amazon/chronos-2",
139
+ notes="Probabilistic multivariate; frozen checkpoint."),
140
+ Method("moirai2", "Moirai 2.0", "tsfm",
141
+ frozenset({"T1"}),
142
+ hf_id="Salesforce/moirai-2.0-R-small",
143
+ notes="Any-variate universal forecaster."),
144
+ Method("timesfm", "TimesFM", "tsfm",
145
+ frozenset({"T1"}),
146
+ hf_id="google/timesfm-1.0-200m-pytorch",
147
+ notes=(
148
+ "Decoder-only foundation; TimesFM 1.0 (200M, 20 transformer "
149
+ "layers). The 2.0 checkpoint (500M, 50 layers) requires a "
150
+ "newer `timesfm` package version than the one currently "
151
+ "installed; revisit once upgraded."
152
+ )),
153
+ )
154
+
155
+
156
+ # ── Family 5: LLM-TS Multi-Task (2 methods) ───────────────────────────────
157
+ # Note: "LLM-TS Forecasting" family (CALF, TimeReasoner) was removed from the
158
+ # panel; the LLM-TS Multi-Task family covers the "LLM adapted for time-series"
159
+ # story across all 7 tasks, subsuming the forecast-only variants.
160
+
161
+ LLM_TS_MULTITASK_METHODS: tuple[Method, ...] = (
162
+ Method("chattime", "ChatTime", "llm_ts",
163
+ frozenset(ALL_TASKS),
164
+ notes="LLaMA-2-7B + 10K-bin tokenisation."),
165
+ Method("time_mqa", "Time-MQA", "llm_ts",
166
+ frozenset(ALL_TASKS),
167
+ notes="Mistral-7B + LoRA r=16; 192,843 QA pairs."),
168
+ )
169
+
170
+
171
+ # ── LLM models ────────────────────────────────────────────────────────────
172
+ # Paper-canonical Family-6 LLM panel (matches DRAFT.md §5.4 and the
173
+ # canon RunRecord JSONs under experiments/results/). Two of the four
174
+ # entries are OpenRouter-hosted closed-source models; the third
175
+ # (gpt-oss-120B) is open-weights routed via OpenRouter for compute
176
+ # economy; the fourth (Qwen-3.5-27B-FP8) runs locally on 4xA100-40GB.
177
+ # Local-vLLM fields (tensor_parallel_size, quant, prequantized) are
178
+ # meaningful only when ``provider == "local"``; for OpenRouter entries
179
+ # they carry placeholder values.
180
+
181
+ @dataclass(frozen=True)
182
+ class LLMModel:
183
+ id: str
184
+ name: str
185
+ provider: Literal["local", "openrouter"]
186
+ hf_id: str | None = None
187
+ tensor_parallel_size: int = 1
188
+ quant: Literal["fp8", "bf16"] = "fp8"
189
+ multimodal: bool = False
190
+ total_params_b: float | None = None
191
+ active_params_b: float | None = None
192
+ ft_strategy: str = "none"
193
+ prequantized: bool = False
194
+
195
+
196
+ LLM_MODELS: tuple[LLMModel, ...] = (
197
+ LLMModel(
198
+ id="gpt51",
199
+ name="GPT-5.1",
200
+ provider="openrouter",
201
+ hf_id="openai/gpt-5.1",
202
+ ft_strategy="none",
203
+ ),
204
+ LLMModel(
205
+ id="gemini3_flash",
206
+ name="Gemini-3-Flash-Preview",
207
+ provider="openrouter",
208
+ hf_id="google/gemini-3-flash-preview",
209
+ ft_strategy="none",
210
+ ),
211
+ LLMModel(
212
+ id="exaone",
213
+ name="EXAONE-4.5 32B",
214
+ provider="local",
215
+ hf_id="LGAI-EXAONE/EXAONE-4.5-32B-FP8",
216
+ tensor_parallel_size=4,
217
+ quant="fp8",
218
+ total_params_b=32.0,
219
+ active_params_b=32.0,
220
+ ft_strategy="qlora_nf4",
221
+ prequantized=True,
222
+ ),
223
+ LLMModel(
224
+ id="llama_scout",
225
+ name="Llama-4 Scout 109B",
226
+ provider="local",
227
+ hf_id="meta-llama/Llama-4-Scout-17B-16E-Instruct",
228
+ tensor_parallel_size=4,
229
+ quant="fp8",
230
+ multimodal=True,
231
+ total_params_b=109.0,
232
+ active_params_b=17.0,
233
+ ft_strategy="qlora_nf4_zero2",
234
+ prequantized=False,
235
+ ),
236
+ LLMModel(
237
+ id="qwen35",
238
+ name="Qwen-3.5-27B-FP8",
239
+ provider="local",
240
+ hf_id="Qwen/Qwen3.5-27B-FP8",
241
+ tensor_parallel_size=1,
242
+ quant="fp8",
243
+ multimodal=False,
244
+ total_params_b=27.0,
245
+ active_params_b=27.0,
246
+ ft_strategy="qlora_nf4",
247
+ prequantized=True,
248
+ ),
249
+ )
250
+
251
+ LLM_MODELS_BY_ID: dict[str, LLMModel] = {m.id: m for m in LLM_MODELS}
252
+
253
+
254
+ # ── Family 6: LLM Zero-Shot (4 methods) ───────────────────────────────────
255
+ # Method ids match the canon RunRecord JSON ``method_id`` field (no
256
+ # ``_zs`` suffix); family is ``llm`` (not ``llm_zs``).
257
+
258
+ def _llm_notes(m: LLMModel) -> str:
259
+ if m.provider == "openrouter":
260
+ return "OpenRouter API; reasoning tokens disabled."
261
+ return f"vLLM {m.quant.upper()} inference, TP={m.tensor_parallel_size}."
262
+
263
+
264
+ LLM_ZS_METHODS: tuple[Method, ...] = tuple(
265
+ Method(
266
+ id=m.id,
267
+ name=m.name,
268
+ family="llm",
269
+ tasks=frozenset(ALL_TASKS),
270
+ hf_id=m.hf_id,
271
+ notes=_llm_notes(m),
272
+ )
273
+ for m in LLM_MODELS
274
+ )
275
+
276
+
277
+ # ── Aggregation ───────────────────────────────────────────────────────────
278
+ # Paper-canonical 18 methods x 6 families. The legacy ``Method``
279
+ # dataclass list aligns with the canon RunRecord JSON ``method_id`` and
280
+ # ``method_family`` fields under ``experiments/results/``.
281
+
282
+ ALL_METHODS: tuple[Method, ...] = (
283
+ NAIVE_METHODS
284
+ + CLASSICAL_METHODS
285
+ + SEQUENCE_METHODS
286
+ + TSFM_ZS_METHODS
287
+ + LLM_TS_MULTITASK_METHODS
288
+ + LLM_ZS_METHODS
289
+ )
290
+
291
+ METHODS_BY_ID: dict[str, Method] = {m.id: m for m in ALL_METHODS}
292
+
293
+ METHODS_BY_FAMILY: dict[Family, tuple[Method, ...]] = {
294
+ "naive": NAIVE_METHODS,
295
+ "classical": CLASSICAL_METHODS,
296
+ "sequence": SEQUENCE_METHODS,
297
+ "tsfm": TSFM_ZS_METHODS,
298
+ "llm_ts": LLM_TS_MULTITASK_METHODS,
299
+ "llm": LLM_ZS_METHODS,
300
+ }
301
+
302
+
303
+ def methods_for_task_panel(task: Task) -> tuple[Method, ...]:
304
+ """All legacy panel ``Method`` dataclasses applicable to a task.
305
+
306
+ Retained under a renamed handle so the new registry-driven
307
+ :func:`methods_for_task` (returning ``list[str]`` of registry ids) is
308
+ the canonical Phase-4 entry point. Callers that need the panel
309
+ dataclass (display name, ``hf_id``, ``notes``) keep using this.
310
+ """
311
+ return tuple(m for m in ALL_METHODS if task in m.tasks)
312
+
313
+
314
+ def methods_for_family(family: Family) -> tuple[Method, ...]:
315
+ return METHODS_BY_FAMILY[family]
316
+
317
+
318
+ # ── Phase-4 unified-API panel helpers ─────────────────────────────────────
319
+ # The orchestrator (``experiments/run_all.py``) consumes the registry-driven
320
+ # 18-method panel rather than the legacy ``Method`` dataclasses above. The
321
+ # helpers below mirror the registry surface so the runner never reaches into
322
+ # ``methods._registry`` directly.
323
+
324
+ from ..methods._registry import ALL_METHODS as _REGISTRY_METHODS
325
+
326
+
327
+ def methods_for_task(task: str) -> list[str]:
328
+ """Return the sorted list of registered method ids that support ``task``.
329
+
330
+ Single source of truth for the Phase-4 runner's "skip methods that do
331
+ not support this task" filter. Reads directly from
332
+ :data:`methods._registry.ALL_METHODS`.
333
+ """
334
+ return sorted(name for name, cls in _REGISTRY_METHODS.items() if task in cls.tasks)
335
+
336
+
337
+ # Canonical 18-method panel (re-derived from the registry every call so
338
+ # additions/removals show up without an explicit panel.py edit).
339
+ PANEL: list[str] = sorted(_REGISTRY_METHODS.keys())
340
+
341
+
342
+ # ── Context ablation subset ──────────────────────────────────────────────
343
+ # DRAFT.md §5.4.1: a five-step feature-context ablation (A-E) is run on
344
+ # the panel's two zero-shot frontier LLMs (GPT-5.1, Gemini-3-Flash) on
345
+ # four tasks (T1 at h=252, T2, T4, T5). Running the full A-E factorial
346
+ # across all four LLMs would dominate the wall-clock budget; restricting
347
+ # to the two frontier LLMs preserves the contrast (does adding context
348
+ # channels help the strongest zero-shot models?) while keeping the
349
+ # 2 x 5 x 4 = 40-cell budget tractable.
350
+
351
+ ABLATION_MODEL_IDS: tuple[str, ...] = ("gpt51", "gemini3_flash")
352
+
353
+ # The submitted ablation reports zero-shot evaluation only. The FT mode is
354
+ # retained as a deferred-experiment slot; with no FT cells the table
355
+ # generator (gen_tables.gen_tab_ablation) emits a placeholder.
356
+ ABLATION_MODES: tuple[str, ...] = ("ZS",)
357
+
358
+ # Deferred fine-tune cell (DRAFT.md does not report any FT row in the
359
+ # Family-6 panel; the submitted paper is zero-shot-only across all
360
+ # four LLMs). Kept as an empty tuple so downstream table generators
361
+ # emit the deferred-placeholder branch without crashing.
362
+ LLM_FT_PANEL_HF_IDS: tuple[str, ...] = ()
363
+
364
+ ABLATION_SETTINGS: dict[str, dict] = {
365
+ "A": {"name": "OHLCV only", "n_features": 6},
366
+ "B": {"name": "A + Fundamentals (XBRL + derived)", "n_features": 70},
367
+ "C": {"name": "B + Macro (FRED + EIA)", "n_features": 123},
368
+ "D": {"name": "C + Scenario flags", "n_features": 127},
369
+ "E": {"name": "D + SBERT filing embeddings", "n_features": 511},
370
+ }
371
+
372
+ ABLATION_TASKS: tuple[Task, ...] = ("T1", "T2", "T4", "T5")
373
+ ABLATION_T1_HORIZON: int = 252
374
+ # DRAFT.md §5.4.1 / Fig. 3 caption: T1 ablation uses h=252 (the longest
375
+ # horizon, where context-channel sensitivity is highest). The other
376
+ # three ablation tasks use their full task-defined targets. T3/T6 are
377
+ # excluded because they use per-field MAPE / success_rate (different
378
+ # metric family); T7 is excluded because RentCast property features
379
+ # don't share the A-E feature space (no XBRL / FRED / scenarios).
380
+
381
+
382
+ # ── Seed policy ───────────────────────────────────────────────────────────
383
+ # v1 (initial submission): SINGLE seed = 42 for every method, every task.
384
+ # Bootstrap 95% CI (1000 resamples) on the test set provides per-method
385
+ # variance reporting -- the same approach used by 4 of 7 verified peer
386
+ # benchmarks (Time-MMD NeurIPS D&B 2024, FinTSB 2025, Fin-RATE 2026,
387
+ # SciTS ICLR 2026), all of which were accepted with single-run headline
388
+ # tables. Bootstrap CI captures test-set variance; it does NOT capture
389
+ # training-stochasticity variance.
390
+ #
391
+ # v2 (rebuttal-ready, only fired if reviewer asks): MULTI_SEEDS {42, 123,
392
+ # 456} on HEADLINE_T1_MULTISEED_METHODS at T1 h=21. Rationale for matching
393
+ # the WIT (ICLR 2026) and EDINET-Bench (ICLR 2026) precedent of 3-run mean
394
+ # +/- std on stochastic methods. Estimated rebuttal compute: ~24h on
395
+ # 4xA100-40GB (well within the 2-week NeurIPS rebuttal window). Deferring
396
+ # to rebuttal saves ~410 GPU-h up front and lets us focus initial
397
+ # wall-clock on getting the 20-method panel + 2 deferred FT cells +
398
+ # 40-cell ablation factorial fully working at single seed first.
399
+
400
+ from .. import config as _config
401
+
402
+ # Single source of truth: the seed lives in config.BENCHMARK_SEED.
403
+ # panel.PRIMARY_SEED is kept as the import handle that downstream baselines
404
+ # already use, but it MUST stay aligned with config.BENCHMARK_SEED -- the
405
+ # assertion below catches any silent drift.
406
+ PRIMARY_SEED: int = _config.BENCHMARK_SEED
407
+ assert PRIMARY_SEED == _config.BENCHMARK_SEED, (
408
+ f"panel.PRIMARY_SEED ({PRIMARY_SEED}) drifted from "
409
+ f"config.BENCHMARK_SEED ({_config.BENCHMARK_SEED})"
410
+ )
411
+ MULTI_SEEDS: tuple[int, ...] = (42, 123, 456)
412
+
413
+ # Methods that WILL report mean +/- std across MULTI_SEEDS on the headline
414
+ # T1 table IF reviewers request multi-seed during rebuttal. List is locked
415
+ # in code so the rebuttal path is documented; in v1 the seeds_for() helper
416
+ # returns only PRIMARY_SEED.
417
+ # Chosen as the stochastic methods present in the current panel; deterministic
418
+ # methods (naive, classical without re-sampling, TSFM zero-shot with fixed
419
+ # weights) would report a single seed even if multi-seed were enabled.
420
+ HEADLINE_T1_MULTISEED_METHODS: tuple[str, ...] = (
421
+ "dlinear", "itransformer", "moderntcn",
422
+ "time_mqa",
423
+ )
424
+
425
+ # Toggle. v1 = False (single seed everywhere); flip to True during rebuttal
426
+ # to activate multi-seed for HEADLINE_T1_MULTISEED_METHODS at T1 h=21.
427
+ ENABLE_MULTI_SEED: bool = False
428
+
429
+
430
+ def seeds_for(method_id: str, task: Task, horizon: int | None = None) -> tuple[int, ...]:
431
+ """Return the seed list for a method-task pair.
432
+
433
+ v1 (initial submission, ENABLE_MULTI_SEED=False): always returns
434
+ (PRIMARY_SEED,) -- single seed everywhere.
435
+
436
+ v2 (rebuttal, ENABLE_MULTI_SEED=True): returns MULTI_SEEDS on the
437
+ headline T1 subset (method in HEADLINE_T1_MULTISEED_METHODS,
438
+ task == 'T1', horizon == 21); single seed otherwise.
439
+ """
440
+ if (
441
+ ENABLE_MULTI_SEED
442
+ and task == "T1"
443
+ and horizon == 21
444
+ and method_id in HEADLINE_T1_MULTISEED_METHODS
445
+ ):
446
+ return MULTI_SEEDS
447
+ return (PRIMARY_SEED,)
448
+
449
+
450
+ # ── GPU assignment ────────────────────────────────────────────────────────
451
+ # MacroLens runs on GPU IDs 4,5,6,7 on the shared host (last 4 of the 8
452
+ # physical A100-SXM4-40GB). All scripts must respect this;
453
+ # `CUDA_VISIBLE_DEVICES` is set by the runner wrappers.
454
+ # (Memory: project_macrolens_gpus.md)
455
+
456
+ GPU_IDS: tuple[int, ...] = (4, 5, 6, 7)
457
+ CUDA_VISIBLE_DEVICES_STR: str = ",".join(str(i) for i in GPU_IDS)
458
+
459
+
460
+ # ── Summary ───────────────────────────────────────────────────────────────
461
+
462
+ def summary() -> dict:
463
+ """Return a small dict summarising the panel for logging / CI assertions."""
464
+ return {
465
+ "total_methods": len(ALL_METHODS),
466
+ "per_family": {f: len(ms) for f, ms in METHODS_BY_FAMILY.items()},
467
+ "per_task": {t: len(methods_for_task_panel(t)) for t in ALL_TASKS},
468
+ "ablation_models": len(ABLATION_MODEL_IDS),
469
+ "ablation_settings": len(ABLATION_SETTINGS),
470
+ "gpu_ids": list(GPU_IDS),
471
+ "primary_seed": PRIMARY_SEED,
472
+ "multi_seeds": list(MULTI_SEEDS),
473
+ "llm_models": [m.hf_id for m in LLM_MODELS],
474
+ }
475
+
476
+
477
+ if __name__ == "__main__":
478
+ # Quick sanity check: `python -m baselines.panel`.
479
+ # Expected total: 18 methods x 6 families (4 naive + 2 classical
480
+ # + 3 sequence + 3 tsfm + 2 llm_ts + 4 llm) -- matches DRAFT.md §5.4
481
+ # and the canon RunRecord JSONs under experiments/results/.
482
+ import json
483
+ s = summary()
484
+ assert s["total_methods"] == 18, f"Expected 18 methods, got {s['total_methods']}"
485
+ assert len(s["per_family"]) == 6, (
486
+ f"Expected 6 families, got {len(s['per_family'])}"
487
+ )
488
+ print(json.dumps(s, indent=2, default=list))
489
+ print(
490
+ f"Context ablation: 2 frontier LLMs x A-E x {{T1 h={ABLATION_T1_HORIZON},"
491
+ f" T2, T4, T5}} = 2 x {len(ABLATION_SETTINGS)}"
492
+ f" x {len(ABLATION_TASKS)} ="
493
+ f" {2 * len(ABLATION_SETTINGS) * len(ABLATION_TASKS)} cells"
494
+ " (DRAFT.md §5.4.1)."
495
+ )
code/experiments/probes/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Diagnostic probes for MacroLens (contamination, leakage, scenario validation).
2
+
3
+ Each probe is a standalone driver script that runs without modifying the
4
+ canonical evaluation pipeline. Probes write JSON reports under
5
+ ``experiments/probes_output/`` (experiment artifacts, not under
6
+ ``data_small_caps/``, which is reserved for raw + derived benchmark data).
7
+ """
code/experiments/probes/contamination.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contamination probe for LLM baselines in the MacroLens panel.
2
+
3
+ Reviewer R2 (W2.1) and R3 (W3.11) flag that the test window (2024-09-03 →
4
+ 2026-03-31) overlaps current frontier-LLM pretraining cutoffs. This module
5
+ probes per-LLM recall of test-period closing prices, filing dates, and
6
+ major news headlines on the **first half** of the test window
7
+ (2024-09-03 → ~2025-06-30), where contamination risk is concentrated; the
8
+ second half (2025-07 → 2026-03) post-dates every Family-6 model's cutoff
9
+ and is left unprobed (contamination-safe by construction).
10
+
11
+ The probe is intentionally narrow: it tests *recall*, not *evaluation
12
+ performance*. A model that recalls a specific test-period closing price
13
+ verbatim has seen that price during pretraining; the probe is silent on
14
+ whether the LLM uses that recall on the actual benchmark task.
15
+
16
+ Usage (no compute is run by importing the module)::
17
+
18
+ python -m projects.agent_builder.scripts.whatif_bench.experiments.probes.contamination \\
19
+ --model-id Qwen/Qwen3.5-27B-FP8 \\
20
+ --base-url http://localhost:8004/v1 \\
21
+ --n-samples 200 \\
22
+ --first-half-end 2025-06-30 \\
23
+ --seed 42 \\
24
+ --output experiments/probes_output/contamination_qwen35.json
25
+
26
+ Per-launch authorisation: this script issues HTTP requests to a vLLM
27
+ endpoint (or OpenRouter); the user must authorise each launch per the
28
+ project's no-unauthorised-runs policy.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import json
35
+ import logging
36
+ import os
37
+ import random
38
+ import re
39
+ from dataclasses import asdict, dataclass
40
+ from pathlib import Path
41
+ from typing import Any
42
+
43
+ import numpy as np
44
+ import pandas as pd
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Probe template construction
51
+ # ---------------------------------------------------------------------------
52
+
53
+
54
+ _PRICE_PROMPT = (
55
+ "What was the closing price of ticker {ticker} on {date}? "
56
+ "This is a factual recall question about U.S. equity markets. "
57
+ "Respond with a single number representing the closing price in USD, "
58
+ "or the exact string 'UNKNOWN' if you cannot recall it. "
59
+ "No commentary, no units, no surrounding text."
60
+ )
61
+
62
+
63
+ def _parse_price_response(text: str) -> float | None:
64
+ """Extract a single float from the response, or None on UNKNOWN/parse fail."""
65
+ if not text:
66
+ return None
67
+ stripped = text.strip()
68
+ if stripped.upper().startswith("UNKNOWN"):
69
+ return None
70
+ # Try the strict path first: response is a single number.
71
+ try:
72
+ return float(stripped)
73
+ except ValueError:
74
+ pass
75
+ # Permissive: pick the first float-looking token in the response.
76
+ matches = re.findall(r"-?\d+(?:\.\d+)?", stripped)
77
+ if matches:
78
+ try:
79
+ return float(matches[0])
80
+ except ValueError:
81
+ return None
82
+ return None
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # Recall scoring
87
+ # ---------------------------------------------------------------------------
88
+
89
+
90
+ @dataclass
91
+ class ProbeOutcome:
92
+ ticker: str
93
+ date: str
94
+ actual: float
95
+ predicted: float | None
96
+ relative_error: float | None # |pred - actual| / actual; None on UNKNOWN/parse-fail
97
+
98
+
99
+ def _score_one(actual: float, predicted: float | None) -> float | None:
100
+ if predicted is None or actual == 0:
101
+ return None
102
+ return abs(predicted - actual) / abs(actual)
103
+
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Sampling
107
+ # ---------------------------------------------------------------------------
108
+
109
+
110
+ def _load_first_half_panel(
111
+ panel_path: Path, first_half_end: str,
112
+ ) -> pd.DataFrame:
113
+ """Load the test-window panel restricted to the first half.
114
+
115
+ Expected columns: ticker, date, close (or adj_close), plus whatever
116
+ additional metadata is needed.
117
+ """
118
+ df = pd.read_parquet(panel_path, columns=["ticker", "date", "close"])
119
+ df = df.dropna(subset=["close"])
120
+ df["date"] = pd.to_datetime(df["date"]).dt.strftime("%Y-%m-%d")
121
+ return df[df["date"] <= first_half_end].reset_index(drop=True)
122
+
123
+
124
+ def _sample_pairs(
125
+ df: pd.DataFrame, n_samples: int, seed: int,
126
+ ) -> pd.DataFrame:
127
+ rng = np.random.default_rng(seed)
128
+ idx = rng.choice(len(df), size=min(n_samples, len(df)), replace=False)
129
+ return df.iloc[idx].reset_index(drop=True)
130
+
131
+
132
+ # ---------------------------------------------------------------------------
133
+ # Probe driver
134
+ # ---------------------------------------------------------------------------
135
+
136
+
137
+ def probe_closing_prices(
138
+ *,
139
+ panel_path: Path,
140
+ model_id: str,
141
+ base_url: str,
142
+ n_samples: int = 200,
143
+ first_half_end: str = "2025-06-30",
144
+ seed: int = 42,
145
+ api_key: str = "EMPTY",
146
+ recall_tolerance: float = 0.05,
147
+ ) -> dict[str, Any]:
148
+ """Run the closing-price recall probe against a single LLM endpoint.
149
+
150
+ Returns a dict with per-instance outcomes and aggregate recall stats.
151
+ Recall = fraction of samples whose predicted price is within
152
+ ``recall_tolerance`` of the ground-truth close.
153
+ """
154
+ from projects.agent_builder.scripts.whatif_bench.methods._openai_engine import OpenAIEngine
155
+
156
+ df = _load_first_half_panel(panel_path, first_half_end)
157
+ if len(df) == 0:
158
+ raise RuntimeError(
159
+ f"first-half panel is empty under filter date {first_half_end}; "
160
+ f"check the panel at {panel_path}"
161
+ )
162
+ samples = _sample_pairs(df, n_samples, seed)
163
+
164
+ engine = OpenAIEngine(base_url=base_url, api_key=api_key, model_id=model_id)
165
+ prompts = [
166
+ [{"role": "user", "content": _PRICE_PROMPT.format(ticker=row.ticker, date=row.date)}]
167
+ for row in samples.itertuples(index=False)
168
+ ]
169
+ responses = engine.chat_complete_batch(
170
+ prompts, max_tokens=64, temperature=0.0, top_p=1.0,
171
+ )
172
+
173
+ outcomes: list[ProbeOutcome] = []
174
+ for row, text in zip(samples.itertuples(index=False), responses, strict=True):
175
+ predicted = _parse_price_response(text)
176
+ rel_err = _score_one(row.close, predicted)
177
+ outcomes.append(ProbeOutcome(
178
+ ticker=row.ticker,
179
+ date=row.date,
180
+ actual=float(row.close),
181
+ predicted=predicted,
182
+ relative_error=rel_err,
183
+ ))
184
+
185
+ n = len(outcomes)
186
+ n_parse = sum(o.predicted is not None for o in outcomes)
187
+ n_recall = sum(
188
+ o.relative_error is not None and o.relative_error <= recall_tolerance
189
+ for o in outcomes
190
+ )
191
+
192
+ return {
193
+ "model_id": model_id,
194
+ "base_url": base_url,
195
+ "panel_path": str(panel_path),
196
+ "first_half_end": first_half_end,
197
+ "n_samples": n,
198
+ "n_parse_success": n_parse,
199
+ "n_recall_within_tol": n_recall,
200
+ "recall_rate": n_recall / n if n else 0.0,
201
+ "parse_rate": n_parse / n if n else 0.0,
202
+ "recall_tolerance": recall_tolerance,
203
+ "seed": seed,
204
+ "outcomes": [asdict(o) for o in outcomes],
205
+ }
206
+
207
+
208
+ # ---------------------------------------------------------------------------
209
+ # CLI
210
+ # ---------------------------------------------------------------------------
211
+
212
+
213
+ def _default_panel_path() -> Path:
214
+ from projects.agent_builder.scripts.whatif_bench import config
215
+
216
+ base = Path(config.DATA_DIR) if hasattr(config, "DATA_DIR") else (
217
+ Path(__file__).resolve().parents[2] / "data_small_caps"
218
+ )
219
+ return base / "benchmark" / "daily" / "panel_test.parquet"
220
+
221
+
222
+ def main() -> int:
223
+ parser = argparse.ArgumentParser(
224
+ description="Contamination probe for LLM baselines (closing-price recall).",
225
+ )
226
+ parser.add_argument("--model-id", required=True,
227
+ help="HuggingFace identifier or OpenRouter model slug.")
228
+ parser.add_argument("--base-url", required=True,
229
+ help="OpenAI-compatible endpoint URL (e.g., http://localhost:8004/v1).")
230
+ parser.add_argument("--n-samples", type=int, default=200,
231
+ help="Number of (ticker, date) pairs to probe.")
232
+ parser.add_argument("--first-half-end", default="2025-06-30",
233
+ help="Last date (inclusive) of the first-half window.")
234
+ parser.add_argument("--seed", type=int, default=42)
235
+ parser.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", "EMPTY"))
236
+ parser.add_argument("--panel-path", type=Path, default=None,
237
+ help="Override the default panel parquet path.")
238
+ parser.add_argument("--recall-tolerance", type=float, default=0.05,
239
+ help="Relative-error threshold for counting a sample as 'recalled'.")
240
+ parser.add_argument("--output", type=Path, required=True,
241
+ help="Path to write the JSON probe report.")
242
+ args = parser.parse_args()
243
+
244
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
245
+
246
+ panel_path = args.panel_path or _default_panel_path()
247
+ if not panel_path.exists():
248
+ logger.error("panel path %s does not exist", panel_path)
249
+ return 2
250
+
251
+ report = probe_closing_prices(
252
+ panel_path=panel_path,
253
+ model_id=args.model_id,
254
+ base_url=args.base_url,
255
+ n_samples=args.n_samples,
256
+ first_half_end=args.first_half_end,
257
+ seed=args.seed,
258
+ api_key=args.api_key,
259
+ recall_tolerance=args.recall_tolerance,
260
+ )
261
+
262
+ args.output.parent.mkdir(parents=True, exist_ok=True)
263
+ args.output.write_text(json.dumps(report, indent=2))
264
+ logger.info(
265
+ "probe finished: model=%s recall=%.2f%% (%d/%d within %.1f%% tol); parse=%.2f%% (%d/%d); report=%s",
266
+ args.model_id,
267
+ 100 * report["recall_rate"],
268
+ report["n_recall_within_tol"],
269
+ report["n_samples"],
270
+ 100 * report["recall_tolerance"],
271
+ 100 * report["parse_rate"],
272
+ report["n_parse_success"],
273
+ report["n_samples"],
274
+ args.output,
275
+ )
276
+ return 0
277
+
278
+
279
+ if __name__ == "__main__":
280
+ raise SystemExit(main())
code/experiments/probes/lightgbm_ablation.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LightGBM A->E context-ablation driver (Phase 2.1).
2
+
3
+ Runs the canonical :class:`LightGBMRegressor` across the five ablation
4
+ settings (A: OHLCV; B: +Fundamentals; C: +Macro; D: +Scenario flags;
5
+ E: +SBERT filing embeddings) on the four ablation tasks (T1 at the
6
+ panel-default horizon, T2, T4, T5). Twenty cells in total at the primary
7
+ seed; library-default LightGBM hyperparameters with no per-cell tuning
8
+ (per project memory: every benchmark cell uses library defaults).
9
+
10
+ The driver writes per-cell prediction pickles under
11
+ ``experiments/predictions/`` using the same tag convention as
12
+ :mod:`experiments.run_all` (``<method>_<task>_seed<seed>_set<setting>.pkl``)
13
+ so a subsequent ``re_evaluate.py`` pass aggregates LightGBM rows into the
14
+ same A->E table that already houses the LLM ablation cells. The driver
15
+ also writes a flat JSON summary report at
16
+ ``experiments/probes_output/lightgbm_ablation.json`` with the primary
17
+ metric per cell and cluster-bootstrap 95% CIs.
18
+
19
+ Per-launch authorisation: this is CPU-only and ~20 fits at moderate
20
+ sample sizes (T1 ~5M panel rows, T2/T5 ~1.3k snapshots, T4 ~4M scenario
21
+ rows); wall-clock estimate is well under one hour on the shared host.
22
+ The user must authorise each launch per the project's no-unauthorised-
23
+ runs policy.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import logging
31
+ import pickle
32
+ import time
33
+ from dataclasses import asdict, dataclass
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+ import numpy as np
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ # Primary metric per ablation task (mirrors the convention used by
43
+ # `gen_tables.py` for the LLM ablation column).
44
+ _PRIMARY_METRIC: dict[str, str] = {
45
+ "T1": "mse",
46
+ "T2": "medape",
47
+ "T4": "mae",
48
+ "T5": "medape",
49
+ }
50
+
51
+
52
+ # Cluster-key column per task (cluster_keys argument to ml.score).
53
+ _CLUSTER_KEY: dict[str, str] = {
54
+ "T1": "ticker",
55
+ "T2": "ticker",
56
+ "T4": "scenario_id",
57
+ "T5": "ticker",
58
+ }
59
+
60
+
61
+ @dataclass
62
+ class _CellReport:
63
+ task: str
64
+ setting: str
65
+ horizon: int | None
66
+ seed: int
67
+ n_train: int
68
+ n_test: int
69
+ primary_metric: str
70
+ value: float
71
+ ci_lo: float
72
+ ci_hi: float
73
+ fit_sec: float
74
+ predict_sec: float
75
+
76
+
77
+ def _cluster_keys(task: str, meta_test: Any) -> Any:
78
+ key = _CLUSTER_KEY[task]
79
+ if hasattr(meta_test, "columns") and key in meta_test.columns:
80
+ return meta_test[key].values
81
+ if hasattr(meta_test, "get"):
82
+ keys = meta_test.get(key)
83
+ if keys is not None:
84
+ return np.asarray(keys)
85
+ return None
86
+
87
+
88
+ def _save_predictions(
89
+ *,
90
+ pred_dir: Path,
91
+ method_id: str,
92
+ task: str,
93
+ seed: int,
94
+ setting: str,
95
+ granularity: str,
96
+ y_pred: Any,
97
+ y_test: Any,
98
+ meta_test: Any,
99
+ ) -> Path:
100
+ pred_dir.mkdir(parents=True, exist_ok=True)
101
+ tag = f"{method_id}_{task}_seed{seed}_set{setting}"
102
+ out_path = pred_dir / f"{tag}.pkl"
103
+ tmp = out_path.with_suffix(".pkl.tmp")
104
+ with open(tmp, "wb") as f:
105
+ pickle.dump({
106
+ "method_id": method_id,
107
+ "task": task,
108
+ "seed": seed,
109
+ "granularity": granularity,
110
+ "ablation_setting": setting,
111
+ "y_pred": y_pred,
112
+ "y_test": y_test,
113
+ "meta_test": meta_test,
114
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
115
+ }, f)
116
+ tmp.replace(out_path)
117
+ return out_path
118
+
119
+
120
+ def run_cell(
121
+ *,
122
+ task: str,
123
+ setting: str,
124
+ granularity: str,
125
+ horizon: int | None,
126
+ seed: int,
127
+ pred_dir: Path,
128
+ method_id: str = "lightgbm",
129
+ ) -> _CellReport:
130
+ """Fit + predict + score a single (task, setting) cell."""
131
+ import macrolens as ml
132
+
133
+ load_kwargs: dict[str, Any] = {"granularity": granularity, "setting": setting}
134
+ if task == "T1" and horizon is not None:
135
+ load_kwargs["horizon"] = horizon
136
+
137
+ train = ml.load(task, "train", **load_kwargs)
138
+ test = ml.load(task, "test", **load_kwargs)
139
+
140
+ model = ml.methods.LightGBMRegressor(task=task)
141
+ t0 = time.perf_counter()
142
+ model.fit(train.X, train.y, seed=seed)
143
+ fit_sec = time.perf_counter() - t0
144
+
145
+ t1 = time.perf_counter()
146
+ y_pred = model.predict(test.X)
147
+ predict_sec = time.perf_counter() - t1
148
+
149
+ _save_predictions(
150
+ pred_dir=pred_dir, method_id=method_id, task=task, seed=seed,
151
+ setting=setting, granularity=granularity,
152
+ y_pred=y_pred, y_test=test.y, meta_test=test.meta,
153
+ )
154
+
155
+ metrics = ml.score(
156
+ task, test.y, y_pred,
157
+ cluster_keys=_cluster_keys(task, test.meta),
158
+ resample="cluster",
159
+ n_boot="adaptive",
160
+ seed=seed,
161
+ )
162
+ primary = _PRIMARY_METRIC[task]
163
+ mv = metrics[primary]
164
+ return _CellReport(
165
+ task=task,
166
+ setting=setting,
167
+ horizon=horizon if task == "T1" else None,
168
+ seed=seed,
169
+ n_train=int(len(train.y)) if hasattr(train.y, "__len__") else -1,
170
+ n_test=int(len(test.y)) if hasattr(test.y, "__len__") else -1,
171
+ primary_metric=primary,
172
+ value=float("nan") if mv.value is None else float(mv.value),
173
+ ci_lo=float("nan") if mv.ci_lo is None else float(mv.ci_lo),
174
+ ci_hi=float("nan") if mv.ci_hi is None else float(mv.ci_hi),
175
+ fit_sec=fit_sec,
176
+ predict_sec=predict_sec,
177
+ )
178
+
179
+
180
+ def run_ablation(
181
+ *,
182
+ tasks: tuple[str, ...] | None = None,
183
+ settings: tuple[str, ...] | None = None,
184
+ granularity: str = "daily",
185
+ horizon: int | None = None,
186
+ seed: int | None = None,
187
+ pred_dir: Path | None = None,
188
+ ) -> dict[str, Any]:
189
+ """Drive the full LightGBM A->E ablation grid.
190
+
191
+ Defaults match :mod:`experiments.panel`: tasks = ABLATION_TASKS,
192
+ settings = list(ABLATION_SETTINGS), horizon = ABLATION_T1_HORIZON,
193
+ seed = PRIMARY_SEED.
194
+ """
195
+ from projects.agent_builder.scripts.whatif_bench.experiments import panel
196
+
197
+ tasks = tasks or panel.ABLATION_TASKS
198
+ settings = settings or tuple(panel.ABLATION_SETTINGS.keys())
199
+ # DRAFT.md (Fig. 3 caption / §5.4.1) reports the ablation at T1 h=252,
200
+ # not at panel.ABLATION_T1_HORIZON=21. Default to 252 so this driver
201
+ # produces cells that align with the paper's figure.
202
+ horizon = horizon if horizon is not None else 252
203
+ seed = seed if seed is not None else panel.PRIMARY_SEED
204
+ pred_dir = pred_dir or Path(__file__).resolve().parents[1] / "predictions"
205
+
206
+ reports: list[_CellReport] = []
207
+ for task in tasks:
208
+ for setting in settings:
209
+ logger.info("lightgbm ablation: task=%s setting=%s seed=%d horizon=%s",
210
+ task, setting, seed, horizon if task == "T1" else "-")
211
+ try:
212
+ cell = run_cell(
213
+ task=task, setting=setting, granularity=granularity,
214
+ horizon=horizon, seed=seed, pred_dir=pred_dir,
215
+ )
216
+ reports.append(cell)
217
+ logger.info(" -> %s=%.6g [%.6g, %.6g]",
218
+ cell.primary_metric, cell.value, cell.ci_lo, cell.ci_hi)
219
+ except Exception as exc:
220
+ logger.exception("cell failed for task=%s setting=%s: %s",
221
+ task, setting, exc)
222
+ # Record the failure but keep going; selective per-cell
223
+ # failures (e.g., missing setting-E SBERT embeddings on a
224
+ # task) must surface in the JSON report rather than abort
225
+ # the whole grid.
226
+ reports.append(_CellReport(
227
+ task=task, setting=setting,
228
+ horizon=horizon if task == "T1" else None,
229
+ seed=seed, n_train=-1, n_test=-1,
230
+ primary_metric=_PRIMARY_METRIC[task],
231
+ value=float("nan"), ci_lo=float("nan"), ci_hi=float("nan"),
232
+ fit_sec=float("nan"), predict_sec=float("nan"),
233
+ ))
234
+
235
+ return {
236
+ "probe": "lightgbm_ablation",
237
+ "method_id": "lightgbm",
238
+ "granularity": granularity,
239
+ "horizon_T1": horizon,
240
+ "seed": seed,
241
+ "tasks": list(tasks),
242
+ "settings": list(settings),
243
+ "n_cells": len(reports),
244
+ "cells": [asdict(r) for r in reports],
245
+ }
246
+
247
+
248
+ def _default_probe_dir() -> Path:
249
+ # Probe outputs live under experiments/ (experiment artifacts),
250
+ # never under data_small_caps/ (raw + derived benchmark data).
251
+ return Path(__file__).resolve().parents[1] / "probes_output"
252
+
253
+
254
+ def main() -> int:
255
+ parser = argparse.ArgumentParser(
256
+ description="LightGBM A->E context-ablation driver.",
257
+ )
258
+ parser.add_argument("--granularity", default="daily")
259
+ parser.add_argument("--tasks", nargs="+", default=None,
260
+ help="Tasks to run (default: panel.ABLATION_TASKS).")
261
+ parser.add_argument("--settings", nargs="+", default=None,
262
+ help="Ablation settings to run (default: A B C D E).")
263
+ parser.add_argument("--horizon", type=int, default=None,
264
+ help="T1 horizon (default: 252, matching DRAFT.md Fig. 3 caption).")
265
+ parser.add_argument("--seed", type=int, default=None,
266
+ help="Seed (default: panel.PRIMARY_SEED).")
267
+ parser.add_argument("--pred-dir", type=Path, default=None,
268
+ help="Override the per-cell predictions directory.")
269
+ parser.add_argument("--output", type=Path, default=None,
270
+ help="Path to the summary JSON report.")
271
+ args = parser.parse_args()
272
+
273
+ logging.basicConfig(
274
+ level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
275
+ )
276
+
277
+ report = run_ablation(
278
+ tasks=tuple(args.tasks) if args.tasks else None,
279
+ settings=tuple(args.settings) if args.settings else None,
280
+ granularity=args.granularity,
281
+ horizon=args.horizon,
282
+ seed=args.seed,
283
+ pred_dir=args.pred_dir,
284
+ )
285
+
286
+ out_path = args.output or _default_probe_dir() / "lightgbm_ablation.json"
287
+ out_path.parent.mkdir(parents=True, exist_ok=True)
288
+ out_path.write_text(json.dumps(report, indent=2, default=str))
289
+ logger.info("ablation report written to %s", out_path)
290
+ return 0
291
+
292
+
293
+ if __name__ == "__main__":
294
+ raise SystemExit(main())
code/experiments/probes/lightgbm_tuned.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LightGBM tuning fairness probe (Phase 2.5).
2
+
3
+ Reviewer R1 (W1.5 / Q1.3) and R2 (W2.3) ask whether the headline finding
4
+ "classical models lead long-horizon T1 forecasting" survives if LightGBM
5
+ is tuned rather than run at library defaults. The canonical Table 6
6
+ LightGBM row remains at library defaults per the project's no-tuning
7
+ rule (every method in the benchmark panel uses library defaults; see
8
+ project memory `feedback_use_library_defaults.md`). This probe is
9
+ **outside the panel** -- it is a one-time secondary analysis whose only
10
+ purpose is to answer the reviewers' fairness question: does a modest
11
+ hyperparameter sweep change the leaderboard?
12
+
13
+ Design: a small 3 x 3 x 2 = 18-cell grid
14
+
15
+ n_estimators ∈ {100, 500, 1000}
16
+ max_depth ∈ {6, 10, 20}
17
+ learning_rate ∈ {0.01, 0.1}
18
+
19
+ All other LightGBM settings are kept at library defaults. The grid is
20
+ run on T1 at the panel's headline T1 horizon (read from
21
+ ``experiments.panel``). For every cell we save predictions under a
22
+ distinct tag (so the probe never overwrites the canonical run) and
23
+ record the primary T1 metric with cluster-bootstrap CIs. The summary
24
+ report names the best cell, the default-config cell, and the relative
25
+ delta -- this is what the camera-ready text quotes back when explaining
26
+ the LightGBM-vs-LLM contrast.
27
+
28
+ Per-launch authorisation: this is CPU-only and 18 fits on T1's full
29
+ panel (~5M rows). Wall-clock estimate is several hours on the shared
30
+ host; the user must authorise the launch.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import itertools
37
+ import json
38
+ import logging
39
+ import pickle
40
+ import time
41
+ from dataclasses import asdict, dataclass
42
+ from pathlib import Path
43
+ from typing import Any
44
+
45
+ import numpy as np
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+
50
+ # Grid as specified by the plan; deliberately modest so the wall-clock
51
+ # stays under one human-day on the shared CPU host.
52
+ _GRID_N_ESTIMATORS: tuple[int, ...] = (100, 500, 1000)
53
+ _GRID_MAX_DEPTH: tuple[int, ...] = (6, 10, 20)
54
+ _GRID_LEARNING_RATE: tuple[float, ...] = (0.01, 0.1)
55
+
56
+
57
+ @dataclass
58
+ class _GridCell:
59
+ n_estimators: int
60
+ max_depth: int
61
+ learning_rate: float
62
+ seed: int
63
+ horizon: int
64
+ n_train: int
65
+ n_test: int
66
+ primary_metric: str
67
+ value: float
68
+ ci_lo: float
69
+ ci_hi: float
70
+ fit_sec: float
71
+ predict_sec: float
72
+ is_default: bool
73
+
74
+
75
+ def _build_config(
76
+ *, n_estimators: int, max_depth: int, learning_rate: float,
77
+ ) -> Any:
78
+ """Construct a ``LightGBMConfig`` with all other fields at defaults."""
79
+ from projects.agent_builder.scripts.whatif_bench.methods._config import (
80
+ LightGBMConfig,
81
+ )
82
+ cfg = LightGBMConfig()
83
+ cfg.n_estimators = n_estimators
84
+ cfg.max_depth = max_depth
85
+ cfg.learning_rate = learning_rate
86
+ return cfg
87
+
88
+
89
+ def _is_default_cell(n_estimators: int, max_depth: int, learning_rate: float) -> bool:
90
+ from projects.agent_builder.scripts.whatif_bench.methods._config import (
91
+ LightGBMConfig,
92
+ )
93
+ d = LightGBMConfig()
94
+ # max_depth default is -1 (unlimited); the grid uses positive depths
95
+ # only, so the default cell is never exactly reproduced by the grid.
96
+ # Flag the conventional "closest to default" cell instead, which is
97
+ # n=100, lr=0.1, max_depth=the largest grid value (closest proxy to
98
+ # the unlimited default).
99
+ return (
100
+ n_estimators == d.n_estimators
101
+ and learning_rate == d.learning_rate
102
+ and max_depth == max(_GRID_MAX_DEPTH)
103
+ )
104
+
105
+
106
+ def _save_predictions(
107
+ *,
108
+ pred_dir: Path,
109
+ method_id: str,
110
+ task: str,
111
+ seed: int,
112
+ cell_tag: str,
113
+ granularity: str,
114
+ y_pred: Any,
115
+ y_test: Any,
116
+ meta_test: Any,
117
+ ) -> Path:
118
+ pred_dir.mkdir(parents=True, exist_ok=True)
119
+ tag = f"{method_id}_{task}_seed{seed}_{cell_tag}"
120
+ out_path = pred_dir / f"{tag}.pkl"
121
+ tmp = out_path.with_suffix(".pkl.tmp")
122
+ with open(tmp, "wb") as f:
123
+ pickle.dump({
124
+ "method_id": method_id,
125
+ "task": task,
126
+ "seed": seed,
127
+ "granularity": granularity,
128
+ "cell_tag": cell_tag,
129
+ "y_pred": y_pred,
130
+ "y_test": y_test,
131
+ "meta_test": meta_test,
132
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
133
+ }, f)
134
+ tmp.replace(out_path)
135
+ return out_path
136
+
137
+
138
+ def run_grid(
139
+ *,
140
+ horizon: int | None = None,
141
+ seed: int | None = None,
142
+ granularity: str = "daily",
143
+ pred_dir: Path | None = None,
144
+ ) -> dict[str, Any]:
145
+ """Sweep the 18-cell grid on T1 at the headline horizon.
146
+
147
+ Returns a dict with one record per cell plus a flagged best cell.
148
+ """
149
+ import macrolens as ml
150
+ from projects.agent_builder.scripts.whatif_bench.experiments import panel
151
+
152
+ # Match DRAFT.md (Fig. 3 caption): T1 ablation horizon is 252, not the
153
+ # panel.ABLATION_T1_HORIZON=21 used for the analyst-rebalancing view.
154
+ horizon = horizon if horizon is not None else 252
155
+ seed = seed if seed is not None else panel.PRIMARY_SEED
156
+ pred_dir = pred_dir or Path(__file__).resolve().parents[1] / "predictions"
157
+
158
+ train = ml.load("T1", "train", granularity=granularity, horizon=horizon)
159
+ test = ml.load("T1", "test", granularity=granularity, horizon=horizon)
160
+
161
+ cells: list[_GridCell] = []
162
+ for n_est, max_d, lr in itertools.product(
163
+ _GRID_N_ESTIMATORS, _GRID_MAX_DEPTH, _GRID_LEARNING_RATE,
164
+ ):
165
+ cell_tag = f"grid_n{n_est}_d{max_d}_lr{lr:.3g}".replace(".", "p")
166
+ logger.info("grid cell: n=%d depth=%d lr=%.3g (tag=%s)",
167
+ n_est, max_d, lr, cell_tag)
168
+ cfg = _build_config(
169
+ n_estimators=n_est, max_depth=max_d, learning_rate=lr,
170
+ )
171
+ model = ml.methods.LightGBMRegressor(task="T1", config=cfg)
172
+ t0 = time.perf_counter()
173
+ model.fit(train.X, train.y, seed=seed)
174
+ fit_sec = time.perf_counter() - t0
175
+ t1 = time.perf_counter()
176
+ y_pred = model.predict(test.X)
177
+ predict_sec = time.perf_counter() - t1
178
+
179
+ _save_predictions(
180
+ pred_dir=pred_dir, method_id="lightgbm_tuned", task="T1",
181
+ seed=seed, cell_tag=cell_tag, granularity=granularity,
182
+ y_pred=y_pred, y_test=test.y, meta_test=test.meta,
183
+ )
184
+
185
+ cluster_keys = None
186
+ if hasattr(test.meta, "columns") and "ticker" in test.meta.columns:
187
+ cluster_keys = test.meta["ticker"].values
188
+ metrics = ml.score(
189
+ "T1", test.y, y_pred,
190
+ cluster_keys=cluster_keys, resample="cluster",
191
+ n_boot="adaptive", seed=seed,
192
+ )
193
+ mv = metrics["mse"]
194
+ value = float("nan") if mv.value is None else float(mv.value)
195
+ ci_lo = float("nan") if mv.ci_lo is None else float(mv.ci_lo)
196
+ ci_hi = float("nan") if mv.ci_hi is None else float(mv.ci_hi)
197
+
198
+ cells.append(_GridCell(
199
+ n_estimators=n_est, max_depth=max_d, learning_rate=lr,
200
+ seed=seed, horizon=horizon,
201
+ n_train=int(len(train.y)) if hasattr(train.y, "__len__") else -1,
202
+ n_test=int(len(test.y)) if hasattr(test.y, "__len__") else -1,
203
+ primary_metric="mse", value=value, ci_lo=ci_lo, ci_hi=ci_hi,
204
+ fit_sec=fit_sec, predict_sec=predict_sec,
205
+ is_default=_is_default_cell(n_est, max_d, lr),
206
+ ))
207
+ logger.info(" -> mse=%.4g [%.4g, %.4g]", value, ci_lo, ci_hi)
208
+
209
+ # Identify the best (minimum) cell by primary metric.
210
+ finite = [c for c in cells if np.isfinite(c.value)]
211
+ best = min(finite, key=lambda c: c.value) if finite else None
212
+ default = next((c for c in cells if c.is_default), None)
213
+ delta = (
214
+ (default.value - best.value) / abs(default.value)
215
+ if (best is not None and default is not None and default.value != 0)
216
+ else None
217
+ )
218
+
219
+ return {
220
+ "probe": "lightgbm_tuned",
221
+ "method_id": "lightgbm_tuned",
222
+ "task": "T1",
223
+ "granularity": granularity,
224
+ "horizon": horizon,
225
+ "seed": seed,
226
+ "grid": {
227
+ "n_estimators": list(_GRID_N_ESTIMATORS),
228
+ "max_depth": list(_GRID_MAX_DEPTH),
229
+ "learning_rate": list(_GRID_LEARNING_RATE),
230
+ },
231
+ "best_cell": asdict(best) if best is not None else None,
232
+ "default_proxy_cell": asdict(default) if default is not None else None,
233
+ "relative_improvement_over_default": delta,
234
+ "cells": [asdict(c) for c in cells],
235
+ }
236
+
237
+
238
+ def _default_probe_dir() -> Path:
239
+ # Probe outputs live under experiments/ (experiment artifacts),
240
+ # never under data_small_caps/ (raw + derived benchmark data).
241
+ return Path(__file__).resolve().parents[1] / "probes_output"
242
+
243
+
244
+ def main() -> int:
245
+ parser = argparse.ArgumentParser(
246
+ description="LightGBM tuning fairness probe (fairness check; NOT in panel).",
247
+ )
248
+ parser.add_argument("--granularity", default="daily")
249
+ parser.add_argument("--horizon", type=int, default=None,
250
+ help="T1 horizon (default: 252, matching DRAFT.md Fig. 3 caption).")
251
+ parser.add_argument("--seed", type=int, default=None,
252
+ help="Seed (default: panel.PRIMARY_SEED).")
253
+ parser.add_argument("--pred-dir", type=Path, default=None,
254
+ help="Override the per-cell predictions directory.")
255
+ parser.add_argument("--output", type=Path, default=None,
256
+ help="Path to the summary JSON report.")
257
+ args = parser.parse_args()
258
+
259
+ logging.basicConfig(
260
+ level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
261
+ )
262
+
263
+ report = run_grid(
264
+ horizon=args.horizon, seed=args.seed,
265
+ granularity=args.granularity, pred_dir=args.pred_dir,
266
+ )
267
+
268
+ out_path = args.output or _default_probe_dir() / "lightgbm_tuned.json"
269
+ out_path.parent.mkdir(parents=True, exist_ok=True)
270
+ out_path.write_text(json.dumps(report, indent=2, default=str))
271
+ logger.info("tuned-grid report written to %s", out_path)
272
+ return 0
273
+
274
+
275
+ if __name__ == "__main__":
276
+ raise SystemExit(main())
code/experiments/probes/llm_finetune_qwen.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Qwen-3.5-27B QLoRA fine-tune driver for the deferred Family-7 slot.
2
+
3
+ Plan reference: Phase 3.1 (R1 Q1.3, R2 Q2.4, R3 W3.4 saturation, R5 W5.1;
4
+ author A2). T3 and T6 saturate near 100% MAPE for every zero-shot LLM
5
+ in the panel; they are the cleanest demonstration target for whether
6
+ MacroLens supports supervised LLM training. This driver populates the
7
+ single deferred Family-7 column in Tables 6-10.
8
+
9
+ Design choices (orthodox interpretation of the existing
10
+ :mod:`methods.llm_finetune` infrastructure):
11
+
12
+ * **Per-task adapters.** :class:`methods.LLMFineTuned` fixes ``self.task``
13
+ at construction and dispatches on it; we therefore train TWO adapters,
14
+ one for T3 and one for T6, rather than one bundled multi-task adapter.
15
+ Both tasks share the same JSON output schema (11 canonical XBRL
16
+ fields); the per-task split keeps the prompt format precisely matched
17
+ to each task. This is the simplest configuration that uses the
18
+ existing class as-is.
19
+ * **Cross-task transfer.** The T3 adapter is evaluated zero-shot on
20
+ T1 / T2 / T4 / T5 / T7 as a catastrophic-forgetting check: if a single
21
+ task's QLoRA pass leaves the model's competence on other tasks intact,
22
+ the result-table column can be populated end-to-end; otherwise the
23
+ cross-task entries become Family-7 / not-applicable.
24
+ * **Library defaults.** ``LLMFineTunedConfig`` ships with
25
+ ``lora_r=16, lora_alpha=32, epochs=3, learning_rate=2e-4`` -- this
26
+ is what the panel-FT recipe was originally pre-registered to use. We
27
+ do not vary any of those four numbers in this driver, per the
28
+ no-tuning rule.
29
+ * **Single seed.** ``panel.PRIMARY_SEED = 42`` end-to-end.
30
+
31
+ Per-launch authorisation: this is a multi-hour GPU run (4 x A100-40GB,
32
+ GPU IDs 4-7 per project memory). The user must authorise the launch.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import json
39
+ import logging
40
+ import pickle
41
+ import time
42
+ from dataclasses import asdict, dataclass
43
+ from pathlib import Path
44
+ from typing import Any
45
+
46
+ import numpy as np
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+
51
+ # Tasks evaluated by the trained adapters. Native-task targets are
52
+ # the rows that directly populate the Family-7 column; cross-task
53
+ # targets test for catastrophic forgetting.
54
+ _NATIVE_TASKS: tuple[str, ...] = ("T3", "T6")
55
+ _CROSS_TASKS: tuple[str, ...] = ("T1", "T2", "T4", "T5", "T7")
56
+
57
+
58
+ # Primary metric per task (mirrors gen_tables.py conventions).
59
+ _PRIMARY_METRIC: dict[str, str] = {
60
+ "T1": "mse",
61
+ "T2": "medape",
62
+ "T3": "mape",
63
+ "T4": "mae",
64
+ "T5": "medape",
65
+ "T6": "mape",
66
+ "T7": "mape",
67
+ }
68
+
69
+
70
+ _CLUSTER_KEY: dict[str, str] = {
71
+ "T1": "ticker",
72
+ "T2": "ticker",
73
+ "T3": "ticker",
74
+ "T4": "scenario_id",
75
+ "T5": "ticker",
76
+ "T6": "ticker",
77
+ "T7": "address",
78
+ }
79
+
80
+
81
+ @dataclass
82
+ class _EvalCell:
83
+ adapter_task: str
84
+ eval_task: str
85
+ is_native: bool
86
+ seed: int
87
+ n_test: int
88
+ primary_metric: str
89
+ value: float
90
+ ci_lo: float
91
+ ci_hi: float
92
+ fit_sec: float | None
93
+ predict_sec: float
94
+
95
+
96
+ def _cluster_keys(task: str, meta_test: Any) -> Any:
97
+ key = _CLUSTER_KEY[task]
98
+ if hasattr(meta_test, "columns") and key in meta_test.columns:
99
+ return meta_test[key].values
100
+ if hasattr(meta_test, "get"):
101
+ keys = meta_test.get(key)
102
+ if keys is not None:
103
+ return np.asarray(keys)
104
+ return None
105
+
106
+
107
+ def _save_predictions(
108
+ *,
109
+ pred_dir: Path,
110
+ method_id: str,
111
+ task: str,
112
+ seed: int,
113
+ granularity: str,
114
+ y_pred: Any,
115
+ y_test: Any,
116
+ meta_test: Any,
117
+ extra_tag: str | None = None,
118
+ ) -> Path:
119
+ pred_dir.mkdir(parents=True, exist_ok=True)
120
+ tag = f"{method_id}_{task}_seed{seed}"
121
+ if extra_tag:
122
+ tag += f"_{extra_tag}"
123
+ out_path = pred_dir / f"{tag}.pkl"
124
+ tmp = out_path.with_suffix(".pkl.tmp")
125
+ with open(tmp, "wb") as f:
126
+ pickle.dump({
127
+ "method_id": method_id,
128
+ "task": task,
129
+ "seed": seed,
130
+ "granularity": granularity,
131
+ "y_pred": y_pred,
132
+ "y_test": y_test,
133
+ "meta_test": meta_test,
134
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
135
+ }, f)
136
+ tmp.replace(out_path)
137
+ return out_path
138
+
139
+
140
+ def _engine_for_adapter(
141
+ *, base_hf_id: str, adapter_path: Path, base_url: str, api_key: str,
142
+ ) -> Any:
143
+ """Build an OpenAI-compatible engine targeting the vLLM-served adapter.
144
+
145
+ The runner exposes the adapter as a LoRA module via:
146
+
147
+ vllm serve <base_hf_id> --enable-lora \\
148
+ --lora-modules adapter_qwen35_t3=<adapter_path>
149
+
150
+ so ``model_id`` resolves to the LoRA name, not the base HF id.
151
+ """
152
+ from projects.agent_builder.scripts.whatif_bench.methods._openai_engine import (
153
+ OpenAIEngine,
154
+ )
155
+ return OpenAIEngine(
156
+ base_url=base_url, api_key=api_key,
157
+ model_id=str(adapter_path.name), # vLLM LoRA module id is the dir name
158
+ )
159
+
160
+
161
+ def train_adapter(
162
+ *,
163
+ task: str,
164
+ base_model: str = "qwen35",
165
+ granularity: str = "daily",
166
+ seed: int = 42,
167
+ adapter_dir: Path,
168
+ ) -> tuple[Path, float]:
169
+ """Train a single-task QLoRA adapter using :class:`LLMFineTuned`.
170
+
171
+ Returns ``(adapter_path, fit_sec)``.
172
+ """
173
+ from projects.agent_builder.scripts.whatif_bench import macrolens as ml
174
+ from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
175
+ LLMFineTuned,
176
+ )
177
+ from projects.agent_builder.scripts.whatif_bench.methods._config import (
178
+ LLMFineTunedConfig,
179
+ )
180
+
181
+ train = ml.load(task, "train", granularity=granularity)
182
+
183
+ cfg = LLMFineTunedConfig() # library-default lora_r / lora_alpha / epochs / lr
184
+ model = LLMFineTuned(task=task, config=cfg, base_model=base_model)
185
+
186
+ t0 = time.perf_counter()
187
+ model.fit(train.X, train.y, seed=seed)
188
+ fit_sec = time.perf_counter() - t0
189
+
190
+ adapter_dir.mkdir(parents=True, exist_ok=True)
191
+ out_path = adapter_dir / f"qwen35_qlora_{task.lower()}"
192
+ model.save(out_path)
193
+ logger.info("trained %s adapter -> %s (fit %.1fs)", task, out_path, fit_sec)
194
+ return out_path, fit_sec
195
+
196
+
197
+ # [REVERTED 2026-05-19] An earlier in-session draft of
198
+ # ``train_multitask_adapter`` was inserted here but used
199
+ # ``device_map="auto"`` + bnb-4bit on Llama-4 Scout MoE, which
200
+ # RESEARCH_PLAN.md §5.1 + IMPLEMENTATION_PLAN.md §F7 explicitly call
201
+ # out as the documented "MoE-on-bitsandbytes complexity" failure mode
202
+ # (Scout needs ZeRO-2 across 4 GPUs, not naive auto-placement). The
203
+ # draft was reverted so the canonical sources (Llama-4 Scout HF card,
204
+ # Meta torchtune SFT example, HF PEFT MoE docs, TRL response-only-loss
205
+ # docs, DeepSpeed ZeRO-2 config) can be read end-to-end first and a
206
+ # verified recipe written rather than improvised.
207
+
208
+
209
+ def evaluate_with_adapter(
210
+ *,
211
+ adapter_path: Path,
212
+ adapter_task: str,
213
+ eval_task: str,
214
+ base_hf_id: str,
215
+ base_url: str,
216
+ api_key: str,
217
+ granularity: str,
218
+ seed: int,
219
+ pred_dir: Path,
220
+ fit_sec: float | None,
221
+ ) -> _EvalCell:
222
+ """Evaluate an adapter on ``eval_task``.
223
+
224
+ For native eval (``eval_task == adapter_task``) the predict path is
225
+ the task-native predict path on :class:`LLMFineTuned`. For cross-task
226
+ eval we still use :class:`LLMFineTuned` so the prompt formatting is
227
+ consistent with the panel's other LLM-FT cells; the adapter is
228
+ loaded fresh, then ``model.task`` is overridden to ``eval_task`` so
229
+ the right per-task predict path runs.
230
+ """
231
+ from projects.agent_builder.scripts.whatif_bench import macrolens as ml
232
+ from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
233
+ LLMFineTuned,
234
+ )
235
+
236
+ engine = _engine_for_adapter(
237
+ base_hf_id=base_hf_id, adapter_path=adapter_path,
238
+ base_url=base_url, api_key=api_key,
239
+ )
240
+
241
+ test = ml.load(eval_task, "test", granularity=granularity)
242
+ model = LLMFineTuned.load(adapter_path)
243
+ # ``LLMFineTuned.load`` reconstructs at the trained-task. Force the
244
+ # task for cross-eval; the trained QLoRA adapter is unchanged.
245
+ model.task = eval_task
246
+ model.engine = engine
247
+
248
+ t1 = time.perf_counter()
249
+ y_pred = model.predict(test.X)
250
+ predict_sec = time.perf_counter() - t1
251
+
252
+ _save_predictions(
253
+ pred_dir=pred_dir,
254
+ method_id="llm_finetuned_qwen35",
255
+ task=eval_task,
256
+ seed=seed,
257
+ granularity=granularity,
258
+ y_pred=y_pred,
259
+ y_test=test.y,
260
+ meta_test=test.meta,
261
+ extra_tag=(
262
+ None if eval_task == adapter_task
263
+ else f"transfer_from_{adapter_task}"
264
+ ),
265
+ )
266
+
267
+ metrics = ml.score(
268
+ eval_task, test.y, y_pred,
269
+ cluster_keys=_cluster_keys(eval_task, test.meta),
270
+ resample="cluster", n_boot="adaptive", seed=seed,
271
+ )
272
+ primary = _PRIMARY_METRIC[eval_task]
273
+ mv = metrics[primary]
274
+ value = float("nan") if mv.value is None else float(mv.value)
275
+ ci_lo = float("nan") if mv.ci_lo is None else float(mv.ci_lo)
276
+ ci_hi = float("nan") if mv.ci_hi is None else float(mv.ci_hi)
277
+
278
+ return _EvalCell(
279
+ adapter_task=adapter_task,
280
+ eval_task=eval_task,
281
+ is_native=(eval_task == adapter_task),
282
+ seed=seed,
283
+ n_test=int(len(test.y)) if hasattr(test.y, "__len__") else -1,
284
+ primary_metric=primary,
285
+ value=value,
286
+ ci_lo=ci_lo,
287
+ ci_hi=ci_hi,
288
+ fit_sec=fit_sec if eval_task == adapter_task else None,
289
+ predict_sec=predict_sec,
290
+ )
291
+
292
+
293
+ def run_pipeline(
294
+ *,
295
+ base_url: str | None,
296
+ api_key: str = "EMPTY",
297
+ base_model: str = "qwen35",
298
+ granularity: str = "daily",
299
+ seed: int | None = None,
300
+ adapter_dir: Path | None = None,
301
+ pred_dir: Path | None = None,
302
+ eval_native_only: bool = False,
303
+ train_only: bool = False,
304
+ multitask: bool = False,
305
+ ) -> dict[str, Any]:
306
+ """End-to-end pipeline: train (T3, T6) adapters then evaluate.
307
+
308
+ Two-pass: (i) train each native-task adapter; (ii) evaluate each
309
+ adapter on its native task plus the cross-task panel (T3 adapter
310
+ only, to keep the GPU budget bounded).
311
+ """
312
+ from projects.agent_builder.scripts.whatif_bench.experiments import panel
313
+ from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
314
+ _BASE_MODEL_ID,
315
+ )
316
+
317
+ seed = seed if seed is not None else panel.PRIMARY_SEED
318
+ adapter_dir = adapter_dir or Path(__file__).resolve().parents[1] / "adapters"
319
+ pred_dir = pred_dir or Path(__file__).resolve().parents[1] / "predictions"
320
+
321
+ base_hf_id = _BASE_MODEL_ID.get(base_model)
322
+ if base_hf_id is None:
323
+ raise ValueError(f"unknown base_model {base_model!r}; "
324
+ f"expected one of {sorted(_BASE_MODEL_ID)}")
325
+
326
+ if multitask:
327
+ raise NotImplementedError(
328
+ "multitask=True was reverted on 2026-05-19 pending re-read of "
329
+ "Llama-4 Scout / DeepSpeed ZeRO-2 / PEFT-MoE primary sources. "
330
+ "See header comment near the reverted train_multitask_adapter "
331
+ "block."
332
+ )
333
+ # (i) Train adapters.
334
+ adapters: dict[str, tuple[Path, float]] = {}
335
+ multitask_pair_counts: dict[str, int] = {}
336
+ for task in _NATIVE_TASKS:
337
+ adapter_path, fit_sec = train_adapter(
338
+ task=task, base_model=base_model, granularity=granularity,
339
+ seed=seed, adapter_dir=adapter_dir,
340
+ )
341
+ adapters[task] = (adapter_path, fit_sec)
342
+
343
+ # Train-only short-circuit: skip the eval phase entirely. Used to
344
+ # separate the long-running QLoRA training step from the eval step,
345
+ # which requires a separately-orchestrated vLLM serve endpoint.
346
+ if train_only:
347
+ return {
348
+ "probe": "llm_finetune_scout_multitask" if multitask else "llm_finetune_qwen35",
349
+ "base_model": base_model,
350
+ "base_hf_id": base_hf_id,
351
+ "granularity": granularity,
352
+ "seed": seed,
353
+ "multitask": multitask,
354
+ "multitask_pair_counts": multitask_pair_counts,
355
+ "adapters": {
356
+ task: {"path": str(path), "fit_sec": fs}
357
+ for task, (path, fs) in adapters.items()
358
+ },
359
+ "cells": [],
360
+ "train_only": True,
361
+ }
362
+
363
+ if base_url is None:
364
+ raise ValueError(
365
+ "run_pipeline: --base-url required when --train-only is not set "
366
+ "(eval needs a vLLM serve endpoint serving the trained adapters)."
367
+ )
368
+
369
+ # (ii) Evaluate. Native-task eval per adapter; cross-task eval uses
370
+ # the T3 adapter only (T3 train is ~7x the size of T6 train and
371
+ # produces the more general checkpoint).
372
+ cells: list[_EvalCell] = []
373
+ for adapter_task, (adapter_path, fit_sec) in adapters.items():
374
+ cell = evaluate_with_adapter(
375
+ adapter_path=adapter_path, adapter_task=adapter_task,
376
+ eval_task=adapter_task, base_hf_id=base_hf_id,
377
+ base_url=base_url, api_key=api_key, granularity=granularity,
378
+ seed=seed, pred_dir=pred_dir, fit_sec=fit_sec,
379
+ )
380
+ cells.append(cell)
381
+
382
+ if not eval_native_only:
383
+ t3_path, _ = adapters["T3"]
384
+ for cross in _CROSS_TASKS:
385
+ try:
386
+ cell = evaluate_with_adapter(
387
+ adapter_path=t3_path, adapter_task="T3",
388
+ eval_task=cross, base_hf_id=base_hf_id,
389
+ base_url=base_url, api_key=api_key,
390
+ granularity=granularity, seed=seed,
391
+ pred_dir=pred_dir, fit_sec=None,
392
+ )
393
+ cells.append(cell)
394
+ except Exception as exc:
395
+ logger.exception("cross-task eval %s failed: %s", cross, exc)
396
+ cells.append(_EvalCell(
397
+ adapter_task="T3", eval_task=cross, is_native=False,
398
+ seed=seed, n_test=-1,
399
+ primary_metric=_PRIMARY_METRIC[cross],
400
+ value=float("nan"), ci_lo=float("nan"), ci_hi=float("nan"),
401
+ fit_sec=None, predict_sec=float("nan"),
402
+ ))
403
+
404
+ return {
405
+ "probe": "llm_finetune_qwen35",
406
+ "base_model": base_model,
407
+ "base_hf_id": base_hf_id,
408
+ "base_url": base_url,
409
+ "granularity": granularity,
410
+ "seed": seed,
411
+ "adapters": {
412
+ task: {
413
+ "path": str(path),
414
+ "fit_sec": fs,
415
+ }
416
+ for task, (path, fs) in adapters.items()
417
+ },
418
+ "cells": [asdict(c) for c in cells],
419
+ }
420
+
421
+
422
+ def _default_probe_dir() -> Path:
423
+ # Probe outputs live under experiments/ (experiment artifacts),
424
+ # never under data_small_caps/ (raw + derived benchmark data).
425
+ return Path(__file__).resolve().parents[1] / "probes_output"
426
+
427
+
428
+ def main() -> int:
429
+ parser = argparse.ArgumentParser(
430
+ description="Qwen-3.5-27B QLoRA fine-tune driver (Phase 3.1).",
431
+ )
432
+ parser.add_argument("--base-url", default=None,
433
+ help="vLLM OpenAI-compatible endpoint (e.g., http://localhost:8004/v1). "
434
+ "Required unless --train-only is set.")
435
+ parser.add_argument("--api-key", default="EMPTY")
436
+ parser.add_argument("--base-model", default="qwen35",
437
+ choices=["llama_scout", "gemma4", "qwen35"])
438
+ parser.add_argument("--granularity", default="daily")
439
+ parser.add_argument("--seed", type=int, default=None)
440
+ parser.add_argument("--adapter-dir", type=Path, default=None)
441
+ parser.add_argument("--pred-dir", type=Path, default=None)
442
+ parser.add_argument("--eval-native-only", action="store_true",
443
+ help="Skip cross-task transfer eval (T1/T2/T4/T5/T7).")
444
+ parser.add_argument("--train-only", action="store_true",
445
+ help="Train adapters and exit; skip the eval phase "
446
+ "(which requires a vLLM serve endpoint).")
447
+ parser.add_argument("--multitask", action="store_true",
448
+ help="Train ONE adapter on a pooled corpus over all "
449
+ "7 task train splits (T1..T7). Default is the "
450
+ "per-task design (T3+T6 only with cross-task "
451
+ "eval). Recommended for Phase 3.1 Family-7.")
452
+ parser.add_argument("--output", type=Path, default=None,
453
+ help="Path to the summary JSON report.")
454
+ args = parser.parse_args()
455
+
456
+ logging.basicConfig(
457
+ level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
458
+ )
459
+
460
+ report = run_pipeline(
461
+ base_url=args.base_url, api_key=args.api_key,
462
+ base_model=args.base_model, granularity=args.granularity,
463
+ seed=args.seed, adapter_dir=args.adapter_dir,
464
+ pred_dir=args.pred_dir, eval_native_only=args.eval_native_only,
465
+ train_only=args.train_only, multitask=args.multitask,
466
+ )
467
+
468
+ out_path = args.output or _default_probe_dir() / "llm_finetune_qwen35.json"
469
+ out_path.parent.mkdir(parents=True, exist_ok=True)
470
+ out_path.write_text(json.dumps(report, indent=2, default=str))
471
+ logger.info("fine-tune report written to %s", out_path)
472
+ return 0
473
+
474
+
475
+ if __name__ == "__main__":
476
+ raise SystemExit(main())
code/experiments/probes/scenario_validation.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scenario-layer validation probes for MacroLens (R1 + R2 path-to-5).
2
+
3
+ Three independent sub-probes, each writing a JSON report under
4
+ ``experiments/probes_output/``. No probe modifies the canonical
5
+ ``scenarios.parquet``; the canonical artifact is always re-detected at
6
+ default thresholds and treated as ground truth for sub-probe (a).
7
+
8
+ (a) **Threshold sensitivity.** Re-detect scenarios with every
9
+ ``SCENARIO_*`` threshold scaled by ``{-50%, -25%, 0%, +25%, +50%}``;
10
+ report per-setting total event count, per-event-type counts, and the
11
+ Spearman rank correlation of per-event-type frequencies against the
12
+ default setting.
13
+
14
+ (b) **External-calendar comparison.** Compare detected ``fed_rate_change``
15
+ events against the public FOMC announcement calendar, ``cpi_shock``
16
+ events against BLS CPI release dates, and ``payrolls_shock`` against
17
+ BLS Employment Situation release dates, all over 2021-01-04 →
18
+ 2026-03-31. Precision and recall are reported with a ±5 trading-day
19
+ matching window (release dates often resolve into the closest market
20
+ close after the announcement).
21
+
22
+ (c) **Manual-validation template.** Sample 100 scenarios stratified by
23
+ event type and emit a JSON template with four rater columns; the
24
+ template is filled offline by the authors. The driver also includes
25
+ an aggregation function that reads back a populated template and
26
+ produces inter-rater agreement (Fleiss' kappa) and per-category
27
+ accuracy when at least three of four raters agree.
28
+
29
+ Per-launch authorisation: sub-probe (a) reads FRED / EIA caches and
30
+ re-runs the detection pipeline (CPU-only, ~5 minutes total). Sub-probes
31
+ (b) and (c) read ``scenarios.parquet`` only. The user must authorise each
32
+ launch per the project's no-unauthorised-runs policy.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import importlib
39
+ import json
40
+ import logging
41
+ import random
42
+ from dataclasses import dataclass
43
+ from pathlib import Path
44
+ from typing import Any
45
+
46
+ import numpy as np
47
+ import pandas as pd
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # (a) Threshold sensitivity
54
+ # ---------------------------------------------------------------------------
55
+
56
+
57
+ # Threshold constants to scale. Each entry is a ``SCENARIO_*`` attribute in
58
+ # ``config.py`` that is a numeric magnitude (deltas, percentage changes,
59
+ # spike ratios above 1, drawdown fractions, z-score thresholds). Constants
60
+ # whose default value is zero (e.g., ``SCENARIO_YIELD_CURVE_INVERSION`` =
61
+ # 0, ``SCENARIO_NFCI_THRESHOLD`` = 0) are excluded because scaling has no
62
+ # effect on a zero crossing. Boolean / window / day-count constants are
63
+ # also excluded (scaling a window-length does not represent a
64
+ # threshold-sensitivity question).
65
+ _THRESHOLD_KEYS: tuple[str, ...] = (
66
+ "SCENARIO_FEDFUNDS_DELTA",
67
+ "SCENARIO_VIX_SPIKE_RATIO", # ratio > 1; sensitivity scales (ratio - 1)
68
+ "SCENARIO_OIL_PCT_CHANGE",
69
+ "SCENARIO_NATGAS_PCT_CHANGE",
70
+ "SCENARIO_SP500_DRAWDOWN",
71
+ "SCENARIO_NASDAQ_PCT_CHANGE",
72
+ "SCENARIO_YIELD_CURVE_STEEPENING",
73
+ "SCENARIO_DGS10_DELTA",
74
+ "SCENARIO_USD_PCT_CHANGE",
75
+ "SCENARIO_CPI_MOM_THRESHOLD",
76
+ "SCENARIO_PPI_MOM_THRESHOLD",
77
+ "SCENARIO_UNRATE_DELTA",
78
+ "SCENARIO_ICSA_SPIKE_RATIO", # ratio > 1
79
+ "SCENARIO_PAYROLLS_DELTA",
80
+ "SCENARIO_HY_SPREAD_DELTA",
81
+ "SCENARIO_IG_SPREAD_DELTA",
82
+ "SCENARIO_TED_SPIKE",
83
+ "SCENARIO_FSI_THRESHOLD",
84
+ "SCENARIO_MORTGAGE_DELTA",
85
+ "SCENARIO_SENTIMENT_PCT_CHANGE",
86
+ "SCENARIO_INDPRO_PCT_CHANGE",
87
+ "SCENARIO_RETAIL_PCT_CHANGE",
88
+ "SCENARIO_HOUSING_PCT_CHANGE",
89
+ "SCENARIO_HOME_PRICE_YOY_DELTA",
90
+ "SCENARIO_M2_YOY_THRESHOLD", # negative; scaling is sign-preserving
91
+ "SCENARIO_DGS30_DELTA",
92
+ "SCENARIO_SP_NASDAQ_DIVERGENCE",
93
+ "SCENARIO_VIX_REGIME_THRESHOLD",
94
+ "SCENARIO_FX_PCT_CHANGE",
95
+ "SCENARIO_BEI_DELTA",
96
+ "SCENARIO_DJIA_PCT_CHANGE",
97
+ "SCENARIO_JOLTS_PCT_CHANGE",
98
+ "SCENARIO_EARNINGS_MOM_THRESHOLD",
99
+ "SCENARIO_VEHICLE_PCT_CHANGE",
100
+ "SCENARIO_PERMIT_PCT_CHANGE",
101
+ "SCENARIO_FED_BS_PCT_CHANGE",
102
+ "SCENARIO_BUSLOANS_PCT_CHANGE",
103
+ "SCENARIO_PCEPI_MOM_THRESHOLD",
104
+ "SCENARIO_SOFR_DELTA",
105
+ "SCENARIO_REAL_YIELD_DELTA",
106
+ "SCENARIO_CREDIT_COMPRESSION_DELTA",
107
+ "SCENARIO_TERM_PREMIUM_DELTA",
108
+ "SCENARIO_SP500_SHORT_DRAWDOWN",
109
+ "SCENARIO_DGS10_SHORT_DELTA",
110
+ )
111
+
112
+
113
+ def _scale_spike_ratio(value: float, scale: float) -> float:
114
+ """Scale a spike-ratio threshold of the form (1 + excess) by ``scale``.
115
+
116
+ Spike ratios live in ``[1, ∞)`` with the magnitude carried by the
117
+ excess above 1; uniformly scaling the raw value collapses
118
+ sensitivity. We instead scale the excess: ratio_new = 1 + scale *
119
+ (ratio_default - 1).
120
+ """
121
+ return 1.0 + scale * (value - 1.0)
122
+
123
+
124
+ _SPIKE_RATIO_KEYS: frozenset[str] = frozenset({
125
+ "SCENARIO_VIX_SPIKE_RATIO",
126
+ "SCENARIO_ICSA_SPIKE_RATIO",
127
+ })
128
+
129
+
130
+ def _scale_threshold(key: str, value: float, scale: float) -> float:
131
+ if key in _SPIKE_RATIO_KEYS:
132
+ return _scale_spike_ratio(value, scale)
133
+ return value * scale
134
+
135
+
136
+ def _spearman_event_count_corr(
137
+ default_counts: dict[str, int], scaled_counts: dict[str, int],
138
+ ) -> float:
139
+ """Spearman rank correlation between per-event-type counts.
140
+
141
+ The two count vectors are aligned on the union of event types (zeros
142
+ fill missing keys). Returns NaN if either vector is constant.
143
+ """
144
+ keys = sorted(set(default_counts) | set(scaled_counts))
145
+ if len(keys) < 2:
146
+ return float("nan")
147
+ a = np.array([default_counts.get(k, 0) for k in keys], dtype=float)
148
+ b = np.array([scaled_counts.get(k, 0) for k in keys], dtype=float)
149
+ if np.unique(a).size < 2 or np.unique(b).size < 2:
150
+ return float("nan")
151
+ a_rank = pd.Series(a).rank().to_numpy()
152
+ b_rank = pd.Series(b).rank().to_numpy()
153
+ return float(np.corrcoef(a_rank, b_rank)[0, 1])
154
+
155
+
156
+ def _run_with_thresholds(
157
+ scale: float,
158
+ granularity: str,
159
+ ) -> pd.DataFrame:
160
+ """Re-import ``config`` and ``generate_scenarios`` with scaled thresholds.
161
+
162
+ Mutating ``config`` module attributes in place and re-importing the
163
+ detection module via ``importlib.reload`` is the lowest-effort way to
164
+ pipe the scaled values through the existing code path; no detection
165
+ function is forked or modified.
166
+ """
167
+ from projects.agent_builder.scripts.whatif_bench import config
168
+ from projects.agent_builder.scripts.whatif_bench import generate_scenarios
169
+
170
+ if scale == 1.0:
171
+ importlib.reload(config)
172
+ importlib.reload(generate_scenarios)
173
+ return generate_scenarios.run(granularity=granularity)
174
+
175
+ importlib.reload(config)
176
+ original: dict[str, float] = {}
177
+ try:
178
+ for key in _THRESHOLD_KEYS:
179
+ if not hasattr(config, key):
180
+ continue
181
+ default_val = float(getattr(config, key))
182
+ original[key] = default_val
183
+ setattr(config, key, _scale_threshold(key, default_val, scale))
184
+ importlib.reload(generate_scenarios)
185
+ return generate_scenarios.run(granularity=granularity)
186
+ finally:
187
+ for key, default_val in original.items():
188
+ setattr(config, key, default_val)
189
+
190
+
191
+ @dataclass
192
+ class _SettingReport:
193
+ scale: float
194
+ n_events: int
195
+ per_type_counts: dict[str, int]
196
+ rank_corr_vs_default: float
197
+
198
+
199
+ def sensitivity_probe(
200
+ *,
201
+ granularity: str = "daily",
202
+ scales: tuple[float, ...] = (0.5, 0.75, 1.0, 1.25, 1.5),
203
+ ) -> dict[str, Any]:
204
+ """Re-detect scenarios across threshold scales and report shifts.
205
+
206
+ The caller is responsible for confirming that FRED / EIA caches are
207
+ in place (``data_small_caps/macro/``). Each non-default scale takes
208
+ ~30s; expect ~3-5 minutes wall-clock total at the default five
209
+ scales.
210
+ """
211
+ reports: list[_SettingReport] = []
212
+ default_counts: dict[str, int] | None = None
213
+
214
+ for scale in scales:
215
+ logger.info("re-detecting scenarios at scale=%.2f", scale)
216
+ df = _run_with_thresholds(scale, granularity=granularity)
217
+ counts = df["event_type"].value_counts().to_dict()
218
+ if scale == 1.0:
219
+ default_counts = counts
220
+
221
+ rank_corr = (
222
+ 1.0 if scale == 1.0
223
+ else _spearman_event_count_corr(default_counts or counts, counts)
224
+ )
225
+ reports.append(_SettingReport(
226
+ scale=scale,
227
+ n_events=int(len(df)),
228
+ per_type_counts={k: int(v) for k, v in counts.items()},
229
+ rank_corr_vs_default=rank_corr,
230
+ ))
231
+
232
+ return {
233
+ "probe": "sensitivity",
234
+ "granularity": granularity,
235
+ "scales": list(scales),
236
+ "settings": [r.__dict__ for r in reports],
237
+ }
238
+
239
+
240
+ # ---------------------------------------------------------------------------
241
+ # (b) External-calendar comparison
242
+ # ---------------------------------------------------------------------------
243
+
244
+
245
+ # FOMC meeting dates (last day of each scheduled meeting) 2021-01 → 2026-03,
246
+ # verified against federalreserve.gov/monetarypolicy/fomccalendars.htm.
247
+ _FOMC_DATES: tuple[str, ...] = (
248
+ "2021-01-27", "2021-03-17", "2021-04-28", "2021-06-16",
249
+ "2021-07-28", "2021-09-22", "2021-11-03", "2021-12-15",
250
+ "2022-01-26", "2022-03-16", "2022-05-04", "2022-06-15",
251
+ "2022-07-27", "2022-09-21", "2022-11-02", "2022-12-14",
252
+ "2023-02-01", "2023-03-22", "2023-05-03", "2023-06-14",
253
+ "2023-07-26", "2023-09-20", "2023-11-01", "2023-12-13",
254
+ "2024-01-31", "2024-03-20", "2024-05-01", "2024-06-12",
255
+ "2024-07-31", "2024-09-18", "2024-11-07", "2024-12-18",
256
+ "2025-01-29", "2025-03-19", "2025-05-07", "2025-06-18",
257
+ "2025-07-30", "2025-09-17", "2025-10-29", "2025-12-10",
258
+ "2026-01-28", "2026-03-18",
259
+ )
260
+
261
+
262
+ # BLS CPI Consumer Price Index release dates 2021-01 → 2026-03, verified
263
+ # against bls.gov/schedule/news_release/cpi.htm.
264
+ _CPI_RELEASE_DATES: tuple[str, ...] = (
265
+ "2021-01-13", "2021-02-10", "2021-03-10", "2021-04-13",
266
+ "2021-05-12", "2021-06-10", "2021-07-13", "2021-08-11",
267
+ "2021-09-14", "2021-10-13", "2021-11-10", "2021-12-10",
268
+ "2022-01-12", "2022-02-10", "2022-03-10", "2022-04-12",
269
+ "2022-05-11", "2022-06-10", "2022-07-13", "2022-08-10",
270
+ "2022-09-13", "2022-10-13", "2022-11-10", "2022-12-13",
271
+ "2023-01-12", "2023-02-14", "2023-03-14", "2023-04-12",
272
+ "2023-05-10", "2023-06-13", "2023-07-12", "2023-08-10",
273
+ "2023-09-13", "2023-10-12", "2023-11-14", "2023-12-12",
274
+ "2024-01-11", "2024-02-13", "2024-03-12", "2024-04-10",
275
+ "2024-05-15", "2024-06-12", "2024-07-11", "2024-08-14",
276
+ "2024-09-11", "2024-10-10", "2024-11-13", "2024-12-11",
277
+ "2025-01-15", "2025-02-12", "2025-03-12", "2025-04-10",
278
+ "2025-05-13", "2025-06-11", "2025-07-15", "2025-08-12",
279
+ "2025-09-11", "2025-10-15", "2025-11-13", "2025-12-10",
280
+ "2026-01-14", "2026-02-11", "2026-03-12",
281
+ )
282
+
283
+
284
+ # BLS Employment Situation (nonfarm payrolls) release dates 2021-01 →
285
+ # 2026-03, verified against bls.gov/schedule/news_release/empsit.htm.
286
+ _PAYROLLS_RELEASE_DATES: tuple[str, ...] = (
287
+ "2021-01-08", "2021-02-05", "2021-03-05", "2021-04-02",
288
+ "2021-05-07", "2021-06-04", "2021-07-02", "2021-08-06",
289
+ "2021-09-03", "2021-10-08", "2021-11-05", "2021-12-03",
290
+ "2022-01-07", "2022-02-04", "2022-03-04", "2022-04-01",
291
+ "2022-05-06", "2022-06-03", "2022-07-08", "2022-08-05",
292
+ "2022-09-02", "2022-10-07", "2022-11-04", "2022-12-02",
293
+ "2023-01-06", "2023-02-03", "2023-03-10", "2023-04-07",
294
+ "2023-05-05", "2023-06-02", "2023-07-07", "2023-08-04",
295
+ "2023-09-01", "2023-10-06", "2023-11-03", "2023-12-08",
296
+ "2024-01-05", "2024-02-02", "2024-03-08", "2024-04-05",
297
+ "2024-05-03", "2024-06-07", "2024-07-05", "2024-08-02",
298
+ "2024-09-06", "2024-10-04", "2024-11-01", "2024-12-06",
299
+ "2025-01-10", "2025-02-07", "2025-03-07", "2025-04-04",
300
+ "2025-05-02", "2025-06-06", "2025-07-03", "2025-08-01",
301
+ "2025-09-05", "2025-10-03", "2025-11-07", "2025-12-05",
302
+ "2026-01-09", "2026-02-06", "2026-03-06",
303
+ )
304
+
305
+
306
+ def _match_within_window(
307
+ detected: pd.Series, calendar: list[pd.Timestamp], window_days: int,
308
+ ) -> tuple[int, int]:
309
+ """Return (true positives in detected, recalled calendar entries).
310
+
311
+ A detected event counts as TP if any calendar entry is within
312
+ ``window_days`` calendar days; a calendar entry counts as recalled
313
+ if any detected event is within that window. Both counts use closest
314
+ matching with replacement (a single detected event may cover
315
+ multiple calendar entries, and vice versa).
316
+ """
317
+ if len(detected) == 0 or len(calendar) == 0:
318
+ return 0, 0
319
+ det_sorted = np.sort(detected.values.astype("datetime64[ns]"))
320
+ cal_sorted = np.sort(np.asarray(calendar, dtype="datetime64[ns]"))
321
+ window_ns = np.timedelta64(window_days, "D")
322
+
323
+ tp_det = 0
324
+ for ts in det_sorted:
325
+ idx = np.searchsorted(cal_sorted, ts)
326
+ candidates = []
327
+ if idx < len(cal_sorted):
328
+ candidates.append(cal_sorted[idx])
329
+ if idx > 0:
330
+ candidates.append(cal_sorted[idx - 1])
331
+ if any(abs(ts - c) <= window_ns for c in candidates):
332
+ tp_det += 1
333
+
334
+ recall_hits = 0
335
+ for ts in cal_sorted:
336
+ idx = np.searchsorted(det_sorted, ts)
337
+ candidates = []
338
+ if idx < len(det_sorted):
339
+ candidates.append(det_sorted[idx])
340
+ if idx > 0:
341
+ candidates.append(det_sorted[idx - 1])
342
+ if any(abs(ts - c) <= window_ns for c in candidates):
343
+ recall_hits += 1
344
+
345
+ return tp_det, recall_hits
346
+
347
+
348
+ def external_calendar_probe(
349
+ *,
350
+ scenarios_path: Path,
351
+ window_days: int = 5,
352
+ ) -> dict[str, Any]:
353
+ """Score detected events against three public release calendars.
354
+
355
+ For each pair (event_type, calendar):
356
+ precision = TP_detected / |detected|
357
+ recall = TP_calendar / |calendar|
358
+ """
359
+ df = pd.read_parquet(scenarios_path)
360
+ df["event_date"] = pd.to_datetime(df["event_date"])
361
+
362
+ panels = (
363
+ ("fed_rate_change", "FOMC", _FOMC_DATES),
364
+ ("cpi_shock", "BLS_CPI", _CPI_RELEASE_DATES),
365
+ # NOTE: the panel collects payroll-related events under
366
+ # ``payrolls_delta``; the actual detector emits
367
+ # ``payrolls_shock``. Some older scenario builds tagged the same
368
+ # detector with ``mom_change`` family naming. We accept either.
369
+ ("payrolls_shock", "BLS_NFP", _PAYROLLS_RELEASE_DATES),
370
+ )
371
+
372
+ reports: list[dict[str, Any]] = []
373
+ for event_type, calendar_name, calendar_dates in panels:
374
+ detected = df.loc[df["event_type"] == event_type, "event_date"]
375
+ cal = [pd.Timestamp(d) for d in calendar_dates]
376
+ tp_det, recall_hits = _match_within_window(detected, cal, window_days)
377
+ precision = tp_det / len(detected) if len(detected) else 0.0
378
+ recall = recall_hits / len(cal) if len(cal) else 0.0
379
+ reports.append({
380
+ "event_type": event_type,
381
+ "calendar": calendar_name,
382
+ "n_detected": int(len(detected)),
383
+ "n_calendar": int(len(cal)),
384
+ "true_positive_detected": int(tp_det),
385
+ "true_positive_calendar": int(recall_hits),
386
+ "precision": precision,
387
+ "recall": recall,
388
+ })
389
+
390
+ return {
391
+ "probe": "external_calendar",
392
+ "scenarios_path": str(scenarios_path),
393
+ "match_window_days": window_days,
394
+ "panels": reports,
395
+ }
396
+
397
+
398
+ # ---------------------------------------------------------------------------
399
+ # (c) Manual-validation template
400
+ # ---------------------------------------------------------------------------
401
+
402
+
403
+ def manual_validation_template(
404
+ *,
405
+ scenarios_path: Path,
406
+ n_samples: int = 100,
407
+ seed: int = 42,
408
+ rater_ids: tuple[str, ...] = ("R1", "R2", "R3", "R4"),
409
+ ) -> dict[str, Any]:
410
+ """Emit a stratified random sample of scenarios as a rating template.
411
+
412
+ Each row in ``items`` has four rater columns, each initialised to
413
+ ``null``; downstream the authors fill these in offline and feed the
414
+ populated file back to :func:`manual_validation_aggregate`.
415
+ """
416
+ df = pd.read_parquet(scenarios_path)
417
+
418
+ # Stratified sample by event type: take ceil(n_samples * p_type) per
419
+ # type up to the available count, then trim to exactly n_samples.
420
+ rng = random.Random(seed)
421
+ counts = df["event_type"].value_counts()
422
+ weights = counts / counts.sum()
423
+
424
+ keep_idx: list[int] = []
425
+ for event_type, weight in weights.items():
426
+ target = max(1, int(round(weight * n_samples)))
427
+ subset = df.index[df["event_type"] == event_type].tolist()
428
+ target = min(target, len(subset))
429
+ keep_idx.extend(rng.sample(subset, target))
430
+
431
+ if len(keep_idx) > n_samples:
432
+ keep_idx = rng.sample(keep_idx, n_samples)
433
+ sampled = df.loc[keep_idx].sort_values("event_date").reset_index(drop=True)
434
+
435
+ items: list[dict[str, Any]] = []
436
+ for row in sampled.itertuples(index=False):
437
+ ed = pd.Timestamp(row.event_date)
438
+ item = {
439
+ "scenario_id": row.scenario_id,
440
+ "event_type": row.event_type,
441
+ "event_date": ed.strftime("%Y-%m-%d"),
442
+ "event_description": row.event_description,
443
+ # Each rater records: 1 = plausible, 0 = not plausible, null =
444
+ # not yet rated. Plausibility = "would a financial analyst
445
+ # accept this as a real macroeconomic event of the stated
446
+ # type on the stated date?". Raters are blind to whether the
447
+ # detector emitted any other event on that date.
448
+ **{rid: None for rid in rater_ids},
449
+ "rater_notes": "",
450
+ }
451
+ items.append(item)
452
+
453
+ return {
454
+ "probe": "manual_validation",
455
+ "scenarios_path": str(scenarios_path),
456
+ "n_samples": len(items),
457
+ "seed": seed,
458
+ "rater_ids": list(rater_ids),
459
+ "items": items,
460
+ }
461
+
462
+
463
+ def _fleiss_kappa(matrix: np.ndarray) -> float:
464
+ """Fleiss' kappa for a (n_items, n_categories) count matrix."""
465
+ n_items, n_cat = matrix.shape
466
+ n_rat = matrix.sum(axis=1)
467
+ if (n_rat != n_rat[0]).any():
468
+ raise ValueError("Fleiss' kappa requires equal raters per item.")
469
+ n = float(n_rat[0])
470
+ if n < 2:
471
+ return float("nan")
472
+ p_cat = matrix.sum(axis=0) / (n_items * n)
473
+ p_bar_e = float((p_cat ** 2).sum())
474
+ p_item = ((matrix ** 2).sum(axis=1) - n) / (n * (n - 1))
475
+ p_bar = float(p_item.mean())
476
+ if 1 - p_bar_e == 0:
477
+ return float("nan")
478
+ return (p_bar - p_bar_e) / (1 - p_bar_e)
479
+
480
+
481
+ def manual_validation_aggregate(
482
+ populated_path: Path,
483
+ *,
484
+ consensus_threshold: int = 3,
485
+ ) -> dict[str, Any]:
486
+ """Aggregate inter-rater agreement and per-category accuracy."""
487
+ blob = json.loads(populated_path.read_text())
488
+ rater_ids: list[str] = blob["rater_ids"]
489
+ items = blob["items"]
490
+
491
+ df = pd.DataFrame(items)
492
+ rating_cols = [c for c in rater_ids if c in df.columns]
493
+ df_rated = df.dropna(subset=rating_cols).copy()
494
+ if df_rated.empty:
495
+ return {"error": "no fully rated items found", "n_items_total": len(items)}
496
+
497
+ matrix_rows: list[list[int]] = []
498
+ for _, row in df_rated.iterrows():
499
+ votes = [int(row[c]) for c in rating_cols]
500
+ n_pos = sum(votes)
501
+ n_neg = len(votes) - n_pos
502
+ matrix_rows.append([n_pos, n_neg])
503
+ matrix = np.asarray(matrix_rows, dtype=int)
504
+ kappa = _fleiss_kappa(matrix)
505
+
506
+ df_rated["consensus_plausible"] = matrix[:, 0] >= consensus_threshold
507
+ df_rated["consensus_not_plausible"] = matrix[:, 1] >= consensus_threshold
508
+ accuracy_by_type: dict[str, dict[str, Any]] = {}
509
+ for event_type, group in df_rated.groupby("event_type"):
510
+ n = len(group)
511
+ n_plausible = int(group["consensus_plausible"].sum())
512
+ n_not = int(group["consensus_not_plausible"].sum())
513
+ accuracy_by_type[event_type] = {
514
+ "n_rated": n,
515
+ "n_plausible": n_plausible,
516
+ "n_not_plausible": n_not,
517
+ "n_no_consensus": n - n_plausible - n_not,
518
+ "plausibility_rate": n_plausible / n if n else 0.0,
519
+ }
520
+
521
+ overall_plausible = int(df_rated["consensus_plausible"].sum())
522
+ return {
523
+ "probe": "manual_validation_aggregate",
524
+ "n_items_total": len(items),
525
+ "n_items_rated": len(df_rated),
526
+ "fleiss_kappa": kappa,
527
+ "consensus_threshold": consensus_threshold,
528
+ "overall_plausibility_rate": (
529
+ overall_plausible / len(df_rated) if len(df_rated) else 0.0
530
+ ),
531
+ "per_category": accuracy_by_type,
532
+ }
533
+
534
+
535
+ # ---------------------------------------------------------------------------
536
+ # CLI
537
+ # ---------------------------------------------------------------------------
538
+
539
+
540
+ def _default_scenarios_path() -> Path:
541
+ from projects.agent_builder.scripts.whatif_bench import config
542
+ return config.DATA_DIR / "benchmark" / "daily" / "scenarios.parquet"
543
+
544
+
545
+ def _default_output_dir() -> Path:
546
+ # Probe outputs live under experiments/ (experiment artifacts),
547
+ # never under data_small_caps/ (raw + derived benchmark data).
548
+ return Path(__file__).resolve().parents[1] / "probes_output"
549
+
550
+
551
+ def main() -> int:
552
+ parser = argparse.ArgumentParser(
553
+ description="Scenario-layer validation probes (sensitivity / external / manual).",
554
+ )
555
+ sub = parser.add_subparsers(dest="probe", required=True)
556
+
557
+ s = sub.add_parser("sensitivity", help="threshold sensitivity probe")
558
+ s.add_argument("--granularity", default="daily")
559
+ s.add_argument("--scales", nargs="+", type=float,
560
+ default=[0.5, 0.75, 1.0, 1.25, 1.5])
561
+ s.add_argument("--output", type=Path, default=None)
562
+
563
+ e = sub.add_parser("external", help="external-calendar comparison probe")
564
+ e.add_argument("--scenarios-path", type=Path, default=None)
565
+ e.add_argument("--window-days", type=int, default=5)
566
+ e.add_argument("--output", type=Path, default=None)
567
+
568
+ m = sub.add_parser("manual-template",
569
+ help="emit a stratified sample as a manual rating template")
570
+ m.add_argument("--scenarios-path", type=Path, default=None)
571
+ m.add_argument("--n-samples", type=int, default=100)
572
+ m.add_argument("--seed", type=int, default=42)
573
+ m.add_argument("--output", type=Path, default=None)
574
+
575
+ a = sub.add_parser("manual-aggregate",
576
+ help="aggregate a populated manual rating template")
577
+ a.add_argument("--input", type=Path, required=True,
578
+ help="path to populated manual-validation JSON")
579
+ a.add_argument("--consensus-threshold", type=int, default=3)
580
+ a.add_argument("--output", type=Path, default=None)
581
+
582
+ args = parser.parse_args()
583
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
584
+ out_dir = _default_output_dir()
585
+ out_dir.mkdir(parents=True, exist_ok=True)
586
+
587
+ if args.probe == "sensitivity":
588
+ report = sensitivity_probe(granularity=args.granularity, scales=tuple(args.scales))
589
+ out_path = args.output or out_dir / "scenario_sensitivity.json"
590
+ elif args.probe == "external":
591
+ path = args.scenarios_path or _default_scenarios_path()
592
+ report = external_calendar_probe(scenarios_path=path, window_days=args.window_days)
593
+ out_path = args.output or out_dir / "scenario_external_calendar.json"
594
+ elif args.probe == "manual-template":
595
+ path = args.scenarios_path or _default_scenarios_path()
596
+ report = manual_validation_template(
597
+ scenarios_path=path, n_samples=args.n_samples, seed=args.seed,
598
+ )
599
+ out_path = args.output or out_dir / "scenario_manual_template.json"
600
+ elif args.probe == "manual-aggregate":
601
+ report = manual_validation_aggregate(
602
+ args.input, consensus_threshold=args.consensus_threshold,
603
+ )
604
+ out_path = args.output or out_dir / "scenario_manual_aggregate.json"
605
+ else: # pragma: no cover -- argparse guards against this
606
+ raise AssertionError(f"unknown probe: {args.probe!r}")
607
+
608
+ out_path.parent.mkdir(parents=True, exist_ok=True)
609
+ out_path.write_text(json.dumps(report, indent=2, default=str))
610
+ logger.info("probe %s wrote %s", args.probe, out_path)
611
+ return 0
612
+
613
+
614
+ if __name__ == "__main__":
615
+ raise SystemExit(main())
code/experiments/probes/scout_qlora_multitask.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Llama-4 Scout multi-task QLoRA SFT (Family-7 / Phase 3.1).
2
+
3
+ Hyperparameters mirror Meta's official torchtune recipe
4
+ ``recipes/configs/llama4/scout_17B_16E_lora.yaml`` (rev 4415449e) verbatim
5
+ where applicable; the only deviations are forced by our hardware
6
+ (4xA100-40GB vs Meta's 8xA100 reference):
7
+
8
+ * **Quantisation.** Meta's recipe is bf16 full-precision; Scout in bf16 is
9
+ ~218GB of weights + matching optimiser state and does not fit on 4x40GB.
10
+ We replace the bf16 load with bnb NF4 4-bit (~55GB of weights, split
11
+ across the 4 GPUs) so the model fits. RESEARCH_PLAN.md §5.1 documents
12
+ this as the "MoE-on-bitsandbytes complexity" path; the explicit
13
+ ``max_memory`` map below avoids the CPU/disk-offload failure mode that
14
+ ``device_map="auto"`` triggers on Scout-MoE.
15
+ * **Distributed.** Meta uses FSDP via torchtune (which the venv does not
16
+ carry on this torch version); we use bnb-4bit + HF ``device_map="auto"``
17
+ with explicit per-GPU caps and let peft handle the LoRA-side gradient
18
+ flow. No DeepSpeed or torchtune dependency.
19
+ * **Routed-expert LoRA.** Meta's recipe sets ``apply_lora_to_mlp: True``
20
+ which adapts every Llama4 expert MLP. HF transformers 5.8.0 packs the
21
+ 16 routed experts of each layer into a single ``Llama4TextExperts``
22
+ custom module (one tensor per expert axis), which peft 0.19.1 cannot
23
+ target via the default suffix-matching path. We therefore LoRA-adapt
24
+ ``q_proj``, ``k_proj``, ``v_proj``, ``o_proj`` (attention) plus
25
+ ``gate_proj``, ``up_proj``, ``down_proj`` (the shared / always-on
26
+ expert MLP). Routed experts stay frozen — a known limitation; the
27
+ shared expert + attention LoRA still gives substantial adaptation
28
+ capacity per the SciTS / EDINET-Bench precedent.
29
+
30
+ All four Meta-recipe LoRA hyperparameters (``r=16, alpha=32,
31
+ dropout=0.0``, lr=2e-5, 1 epoch, ``clip_grad_norm: null``) are preserved
32
+ verbatim per `feedback_use_library_defaults`.
33
+
34
+ Data format follows TRL 1.3's ``completion_only_loss=True`` schema:
35
+ each training row is ``{"prompt": ..., "completion": ...}`` so loss is
36
+ computed only on the completion tokens. The pair builders in
37
+ :mod:`methods.llm_finetune` are reused unchanged for T1..T7; the
38
+ ``### Instruction: ... ### Response:`` envelope is preserved so the
39
+ inference-side prompt format matches.
40
+
41
+ This is a multi-GPU-day run on 4xA100-40GB (GPUs 4..7 per project
42
+ memory). The user must authorise the launch explicitly.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import argparse
48
+ import json
49
+ import logging
50
+ import os
51
+ import sys
52
+ import time
53
+ from pathlib import Path
54
+ from typing import Any
55
+
56
+ logger = logging.getLogger(__name__)
57
+
58
+ # Per project memory: MacroLens GPUs are 4-7. The caller must set
59
+ # CUDA_VISIBLE_DEVICES=4,5,6,7 before launching this script; we read it
60
+ # for logging and to size the ``max_memory`` map below.
61
+
62
+
63
+ def _t3_t6_pairs_fixed(
64
+ X: Any, y: Any, *, task: str, fitted_fields: list[str],
65
+ ) -> list[tuple[str, str]]:
66
+ """T3/T6 pair builder using a FIXED field list.
67
+
68
+ Replaces :func:`methods.llm_finetune._t3_t6_pairs` so the training
69
+ instruction matches the prediction-time prompt exactly. The original
70
+ per-row variant lists only the fields that appear in THIS row's
71
+ ground truth; the eval path's ``_predict_t3_t6`` falls back to a
72
+ fitted-field list (or the buggy 10-field ``_DEFAULT_T3_T6_FIELDS``).
73
+ The mismatch causes the adapter to learn one schema and be queried
74
+ on another at test time.
75
+
76
+ Here every (ticker, fiscal_year) row is wrapped in a prompt that
77
+ lists ``fitted_fields`` verbatim. The response JSON includes every
78
+ field in ``fitted_fields``; values not present in the row's ground
79
+ truth get ``null`` (which the eval-side parser
80
+ :func:`_extract_json_object` skips, contributing fillna(0) → APE
81
+ 100% on the eval side per ``feedback_penalize_incomplete``).
82
+ """
83
+ import json as _json
84
+
85
+ import pandas as _pd
86
+
87
+ from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
88
+ _safe_float,
89
+ )
90
+
91
+ if y is None or not hasattr(y, "empty") or y.empty:
92
+ return []
93
+ y_grouped = (
94
+ y.groupby(["ticker", "fiscal_year"])
95
+ .apply(lambda g: dict(zip(g["field"], g["value"])))
96
+ .to_dict()
97
+ )
98
+ fields_str = ", ".join(fitted_fields)
99
+ pairs: list[tuple[str, str]] = []
100
+ for _, row in X.iterrows():
101
+ ticker = str(row.get("ticker", "?"))
102
+ fy = row.get("fiscal_year", None)
103
+ key = (ticker, fy)
104
+ if key not in y_grouped:
105
+ for cand_key in y_grouped:
106
+ if str(cand_key[0]) == ticker and str(cand_key[1]) == str(fy):
107
+ key = cand_key
108
+ break
109
+ gt_fields = y_grouped.get(key, {})
110
+ if not gt_fields:
111
+ continue
112
+ if task == "T3":
113
+ sector = row.get("sector", "Unknown")
114
+ revenue = _safe_float(row.get("stmt_revenue", 0))
115
+ net_income = _safe_float(row.get("stmt_net_income", 0))
116
+ instr = (
117
+ f"You are a financial analyst. Given {ticker}'s known "
118
+ f"fundamentals (sector={sector}, revenue=${revenue:,.0f}, "
119
+ f"net_income=${net_income:,.0f}), predict these XBRL "
120
+ f"fields: [{fields_str}]"
121
+ )
122
+ else: # T6
123
+ description = row.get(
124
+ "company_description", f"A company with ticker {ticker}",
125
+ )
126
+ sector = row.get("sector", "Unknown")
127
+ industry = row.get("industry", "Unknown")
128
+ instr = (
129
+ f"Given this company description: '{description}', "
130
+ f"sector: '{sector}', industry: '{industry}', generate "
131
+ f"plausible financial statement values for these XBRL "
132
+ f"fields: [{fields_str}]"
133
+ )
134
+ resp_dict: dict[str, Any] = {}
135
+ for f in fitted_fields:
136
+ v = gt_fields.get(f, None)
137
+ if v is None or (isinstance(v, float) and _pd.isna(v)):
138
+ resp_dict[f] = None
139
+ else:
140
+ try:
141
+ resp_dict[f] = round(float(v), 2)
142
+ except (TypeError, ValueError):
143
+ resp_dict[f] = None
144
+ resp = _json.dumps(resp_dict)
145
+ pairs.append((instr, resp))
146
+ return pairs
147
+
148
+
149
+ def _build_pooled_pairs(granularity: str) -> tuple[
150
+ list[dict[str, str]], dict[str, int], dict[str, Any]
151
+ ]:
152
+ """Build the pooled SFT corpus across T1..T7 train splits.
153
+
154
+ Each task's training set is rendered into ``(instruction, response)``
155
+ pairs by the task-specific builders in :mod:`methods.llm_finetune`,
156
+ except T3 and T6 which use :func:`_t3_t6_pairs_fixed` (this file)
157
+ with a globally-fitted field list pooled from T3 + T6 train data;
158
+ that fixes the documented train/predict prompt-field-list mismatch.
159
+
160
+ Returns ``(rows, pair_counts_by_task, fitted_fields_meta)`` where
161
+ ``fitted_fields_meta`` is the sidecar dict written next to the
162
+ adapter for the eval path to load.
163
+ """
164
+ import numpy as np
165
+
166
+ from projects.agent_builder.scripts.whatif_bench import macrolens as ml
167
+ from projects.agent_builder.scripts.whatif_bench.methods.llm_finetune import (
168
+ _t1_pairs, _t2_t5_pairs, _t4_pairs, _t7_pairs,
169
+ _find_close_idx_from_array,
170
+ )
171
+
172
+ # ── Pre-load T3 + T6 train y to fit the global + per-ticker field lists ──
173
+ t3_train = ml.load("T3", "train", granularity=granularity)
174
+ t6_train = ml.load("T6", "train", granularity=granularity)
175
+
176
+ import pandas as pd
177
+ union_y = pd.concat(
178
+ [df for df in (t3_train.y, t6_train.y)
179
+ if df is not None and hasattr(df, "empty") and not df.empty],
180
+ ignore_index=True,
181
+ )
182
+ if union_y.empty or "field" not in union_y.columns:
183
+ raise RuntimeError("T3 + T6 train y is empty / lacks a 'field' column.")
184
+ fitted_fields_global: list[str] = sorted(
185
+ str(f) for f in union_y["field"].astype(str).unique()
186
+ )
187
+ fitted_fields_per_ticker: dict[str, list[str]] = {}
188
+ for t, grp in union_y.groupby("ticker", sort=False):
189
+ fitted_fields_per_ticker[str(t)] = sorted(
190
+ str(f) for f in grp["field"].astype(str).unique()
191
+ )
192
+ logger.info(
193
+ "T3+T6 fitted_fields_global has %d fields: %s",
194
+ len(fitted_fields_global), fitted_fields_global,
195
+ )
196
+
197
+ rows: list[dict[str, str]] = []
198
+ counts: dict[str, int] = {}
199
+ for task in ("T1", "T2", "T3", "T4", "T5", "T6", "T7"):
200
+ if task == "T3":
201
+ train = t3_train
202
+ elif task == "T6":
203
+ train = t6_train
204
+ else:
205
+ train = ml.load(task, "train", granularity=granularity)
206
+ X, y = train.X, train.y
207
+ if task == "T1":
208
+ X_arr = np.asarray(X, dtype=np.float32)
209
+ close_idx = _find_close_idx_from_array(X_arr)
210
+ pairs = _t1_pairs(
211
+ X_arr, np.asarray(y, dtype=np.float32), close_idx=close_idx,
212
+ )
213
+ elif task in ("T2", "T5"):
214
+ pairs = _t2_t5_pairs(X, np.asarray(y, dtype=np.float64), task=task)
215
+ elif task in ("T3", "T6"):
216
+ # CORRECTNESS FIX: use the globally-fitted field list (not per-row
217
+ # available fields) so training prompts match the eval-time
218
+ # prompt format produced by ``_predict_t3_t6`` after we populate
219
+ # ``_fitted_fields_global`` from our sidecar.
220
+ pairs = _t3_t6_pairs_fixed(
221
+ X, y, task=task, fitted_fields=fitted_fields_global,
222
+ )
223
+ elif task == "T4":
224
+ pairs = _t4_pairs(X, np.asarray(y, dtype=np.float32))
225
+ else:
226
+ pairs = _t7_pairs(X, y)
227
+ for instr, resp in pairs:
228
+ rows.append({
229
+ "prompt": f"### Instruction:\n{instr}\n\n### Response:\n",
230
+ "completion": resp,
231
+ })
232
+ counts[task] = len(pairs)
233
+ logger.info("built %d pairs for %s", len(pairs), task)
234
+
235
+ fitted_fields_meta = {
236
+ "fitted_fields_global": fitted_fields_global,
237
+ "fitted_fields_per_ticker": fitted_fields_per_ticker,
238
+ "granularity": granularity,
239
+ "source": "T3 + T6 train y union",
240
+ }
241
+ return rows, counts, fitted_fields_meta
242
+
243
+
244
+ def _build_model_and_tokenizer(
245
+ *, model_id: str, per_gpu_gib: int,
246
+ ) -> tuple[Any, Any]:
247
+ """Load the base LLM under bnb-NF4.
248
+
249
+ Standard dense-Transformer path: ``AutoModelForCausalLM`` +
250
+ ``device_map="auto"``. The naïve auto-dispatcher works correctly
251
+ because bnb-NF4 quantises every ``nn.Linear`` in a vanilla dense
252
+ decoder (no MoE-experts-stay-bf16 trap, no multimodal wrapper,
253
+ no hybrid attention modules to special-case).
254
+ """
255
+ import torch
256
+ from transformers import (
257
+ AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,
258
+ )
259
+
260
+ quant_config = BitsAndBytesConfig(
261
+ load_in_4bit=True,
262
+ bnb_4bit_quant_type="nf4",
263
+ bnb_4bit_use_double_quant=True,
264
+ bnb_4bit_compute_dtype=torch.bfloat16,
265
+ )
266
+
267
+ n_vis = torch.cuda.device_count() if torch.cuda.is_available() else 0
268
+ if n_vis < 1:
269
+ raise RuntimeError("no CUDA devices visible to PyTorch.")
270
+ max_memory = {i: f"{per_gpu_gib}GiB" for i in range(n_vis)}
271
+ logger.info(
272
+ "loading %s as AutoModelForCausalLM with bnb-NF4 (max_memory=%s)",
273
+ model_id, max_memory,
274
+ )
275
+
276
+ model = AutoModelForCausalLM.from_pretrained(
277
+ model_id,
278
+ quantization_config=quant_config,
279
+ device_map="auto",
280
+ max_memory=max_memory,
281
+ torch_dtype=torch.bfloat16,
282
+ attn_implementation="eager",
283
+ )
284
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
285
+ if tokenizer.pad_token is None:
286
+ tokenizer.pad_token = tokenizer.eos_token
287
+ return model, tokenizer
288
+
289
+
290
+ def run(
291
+ *,
292
+ base_hf_id: str = "Qwen/Qwen2.5-7B-Instruct",
293
+ granularity: str = "daily",
294
+ seed: int = 42,
295
+ output_dir: Path,
296
+ per_gpu_gib: int = 36,
297
+ max_length: int = 4096,
298
+ smoke_only: bool = False,
299
+ ) -> dict[str, Any]:
300
+ """Train one Scout multi-task QLoRA adapter across T1..T7 pooled.
301
+
302
+ Parameters
303
+ ----------
304
+ smoke_only
305
+ When True, run ``max_steps=2`` instead of one full epoch, so the
306
+ smoke pass verifies the load + LoRA-wrap + forward+backward +
307
+ optimiser step path before committing to the full training
308
+ wall-clock (~ 6-12 GPU-hours).
309
+ """
310
+ import torch
311
+ from datasets import Dataset
312
+ from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
313
+ from trl import SFTConfig, SFTTrainer
314
+
315
+ output_dir.mkdir(parents=True, exist_ok=True)
316
+
317
+ # 1. Pool data
318
+ t0 = time.perf_counter()
319
+ rows, counts, fitted_fields_meta = _build_pooled_pairs(
320
+ granularity=granularity,
321
+ )
322
+ if not rows:
323
+ raise RuntimeError("empty pooled corpus.")
324
+ pool_sec = time.perf_counter() - t0
325
+ logger.info(
326
+ "pooled %d pairs total (%s); pool build took %.1fs",
327
+ len(rows), counts, pool_sec,
328
+ )
329
+ # Write the fitted-fields sidecar BEFORE training so the eval path
330
+ # can populate ``_fitted_fields_per_ticker`` / ``_fitted_fields_global``
331
+ # on the loaded :class:`methods.LLMFineTuned` instance (matching the
332
+ # training prompts the adapter was tuned on).
333
+ sidecar_path = output_dir / "fitted_fields.json"
334
+ sidecar_path.write_text(json.dumps(fitted_fields_meta, indent=2))
335
+ logger.info("wrote T3/T6 fitted-fields sidecar to %s", sidecar_path)
336
+
337
+ # 2. Load model
338
+ model, tokenizer = _build_model_and_tokenizer(
339
+ model_id=base_hf_id, per_gpu_gib=per_gpu_gib,
340
+ )
341
+
342
+ # 3. Prepare for k-bit + apply LoRA
343
+ model = prepare_model_for_kbit_training(
344
+ model, use_gradient_checkpointing=True,
345
+ )
346
+ lora_cfg = LoraConfig(
347
+ r=16, # Meta's recipe
348
+ lora_alpha=32, # Meta's recipe
349
+ lora_dropout=0.0, # Meta's recipe
350
+ target_modules=[
351
+ "q_proj", "k_proj", "v_proj", "o_proj",
352
+ "gate_proj", "up_proj", "down_proj",
353
+ ],
354
+ bias="none",
355
+ task_type="CAUSAL_LM",
356
+ )
357
+ model = get_peft_model(model, lora_cfg)
358
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
359
+ total = sum(p.numel() for p in model.parameters())
360
+ logger.info(
361
+ "LoRA-adapted: %d trainable / %d total params (%.4f%%)",
362
+ trainable, total, 100.0 * trainable / max(1, total),
363
+ )
364
+
365
+ # 4. Format dataset for completion_only_loss
366
+ train_dataset = Dataset.from_list(rows)
367
+ if seed is not None:
368
+ train_dataset = train_dataset.shuffle(seed=seed)
369
+
370
+ # 5. SFTConfig — Meta's hyperparameters verbatim
371
+ sft_cfg = SFTConfig(
372
+ output_dir=str(output_dir),
373
+ num_train_epochs=1, # Meta's recipe
374
+ per_device_train_batch_size=2, # Meta's recipe
375
+ gradient_accumulation_steps=1, # Meta's recipe
376
+ learning_rate=2e-5, # Meta's recipe
377
+ lr_scheduler_type="cosine",
378
+ warmup_steps=100, # Meta's recipe
379
+ optim="adamw_torch", # Meta uses AdamW (not paged_adamw_8bit)
380
+ weight_decay=0.0,
381
+ max_grad_norm=0.0, # Meta: clip_grad_norm: null -> disabled
382
+ bf16=True,
383
+ fp16=False,
384
+ gradient_checkpointing=True,
385
+ completion_only_loss=True, # TRL 1.3 response-only loss
386
+ max_length=max_length, # T1 trajectories ~ 2000 tokens
387
+ dataset_text_field=None,
388
+ packing=False,
389
+ save_strategy="epoch",
390
+ save_total_limit=1,
391
+ save_only_model=True, # adapter checkpoints only
392
+ logging_steps=10,
393
+ report_to="none",
394
+ seed=seed,
395
+ max_steps=2 if smoke_only else -1,
396
+ )
397
+
398
+ trainer = SFTTrainer(
399
+ model=model,
400
+ args=sft_cfg,
401
+ train_dataset=train_dataset,
402
+ processing_class=tokenizer,
403
+ )
404
+
405
+ t1 = time.perf_counter()
406
+ trainer.train()
407
+ fit_sec = time.perf_counter() - t1
408
+ logger.info("training done in %.1fs (smoke=%s)", fit_sec, smoke_only)
409
+
410
+ # 6. Save adapter
411
+ adapter_dir = output_dir / "adapter"
412
+ tokenizer_dir = output_dir / "tokenizer"
413
+ model.save_pretrained(str(adapter_dir))
414
+ tokenizer.save_pretrained(str(tokenizer_dir))
415
+ logger.info("adapter saved to %s", adapter_dir)
416
+
417
+ return {
418
+ "probe": "scout_qlora_multitask",
419
+ "base_hf_id": base_hf_id,
420
+ "granularity": granularity,
421
+ "seed": seed,
422
+ "pair_counts": counts,
423
+ "pool_sec": pool_sec,
424
+ "fit_sec": fit_sec,
425
+ "smoke_only": smoke_only,
426
+ "adapter_dir": str(adapter_dir),
427
+ "tokenizer_dir": str(tokenizer_dir),
428
+ "max_length": max_length,
429
+ "fitted_fields_sidecar": str(sidecar_path),
430
+ }
431
+
432
+
433
+ def main() -> int:
434
+ parser = argparse.ArgumentParser(description=__doc__)
435
+ parser.add_argument(
436
+ "--base-hf-id",
437
+ default="Qwen/Qwen2.5-7B-Instruct",
438
+ help="HF model id of the base.",
439
+ )
440
+ parser.add_argument("--granularity", default="daily")
441
+ parser.add_argument("--seed", type=int, default=42)
442
+ parser.add_argument(
443
+ "--output-dir", type=Path,
444
+ default=Path(__file__).resolve().parents[1] / "adapters" / "qwen25_7b_qlora_multitask",
445
+ )
446
+ parser.add_argument("--per-gpu-gib", type=int, default=36)
447
+ parser.add_argument("--max-length", type=int, default=4096)
448
+ parser.add_argument(
449
+ "--smoke-only", action="store_true",
450
+ help="Run max_steps=2 instead of a full epoch (verifies load + "
451
+ "forward + backward + optimiser step in ~minutes).",
452
+ )
453
+ parser.add_argument(
454
+ "--report-path", type=Path, default=None,
455
+ help="JSON report path (default: <output_dir>/training_report.json).",
456
+ )
457
+ args = parser.parse_args()
458
+
459
+ logging.basicConfig(
460
+ level=logging.INFO,
461
+ format="%(asctime)s %(levelname)s %(message)s",
462
+ )
463
+
464
+ report = run(
465
+ base_hf_id=args.base_hf_id,
466
+ granularity=args.granularity,
467
+ seed=args.seed,
468
+ output_dir=args.output_dir,
469
+ per_gpu_gib=args.per_gpu_gib,
470
+ max_length=args.max_length,
471
+ smoke_only=args.smoke_only,
472
+ )
473
+ report_path = args.report_path or (args.output_dir / "training_report.json")
474
+ report_path.parent.mkdir(parents=True, exist_ok=True)
475
+ report_path.write_text(json.dumps(report, indent=2, default=str))
476
+ logger.info("report -> %s", report_path)
477
+ return 0
478
+
479
+
480
+ if __name__ == "__main__":
481
+ sys.exit(main())
code/experiments/re_evaluate.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Re-score saved predictions with the current eval.py (no re-running models).
2
+
3
+ Reads every ``experiments/predictions/<method>_<task>_seed<seed>[_setX].pkl``,
4
+ calls ``ml.score`` with the current ``eval.py``, writes a fresh
5
+ ``RunRecord`` JSON to ``experiments/results/canon_reeval_<timestamp>.json``.
6
+
7
+ Use this whenever ``eval.py`` is patched: regenerates metrics from cached
8
+ predictions in ~seconds, no LLM/GPU spend.
9
+ """
10
+ from __future__ import annotations
11
+ import argparse, json, pickle, pathlib, sys
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ def main():
16
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
17
+ from whatif_bench import config
18
+ from whatif_bench import macrolens as ml
19
+
20
+ pred_dir = pathlib.Path(__file__).parent / "predictions"
21
+ out_dir = pathlib.Path(__file__).parent / "results"
22
+ out_path = out_dir / f"canon_reeval_{pd.Timestamp.utcnow().strftime('%Y%m%dT%H%M%SZ')}.json"
23
+ records = []
24
+ pkls = sorted(pred_dir.glob("*.pkl"))
25
+ print(f"re-evaluating {len(pkls)} prediction files")
26
+ for p in pkls:
27
+ with open(p, "rb") as f:
28
+ d = pickle.load(f)
29
+ task = d["task"]
30
+ meta_test = d["meta_test"]
31
+ y_test = d["y_test"]
32
+ y_pred = d["y_pred"]
33
+ # cluster keys
34
+ if task == "T4":
35
+ ck = meta_test["scenario_id"].values if "scenario_id" in meta_test.columns else None
36
+ elif task == "T7":
37
+ ck = meta_test["address"].values if "address" in meta_test.columns else None
38
+ elif "ticker" in meta_test.columns:
39
+ ck = meta_test["ticker"].values
40
+ else:
41
+ ck = None
42
+ kw = {"cluster_keys": ck}
43
+ if task == "T1" and "close_last" in meta_test.columns:
44
+ kw["close_last"] = meta_test["close_last"].values
45
+ try:
46
+ metrics = ml.score(task, y_test, y_pred, **kw)
47
+ except Exception as exc:
48
+ print(f" {p.name}: score raised {type(exc).__name__}: {exc}")
49
+ continue
50
+ # Build a record (mirroring RunRecord essentials)
51
+ rec = {
52
+ "method_id": d["method_id"],
53
+ "task": task,
54
+ "granularity": d.get("granularity", "daily"),
55
+ "seed": d.get("seed", 42),
56
+ "status": "ok",
57
+ "ablation_setting": d.get("ablation_setting"),
58
+ "timestamp": pd.Timestamp.utcnow().isoformat(),
59
+ "metrics": {k: (v.model_dump() if hasattr(v,"model_dump") else v) for k,v in metrics.items()},
60
+ }
61
+ records.append(rec)
62
+ primary = {"T1":"mse","T2":"median_ape","T3":"overall_mape","T4":"return_mae_pct",
63
+ "T5":"median_ape","T6":"overall_mape","T7":"rent_MAPE"}.get(task)
64
+ pv = (metrics or {}).get(primary)
65
+ pv = pv.value if pv is not None and hasattr(pv, "value") else None
66
+ print(f" {d['method_id']:18s} {task} setting={d.get('ablation_setting')} {primary}={pv}")
67
+ out_path.write_text(json.dumps(records, indent=2, default=str))
68
+ print(f"\nwrote {len(records)} re-evaluated records to {out_path}")
69
+
70
+ if __name__ == "__main__":
71
+ main()
code/experiments/result_schema.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pydantic v2 result schemas for MacroLens task runners.
2
+
3
+ These models replace the legacy ``TypedDict`` shapes used pre-Phase-4. The
4
+ orchestrator (:mod:`experiments.run_all`) persists results as
5
+ :class:`macrolens.RunRecord` (full reproducibility envelope); these
6
+ per-task models capture the *metric content* of a single record's
7
+ ``metrics`` field and are used by post-hoc tools (``gen_tables.py``,
8
+ ``analysis.py``) that need a typed handle on the per-task metric set.
9
+
10
+ Every model:
11
+
12
+ * Uses ``model_config = ConfigDict(extra="forbid", frozen=True)`` so unknown
13
+ keys raise at construction and instances are hashable.
14
+ * Allows every metric to be ``None`` — runners that legitimately skip a
15
+ metric (e.g., a deterministic naive method that does not report CRPS)
16
+ emit ``None``, not a sentinel string.
17
+ * Adds T5/T6/T7 (the legacy schema was missing T5/T6/T7).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import pydantic
23
+
24
+
25
+ # ── Shared sub-schemas ────────────────────────────────────────────────────
26
+
27
+
28
+ class BootstrapCI(pydantic.BaseModel):
29
+ """Bootstrap 95% CI for a scalar metric (matches ``MetricValue``)."""
30
+
31
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
32
+
33
+ mean: float | None = None
34
+ ci_lo: float | None = None
35
+ ci_hi: float | None = None
36
+ std: float | None = None
37
+
38
+
39
+ class MultiSeedStats(pydantic.BaseModel):
40
+ """Mean +/- std over the headline T1 multi-seed subset."""
41
+
42
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
43
+
44
+ seed_mean: float | None = None
45
+ seed_std: float | None = None
46
+ per_seed: dict[int, float] | None = None
47
+
48
+
49
+ # ── Per-task metric schemas ───────────────────────────────────────────────
50
+
51
+
52
+ class T1Metrics(pydantic.BaseModel):
53
+ """T1 — Contextual Time-Series Forecasting."""
54
+
55
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
56
+
57
+ method_id: str
58
+ task: str = "T1"
59
+ horizon: int | None = None
60
+ granularity: str = "daily"
61
+ seed: int = 42
62
+ mse: float | None = None
63
+ mae: float | None = None
64
+ rmse: float | None = None
65
+ directional_accuracy: float | None = None
66
+ mse_ci: BootstrapCI | None = None
67
+ mae_ci: BootstrapCI | None = None
68
+ da_ci: BootstrapCI | None = None
69
+ multiseed: MultiSeedStats | None = None
70
+ n_instances: int | None = None
71
+ inference_time_sec: float | None = None
72
+ train_time_sec: float | None = None
73
+
74
+
75
+ class T2Metrics(pydantic.BaseModel):
76
+ """T2 — Point-in-Time Equity Valuation."""
77
+
78
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
79
+
80
+ method_id: str
81
+ task: str = "T2"
82
+ granularity: str = "daily"
83
+ seed: int = 42
84
+ mape: float | None = None
85
+ median_ape: float | None = None
86
+ rank_correlation: float | None = None
87
+ rank_p_value: float | None = None
88
+ mape_ci: BootstrapCI | None = None
89
+ n_predictions: int | None = None
90
+ n_tickers: int | None = None
91
+ inference_time_sec: float | None = None
92
+
93
+
94
+ class T3Metrics(pydantic.BaseModel):
95
+ """T3 — Statement Generation (per-field MAPE + balance equation)."""
96
+
97
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
98
+
99
+ method_id: str
100
+ task: str = "T3"
101
+ granularity: str = "daily"
102
+ seed: int = 42
103
+ overall_mape: float | None = None
104
+ per_field_mape: dict[str, float] | None = None
105
+ balance_equation_accuracy: float | None = None
106
+ balance_equation_checked: int | None = None
107
+ success_rate: float | None = None
108
+ n_fields_matched: int | None = None
109
+ n_field_misses: int | None = None
110
+ n_tickers: int | None = None
111
+ inference_time_sec: float | None = None
112
+
113
+
114
+ class T4Metrics(pydantic.BaseModel):
115
+ """T4 — Scenario-Conditioned Return Forecasting."""
116
+
117
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
118
+
119
+ method_id: str
120
+ task: str = "T4"
121
+ granularity: str = "daily"
122
+ seed: int = 42
123
+ return_mae_pct: float | None = None
124
+ directional_accuracy: float | None = None
125
+ ci_calibration_95: float | None = None
126
+ return_mae_ci: BootstrapCI | None = None
127
+ n_predictions: int | None = None
128
+ n_scenarios: int | None = None
129
+ inference_time_sec: float | None = None
130
+
131
+
132
+ class T5Metrics(pydantic.BaseModel):
133
+ """T5 — Private-Company Valuation (no market prices)."""
134
+
135
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
136
+
137
+ method_id: str
138
+ task: str = "T5"
139
+ granularity: str = "daily"
140
+ seed: int = 42
141
+ mape: float | None = None
142
+ median_ape: float | None = None
143
+ rank_correlation: float | None = None
144
+ rank_p_value: float | None = None
145
+ mape_ci: BootstrapCI | None = None
146
+ n_predictions: int | None = None
147
+ n_tickers: int | None = None
148
+ gap_vs_t2: float | None = None
149
+ inference_time_sec: float | None = None
150
+
151
+
152
+ class T6Metrics(pydantic.BaseModel):
153
+ """T6 — Generator Evaluation (NL description -> XBRL)."""
154
+
155
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
156
+
157
+ method_id: str
158
+ task: str = "T6"
159
+ granularity: str = "daily"
160
+ seed: int = 42
161
+ overall_mape: float | None = None
162
+ per_field_mape: dict[str, float] | None = None
163
+ success_rate: float | None = None
164
+ n_fields_matched: int | None = None
165
+ n_field_misses: int | None = None
166
+ n_tickers: int | None = None
167
+ inference_time_sec: float | None = None
168
+
169
+
170
+ class T7Metrics(pydantic.BaseModel):
171
+ """T7 — Real-Estate Valuation."""
172
+
173
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
174
+
175
+ method_id: str
176
+ task: str = "T7"
177
+ granularity: str = "daily"
178
+ seed: int = 42
179
+ rent_MAPE: float | None = None
180
+ price_MAPE: float | None = None
181
+ rent_median_APE: float | None = None
182
+ price_median_APE: float | None = None
183
+ rent_n_valid: int | None = None
184
+ price_n_valid: int | None = None
185
+ n_predictions: int | None = None
186
+ inference_time_sec: float | None = None
187
+
188
+
189
+ # ── Family-level container ────────────────────────────────────────────────
190
+
191
+
192
+ class FamilyResults(pydantic.BaseModel):
193
+ """Container emitted by each family's ``run_all_*()`` function."""
194
+
195
+ model_config = pydantic.ConfigDict(extra="forbid", frozen=True)
196
+
197
+ family: str
198
+ panel_version: str | None = None
199
+ methods: dict[str, list[dict]] = pydantic.Field(default_factory=dict)
200
+
201
+
202
+ # ── Task dispatch map ─────────────────────────────────────────────────────
203
+
204
+
205
+ TASK_RESULT_TYPES: dict[str, type[pydantic.BaseModel]] = {
206
+ "T1": T1Metrics,
207
+ "T2": T2Metrics,
208
+ "T3": T3Metrics,
209
+ "T4": T4Metrics,
210
+ "T5": T5Metrics,
211
+ "T6": T6Metrics,
212
+ "T7": T7Metrics,
213
+ }
code/experiments/run_all.py ADDED
@@ -0,0 +1,1041 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Phase-4 unified-API experiment orchestrator.
2
+
3
+ Thin runner that ties together:
4
+
5
+ data (``ml.load``) -> method (``ml.methods.<Class>``)
6
+ -> eval (``ml.score``)
7
+ -> :class:`macrolens.RunRecord`
8
+ -> JSON via ``pydantic.TypeAdapter``.
9
+
10
+ Every choice mirrors the unified-API plan §6 (RunRecord), §7 (Determinism
11
+ flag), and Phase-4 Pipeline B pseudocode.
12
+
13
+ Hard rules:
14
+
15
+ * Zero benchmark-data IO outside ``ml.load`` (this file is a leaf consumer).
16
+ * Methods/eval are accessed strictly via :mod:`macrolens` (no reaching into
17
+ private internals).
18
+ * The runner does NOT override hyperparameters except for two cases:
19
+ (i) T1 + ``Persistence`` — the runner reads the actual ``close`` index
20
+ out of ``meta_test.attrs["feature_names"]`` and overrides
21
+ ``PersistenceConfig.close_feature_idx``;
22
+ (ii) opt-in ``--config-override`` flag (e.g. ``lightgbm.n_estimators=20``)
23
+ for fast smoke tests.
24
+ * LLM/LLM-TS/LLM-FT method families require an externally-managed vLLM
25
+ HTTP endpoint (one ``vllm serve`` per HF model id). The runner reads the
26
+ endpoint URL from a per-method environment variable
27
+ (``MACROLENS_LLM_BASE_URL_<NAME>`` — see :func:`_resolve_llm_engine`),
28
+ constructs one :class:`methods._openai_engine.OpenAIChatEngine` per
29
+ ``(method_id, model_id)`` pair, and injects it via the ``engine=``
30
+ ctor kwarg. If no endpoint is configured for an LLM-family method, the
31
+ runner emits ``status="skip"`` with a clear ``error`` message — there
32
+ is NO silent fallback to a dry-run engine.
33
+
34
+ Usage::
35
+
36
+ python -m projects.agent_builder.scripts.whatif_bench.experiments \\
37
+ --task T1 T2 \\
38
+ --method persistence log_size_ols lightgbm \\
39
+ --granularity daily --seeds 42 --no-checkpoint
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import argparse
45
+ import datetime as dt
46
+ import json
47
+ import logging
48
+ import os
49
+ import platform
50
+ import subprocess
51
+ import sys
52
+ import time
53
+ import traceback
54
+ import tracemalloc
55
+ from concurrent.futures import ProcessPoolExecutor, as_completed
56
+ from pathlib import Path
57
+ from typing import Any, Iterable
58
+
59
+ import pydantic
60
+
61
+ from .. import config
62
+ from .. import macrolens as ml
63
+ from ..macrolens import RunRecord
64
+ from . import panel as panel_module
65
+
66
+ logger = logging.getLogger(__name__)
67
+
68
+
69
+ # ── Constants ─────────────────────────────────────────────────────────────
70
+
71
+
72
+ # Method families that talk to an externally-managed vLLM HTTP endpoint.
73
+ # The runner resolves one ``OpenAIChatEngine`` per family member from
74
+ # ``MACROLENS_LLM_BASE_URL_<NAME>`` and injects it via ``engine=``.
75
+ _LLM_FAMILIES: frozenset[str] = frozenset({"llm", "llm_ts", "llm_ft"})
76
+
77
+ # Hard cap on how much traceback text is recorded on a failed RunRecord
78
+ # so the result JSON stays bounded even when stack traces are huge.
79
+ _TRACEBACK_TRUNCATE_BYTES: int = 4 * 1024
80
+
81
+
82
+ # ── LLM engine resolution (env-var → OpenAIChatEngine) ────────────────────
83
+
84
+
85
+ def _llm_endpoint_env_var(method_id: str) -> str:
86
+ """Canonical env-var name for a given LLM-family method id.
87
+
88
+ Mapping rule: uppercase the method id and prefix with
89
+ ``MACROLENS_LLM_BASE_URL_``. Examples::
90
+
91
+ llama_scout -> MACROLENS_LLM_BASE_URL_LLAMA_SCOUT
92
+ gemma4 -> MACROLENS_LLM_BASE_URL_GEMMA4
93
+ chattime -> MACROLENS_LLM_BASE_URL_CHATTIME
94
+ time_mqa -> MACROLENS_LLM_BASE_URL_TIME_MQA
95
+ llm_finetuned -> MACROLENS_LLM_BASE_URL_LLM_FINETUNED
96
+ """
97
+ return f"MACROLENS_LLM_BASE_URL_{method_id.upper()}"
98
+
99
+
100
+ # Process-global cache: one OpenAIChatEngine per (env-var, model_id) pair
101
+ # so all (task, seed) cells reuse the same HTTP client.
102
+ _LLM_ENGINE_CACHE: dict[tuple[str, str], Any] = {}
103
+
104
+
105
+ def _resolve_llm_engine(
106
+ method_id: str, cls: type,
107
+ ) -> tuple[Any | None, str | None]:
108
+ """Return ``(engine, error)`` for one LLM-family method.
109
+
110
+ Reads the endpoint URL from ``MACROLENS_LLM_BASE_URL_<METHOD_ID>``.
111
+ If unset, returns ``(None, "<reason>")`` so the runner can emit a
112
+ ``status="skip"`` record. If set, constructs (or returns the cached)
113
+ :class:`methods._openai_engine.OpenAIChatEngine` and returns it.
114
+
115
+ Exception: methods whose authors' inference code is fundamentally
116
+ incompatible with the OpenAI chat API (ChatTime's 10K-bin numeric
117
+ tokenisation; Time-MQA's LoRA prompt protocol) are loaded in-process
118
+ from the vendored authors' code via a dedicated engine wrapper. They
119
+ do not require an env-var endpoint.
120
+ """
121
+ # In-process engines for methods that can't be served via vllm-serve.
122
+ if method_id == "chattime":
123
+ try:
124
+ cfg = cls.default_config()
125
+ model_id = getattr(cfg, "model_id", "") or "ChengsenWang/ChatTime-1-7B-Chat"
126
+ except Exception:
127
+ model_id = "ChengsenWang/ChatTime-1-7B-Chat"
128
+ cache_key = ("inprocess:chattime", model_id)
129
+ cached = _LLM_ENGINE_CACHE.get(cache_key)
130
+ if cached is not None:
131
+ return cached, None
132
+ try:
133
+ from ..methods._chattime_engine import ChatTimeEngine
134
+ engine = ChatTimeEngine(model_path=model_id)
135
+ except Exception as exc:
136
+ return None, f"ChatTimeEngine construction failed: {exc!r}"
137
+ _LLM_ENGINE_CACHE[cache_key] = engine
138
+ return engine, None
139
+
140
+ env_var = _llm_endpoint_env_var(method_id)
141
+ base_url = os.environ.get(env_var, "").strip()
142
+ if not base_url:
143
+ return (
144
+ None,
145
+ f"No endpoint configured for {method_id}; "
146
+ f"set {env_var}=http://<host>:<port>/v1",
147
+ )
148
+
149
+ # Pull the model_id from the method's default config so the engine
150
+ # can target the matching ``model`` field on the vLLM endpoint.
151
+ try:
152
+ cfg = cls.default_config()
153
+ model_id = getattr(cfg, "model_id", "") or method_id
154
+ except Exception:
155
+ model_id = method_id
156
+
157
+ cache_key = (base_url, model_id)
158
+ cached = _LLM_ENGINE_CACHE.get(cache_key)
159
+ if cached is not None:
160
+ return cached, None
161
+
162
+ try:
163
+ from ..methods._openai_engine import OpenAIChatEngine
164
+ except ImportError as exc: # pragma: no cover -- defensive
165
+ return None, f"OpenAI client import failed: {exc!r}"
166
+
167
+ api_key = os.environ.get("MACROLENS_LLM_API_KEY", "EMPTY") or "EMPTY"
168
+ n_workers = int(os.environ.get("MACROLENS_LLM_N_WORKERS", "8"))
169
+ timeout = float(os.environ.get("MACROLENS_LLM_TIMEOUT_SEC", "300"))
170
+ try:
171
+ engine = OpenAIChatEngine(
172
+ base_url=base_url, api_key=api_key, model_id=model_id,
173
+ n_workers=n_workers, request_timeout_sec=timeout,
174
+ )
175
+ except Exception as exc:
176
+ return None, f"OpenAIChatEngine construction failed: {exc!r}"
177
+
178
+ _LLM_ENGINE_CACHE[cache_key] = engine
179
+ return engine, None
180
+
181
+
182
+ # ── Provenance helpers ────────────────────────────────────────────────────
183
+
184
+
185
+ def _git_sha() -> str:
186
+ """Return the current git SHA, or ``"unknown"`` if outside a git tree."""
187
+ try:
188
+ out = subprocess.check_output(
189
+ ["git", "rev-parse", "HEAD"], stderr=subprocess.DEVNULL,
190
+ )
191
+ return out.decode().strip()
192
+ except Exception:
193
+ return "unknown"
194
+
195
+
196
+ def _detect_hardware() -> dict[str, str]:
197
+ """Best-effort hardware fingerprint (CPU + GPU + CUDA)."""
198
+ hw: dict[str, str] = {
199
+ "cpu": platform.processor() or platform.machine(),
200
+ "platform": platform.platform(),
201
+ "python_version": platform.python_version(),
202
+ }
203
+ try:
204
+ import torch # type: ignore
205
+
206
+ hw["torch_version"] = torch.__version__
207
+ if torch.cuda.is_available():
208
+ hw["gpu"] = torch.cuda.get_device_name(0)
209
+ hw["n_gpus"] = str(torch.cuda.device_count())
210
+ hw["cuda_version"] = str(torch.version.cuda)
211
+ else:
212
+ hw["gpu"] = "none"
213
+ hw["n_gpus"] = "0"
214
+ hw["cuda_version"] = "n/a"
215
+ except Exception:
216
+ hw["gpu"] = "unknown"
217
+ hw["n_gpus"] = "0"
218
+ hw["cuda_version"] = "n/a"
219
+ return hw
220
+
221
+
222
+ def _truncate_traceback(exc: BaseException) -> str:
223
+ tb = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
224
+ if len(tb) > _TRACEBACK_TRUNCATE_BYTES:
225
+ tb = tb[: _TRACEBACK_TRUNCATE_BYTES - 16] + "\n... [truncated]"
226
+ return tb
227
+
228
+
229
+ def _checkpoint_path(
230
+ method_id: str, task: str, granularity: str, seed: int,
231
+ horizon: int | None = None,
232
+ ) -> Path:
233
+ """Canonical per-run checkpoint directory.
234
+
235
+ For T1, ``horizon`` is included in the path so multiple horizons
236
+ on the same (method, task, granularity, seed) tuple each get their
237
+ own fresh fit/save state and never collide.
238
+ """
239
+ base = (
240
+ Path(__file__).resolve().parent
241
+ / "checkpoints"
242
+ / method_id
243
+ / task
244
+ / granularity
245
+ / f"seed={seed}"
246
+ )
247
+ if task == "T1" and horizon is not None:
248
+ base = base / f"h={horizon}"
249
+ return base
250
+
251
+
252
+ def _apply_overrides(config_overrides: dict[str, dict[str, Any]], method_id: str) -> dict[str, Any]:
253
+ """Return the kwarg dict for one method (post-override)."""
254
+ return dict(config_overrides.get(method_id, {}))
255
+
256
+
257
+ def _now_iso() -> str:
258
+ return dt.datetime.now(dt.timezone.utc).isoformat()
259
+
260
+
261
+ # ── Inner per-(method, seed) execution ─────────────────────────────────────
262
+
263
+
264
+ def _make_failed_record(
265
+ *,
266
+ method_id: str,
267
+ method_family: str,
268
+ task: str,
269
+ granularity: str,
270
+ seed: int,
271
+ status: str,
272
+ error: str,
273
+ n_train: int | None,
274
+ n_test: int | None,
275
+ hyperparams: dict[str, Any],
276
+ artifact_sha256: dict[str, str],
277
+ deterministic_mode: bool,
278
+ fit_time_sec: float | None = None,
279
+ predict_time_sec: float | None = None,
280
+ peak_mem_mb: float | None = None,
281
+ ablation_setting: str | None = None,
282
+ ) -> RunRecord:
283
+ return RunRecord(
284
+ method_id=method_id, method_family=method_family,
285
+ task=task, granularity=granularity, seed=seed,
286
+ status=status, error=error,
287
+ n_train=n_train, n_test=n_test,
288
+ hyperparams=hyperparams,
289
+ lib_versions={}, hardware=_detect_hardware(),
290
+ fit_time_sec=fit_time_sec, predict_time_sec=predict_time_sec,
291
+ peak_mem_mb=peak_mem_mb, metrics=None,
292
+ artifact_sha256=artifact_sha256,
293
+ timestamp=_now_iso(), git_sha=_git_sha(),
294
+ deterministic_mode=deterministic_mode,
295
+ ablation_setting=ablation_setting,
296
+ )
297
+
298
+
299
+ def _sanity_gate(
300
+ task: str,
301
+ X_test: Any,
302
+ y_test: Any,
303
+ y_pred: Any,
304
+ y_train: Any,
305
+ meta_test: Any,
306
+ ) -> str | None:
307
+ """Persistence-/constant-floor sanity gate for regression tasks.
308
+
309
+ Compares the model's primary metric on the eval set against a trivial
310
+ reference floor (persistence for T1, train-median/-mean constant for
311
+ T2/T4/T5/T7). If model_metric > 10× baseline_metric (100× for T1's
312
+ persistence floor — kept tight because persistence is itself non-trivial)
313
+ the cell is flagged "suspect" via a returned reason string. T3 and T6
314
+ are long-form per-field tasks; their per-field MAPE floor is implicitly
315
+ the SectorMedian baseline already in the panel, so they are skipped here.
316
+
317
+ The gate is best-effort: any internal exception or shape mismatch
318
+ yields ``None`` so the runner never crashes on a sanity probe.
319
+ """
320
+ try:
321
+ import numpy as _np
322
+ except Exception: # pragma: no cover -- numpy is a hard dep
323
+ return None
324
+
325
+ try:
326
+ # ── T1: persistence MSE floor ────────────────────────────────────
327
+ if task == "T1":
328
+ y_t = _np.asarray(y_test, dtype=_np.float64)
329
+ y_p = _np.asarray(y_pred, dtype=_np.float64)
330
+ close_last = None
331
+ if hasattr(meta_test, "columns") and "close_last" in meta_test.columns:
332
+ close_last = _np.asarray(
333
+ meta_test["close_last"].values, dtype=_np.float64,
334
+ )
335
+ elif hasattr(X_test, "shape") and getattr(X_test, "ndim", 0) == 3:
336
+ close_last = _np.asarray(X_test[:, -1, -1], dtype=_np.float64)
337
+ if (close_last is None
338
+ or y_t.ndim != 2 or y_p.ndim != 2
339
+ or y_t.shape != y_p.shape):
340
+ return None
341
+ tile = _np.broadcast_to(close_last[:, None], y_t.shape)
342
+ pers_mse = float(_np.nanmean((tile - y_t) ** 2))
343
+ model_mse = float(_np.nanmean((y_p - y_t) ** 2))
344
+ if not (_np.isfinite(pers_mse) and _np.isfinite(model_mse)
345
+ and pers_mse > 0):
346
+ return None
347
+ if model_mse > 100.0 * pers_mse:
348
+ return (
349
+ f"T1 SUSPECT: model_MSE={model_mse:.4g} > 100x "
350
+ f"persistence_MSE={pers_mse:.4g} on the same eval set; "
351
+ "model likely emitting un-normalised raw close instead "
352
+ "of per-window log-returns."
353
+ )
354
+ return None
355
+
356
+ # ── T2 / T5: constant (train-median) MAPE floor ─────────────────
357
+ if task in ("T2", "T5"):
358
+ y_tr = _np.asarray(y_train, dtype=_np.float64).ravel()
359
+ y_t = _np.asarray(y_test, dtype=_np.float64).ravel()
360
+ y_p = _np.asarray(y_pred, dtype=_np.float64).ravel()
361
+ if y_t.size == 0 or y_t.shape != y_p.shape:
362
+ return None
363
+ const = float(_np.nanmedian(y_tr))
364
+ if not _np.isfinite(const):
365
+ return None
366
+ denom = _np.abs(y_t)
367
+ mask = _np.isfinite(y_t) & _np.isfinite(y_p) & (denom > 0)
368
+ if not mask.any():
369
+ return None
370
+ const_mape = 100.0 * float(_np.nanmean(
371
+ _np.abs(const - y_t[mask]) / denom[mask]
372
+ ))
373
+ model_mape = 100.0 * float(_np.nanmean(
374
+ _np.abs(y_p[mask] - y_t[mask]) / denom[mask]
375
+ ))
376
+ if not (_np.isfinite(const_mape) and _np.isfinite(model_mape)
377
+ and const_mape > 0):
378
+ return None
379
+ if model_mape > 10.0 * const_mape:
380
+ return (
381
+ f"{task} SUSPECT: model_MAPE={model_mape:.4g} > 10x "
382
+ f"baseline_MAPE={const_mape:.4g} on the same eval set; "
383
+ "check method implementation"
384
+ )
385
+ return None
386
+
387
+ # ── T4: constant (train-mean) MAE floor on return % ─────────────
388
+ if task == "T4":
389
+ y_tr = _np.asarray(y_train, dtype=_np.float64).ravel()
390
+ y_t = _np.asarray(y_test, dtype=_np.float64).ravel()
391
+ y_p = _np.asarray(y_pred, dtype=_np.float64).ravel()
392
+ if y_t.size == 0 or y_t.shape != y_p.shape:
393
+ return None
394
+ const = float(_np.nanmean(y_tr))
395
+ if not _np.isfinite(const):
396
+ return None
397
+ mask = _np.isfinite(y_t) & _np.isfinite(y_p)
398
+ if not mask.any():
399
+ return None
400
+ const_mae = float(_np.nanmean(_np.abs(const - y_t[mask])))
401
+ model_mae = float(_np.nanmean(_np.abs(y_p[mask] - y_t[mask])))
402
+ if not (_np.isfinite(const_mae) and _np.isfinite(model_mae)
403
+ and const_mae > 0):
404
+ return None
405
+ if model_mae > 10.0 * const_mae:
406
+ return (
407
+ f"T4 SUSPECT: model_MAE={model_mae:.4g} > 10x "
408
+ f"baseline_MAE={const_mae:.4g} on the same eval set; "
409
+ "check method implementation"
410
+ )
411
+ return None
412
+
413
+ # ── T7: per-target constant (train-median) MAPE floors ──────────
414
+ if task == "T7":
415
+ try:
416
+ import pandas as _pd
417
+ except Exception: # pragma: no cover
418
+ return None
419
+ if not (isinstance(y_train, _pd.DataFrame)
420
+ and isinstance(y_test, _pd.DataFrame)
421
+ and isinstance(y_pred, _pd.DataFrame)):
422
+ return None
423
+ if "address" not in y_test.columns or "address" not in y_pred.columns:
424
+ return None
425
+ merged = y_test.merge(
426
+ y_pred, on="address", how="inner",
427
+ suffixes=("_actual", "_pred"),
428
+ )
429
+ if merged.empty:
430
+ return None
431
+ for target, pred_col in (("rent", "pred_rent"),
432
+ ("price", "pred_price")):
433
+ actual_col = target if target in merged.columns else f"{target}_actual"
434
+ if pred_col not in merged.columns or actual_col not in merged.columns:
435
+ continue
436
+ if target not in y_train.columns:
437
+ continue
438
+ y_tr = _pd.to_numeric(y_train[target], errors="coerce").to_numpy()
439
+ const = float(_np.nanmedian(y_tr))
440
+ if not _np.isfinite(const):
441
+ continue
442
+ actual = _pd.to_numeric(merged[actual_col], errors="coerce").to_numpy()
443
+ pred = _pd.to_numeric(merged[pred_col], errors="coerce").to_numpy()
444
+ denom = _np.abs(actual)
445
+ mask = _np.isfinite(actual) & _np.isfinite(pred) & (denom > 0)
446
+ if not mask.any():
447
+ continue
448
+ const_mape = 100.0 * float(_np.nanmean(
449
+ _np.abs(const - actual[mask]) / denom[mask]
450
+ ))
451
+ model_mape = 100.0 * float(_np.nanmean(
452
+ _np.abs(pred[mask] - actual[mask]) / denom[mask]
453
+ ))
454
+ if not (_np.isfinite(const_mape) and _np.isfinite(model_mape)
455
+ and const_mape > 0):
456
+ continue
457
+ if model_mape > 10.0 * const_mape:
458
+ return (
459
+ f"T7 SUSPECT: model_{target}_MAPE={model_mape:.4g} "
460
+ f"> 10x baseline_{target}_MAPE={const_mape:.4g} on "
461
+ "the same eval set; check method implementation"
462
+ )
463
+ return None
464
+
465
+ # T3, T6 (long-form per-field tasks): skipped by design.
466
+ return None
467
+ except Exception: # noqa: BLE001 -- gate is best-effort
468
+ return None
469
+
470
+
471
+ def _run_one(
472
+ *,
473
+ method_id: str,
474
+ cls: type,
475
+ task: str,
476
+ granularity: str,
477
+ seed: int,
478
+ X_train: Any, y_train: Any, meta_train: Any,
479
+ X_test: Any, y_test: Any, meta_test: Any,
480
+ no_checkpoint: bool,
481
+ deterministic: bool,
482
+ extra_kwargs: dict[str, Any],
483
+ ) -> RunRecord:
484
+ """Run a single (method, seed) cell on already-loaded data."""
485
+ method_family = getattr(cls, "family", "unknown")
486
+ artifact_sha256: dict[str, str] = {
487
+ **(meta_train.attrs.get("data_sha256") or {}),
488
+ **(meta_test.attrs.get("data_sha256") or {}),
489
+ }
490
+ n_train, n_test = len(X_train), len(X_test)
491
+ ablation_setting = (
492
+ meta_test.attrs.get("ablation_setting")
493
+ if meta_test is not None else None
494
+ )
495
+
496
+ # T1 + Persistence: discover the close-feature index from train meta.
497
+ ctor_kwargs: dict[str, Any] = dict(extra_kwargs)
498
+ if task == "T1" and method_id == "persistence":
499
+ feat_names = meta_test.attrs.get("feature_names") or []
500
+ if "close" in feat_names:
501
+ ctor_kwargs["close_feature_idx"] = int(feat_names.index("close"))
502
+
503
+ # Ctor.
504
+ try:
505
+ model = cls(task=task, **ctor_kwargs)
506
+ except Exception as exc: # pragma: no cover -- defensive
507
+ return _make_failed_record(
508
+ method_id=method_id, method_family=method_family,
509
+ task=task, granularity=granularity, seed=seed,
510
+ status="fit_failed",
511
+ error=f"ctor: {_truncate_traceback(exc)}",
512
+ n_train=n_train, n_test=n_test,
513
+ hyperparams=ctor_kwargs, artifact_sha256=artifact_sha256,
514
+ deterministic_mode=deterministic,
515
+ ablation_setting=ablation_setting,
516
+ )
517
+
518
+ # For T1, derive horizon from y_test/y_train shape so the checkpoint path
519
+ # is horizon-specific. Without this, multiple horizons on the same
520
+ # (method, task, granularity, seed) tuple share one checkpoint dir; the
521
+ # first horizon's manifest gets loaded by every subsequent horizon and
522
+ # the runner silently emits wrong-shape predictions.
523
+ t1_horizon = None
524
+ if task == "T1":
525
+ try:
526
+ import numpy as _np # noqa: F401
527
+ y_ref = y_test if hasattr(y_test, "shape") else y_train
528
+ if hasattr(y_ref, "shape") and len(y_ref.shape) == 2:
529
+ t1_horizon = int(y_ref.shape[1])
530
+ except Exception:
531
+ t1_horizon = None
532
+ ckpt = _checkpoint_path(method_id, task, granularity, seed, horizon=t1_horizon)
533
+ manifest_path = ckpt / "manifest.json"
534
+
535
+ fit_time_sec: float | None = None
536
+ predict_time_sec: float | None = None
537
+ peak_mem_mb: float | None = None
538
+
539
+ # Fit (or load from checkpoint).
540
+ try:
541
+ if manifest_path.exists() and not no_checkpoint:
542
+ model = cls.load(ckpt) # type: ignore[attr-defined]
543
+ fit_time_sec = 0.0
544
+ # cls.load reconstructs state from disk and does NOT preserve
545
+ # injected runtime resources (the LLM-family engine, etc.).
546
+ # Re-attach any kwargs the runner originally injected so
547
+ # ``predict`` does not hit "no engine" failures on a checkpoint
548
+ # round-trip.
549
+ for k, v in ctor_kwargs.items():
550
+ if k in ("task",):
551
+ continue
552
+ setattr(model, k, v)
553
+ # Also propagate the X_train cache for LLM in-context fitting.
554
+ if method_family in _LLM_FAMILIES:
555
+ if hasattr(model, "_X_train"):
556
+ model._X_train = X_train
557
+ if hasattr(model, "_y_train"):
558
+ model._y_train = y_train
559
+ else:
560
+ tracemalloc.start()
561
+ t0 = time.perf_counter()
562
+ model.fit(X_train, y_train, seed=seed)
563
+ fit_time_sec = time.perf_counter() - t0
564
+ _, peak = tracemalloc.get_traced_memory()
565
+ tracemalloc.stop()
566
+ peak_mem_mb = peak / (1024.0 * 1024.0)
567
+ # Skip writing checkpoint state under ``--no-checkpoint`` —
568
+ # those files would never be loaded back (the load branch is
569
+ # gated on ``not no_checkpoint``) and just accumulate.
570
+ if not no_checkpoint:
571
+ try:
572
+ ckpt.mkdir(parents=True, exist_ok=True)
573
+ model.save(ckpt)
574
+ except Exception: # save failure is non-fatal for the run
575
+ logger.warning("checkpoint save failed for %s/%s/%s", method_id, task, seed)
576
+ except Exception as exc:
577
+ return _make_failed_record(
578
+ method_id=method_id, method_family=method_family,
579
+ task=task, granularity=granularity, seed=seed,
580
+ status="fit_failed",
581
+ error=_truncate_traceback(exc),
582
+ n_train=n_train, n_test=n_test,
583
+ hyperparams=model.hyperparams() if hasattr(model, "hyperparams") else ctor_kwargs,
584
+ artifact_sha256=artifact_sha256,
585
+ deterministic_mode=deterministic,
586
+ fit_time_sec=fit_time_sec, peak_mem_mb=peak_mem_mb,
587
+ ablation_setting=ablation_setting,
588
+ )
589
+
590
+ # Predict.
591
+ try:
592
+ t1 = time.perf_counter()
593
+ y_pred = model.predict(X_test)
594
+ predict_time_sec = time.perf_counter() - t1
595
+ # Save y_pred + y_test + meta to parquet/npz so eval can be RE-RUN
596
+ # later without re-doing the expensive predict step. One file per
597
+ # (method, task, seed, ablation_setting). Failures are non-fatal.
598
+ try:
599
+ import pickle
600
+ # Predictions are experimental outputs, not dataset content.
601
+ # Live alongside experiments/results/, not under data_small_caps/.
602
+ pred_dir = Path(__file__).parent / "predictions"
603
+ pred_dir.mkdir(parents=True, exist_ok=True)
604
+ tag = f"{method_id}_{task}_{granularity}_seed{seed}"
605
+ if task == "T1" and t1_horizon is not None:
606
+ tag += f"_h{t1_horizon}"
607
+ if ablation_setting:
608
+ tag += f"_set{ablation_setting}"
609
+ pred_path = pred_dir / f"{tag}.pkl"
610
+ tmp = pred_path.with_suffix(".pkl.tmp")
611
+ with open(tmp, "wb") as f:
612
+ pickle.dump({
613
+ "method_id": method_id, "task": task, "seed": seed,
614
+ "granularity": granularity,
615
+ "ablation_setting": ablation_setting,
616
+ "y_pred": y_pred,
617
+ "y_test": y_test,
618
+ "meta_test": meta_test,
619
+ "timestamp": _now_iso(),
620
+ }, f)
621
+ tmp.replace(pred_path)
622
+ except Exception:
623
+ logger.warning("save predictions failed for %s/%s", method_id, task)
624
+ except Exception as exc:
625
+ return _make_failed_record(
626
+ method_id=method_id, method_family=method_family,
627
+ task=task, granularity=granularity, seed=seed,
628
+ status="predict_failed",
629
+ error=_truncate_traceback(exc),
630
+ n_train=n_train, n_test=n_test,
631
+ hyperparams=model.hyperparams(), artifact_sha256=artifact_sha256,
632
+ deterministic_mode=deterministic,
633
+ fit_time_sec=fit_time_sec, peak_mem_mb=peak_mem_mb,
634
+ ablation_setting=ablation_setting,
635
+ )
636
+
637
+ # Score.
638
+ try:
639
+ # Cluster keys: ticker for T1/T2/T3/T5/T6, scenario_id for T4,
640
+ # address for T7. Loader ``meta`` always carries the right column.
641
+ if task == "T4":
642
+ cluster_keys = (
643
+ meta_test["scenario_id"].values
644
+ if "scenario_id" in meta_test.columns
645
+ else None
646
+ )
647
+ elif task == "T7":
648
+ cluster_keys = (
649
+ meta_test["address"].values
650
+ if "address" in meta_test.columns
651
+ else None
652
+ )
653
+ elif "ticker" in meta_test.columns:
654
+ cluster_keys = meta_test["ticker"].values
655
+ else:
656
+ cluster_keys = None
657
+
658
+ score_kwargs: dict[str, Any] = {"cluster_keys": cluster_keys}
659
+ if task == "T1" and "close_last" in meta_test.columns:
660
+ score_kwargs["close_last"] = meta_test["close_last"].values
661
+
662
+ metrics = ml.score(task, y_test, y_pred, **score_kwargs)
663
+ except Exception as exc:
664
+ return _make_failed_record(
665
+ method_id=method_id, method_family=method_family,
666
+ task=task, granularity=granularity, seed=seed,
667
+ status="score_failed",
668
+ error=_truncate_traceback(exc),
669
+ n_train=n_train, n_test=n_test,
670
+ hyperparams=model.hyperparams(), artifact_sha256=artifact_sha256,
671
+ deterministic_mode=deterministic,
672
+ fit_time_sec=fit_time_sec, predict_time_sec=predict_time_sec,
673
+ peak_mem_mb=peak_mem_mb,
674
+ ablation_setting=ablation_setting,
675
+ )
676
+
677
+ # If eval returned a primary metric of None (NaN-only signal — happens
678
+ # when an LLM emits non-canonical field names so the inner-join finds
679
+ # 0 valid (ticker, FY, field) tuples), surface the cell as
680
+ # ``score_failed`` rather than ``status=ok`` with a None metric. This
681
+ # keeps the no-silent-NaN rule honest at the runner level.
682
+ _PRIMARY_METRIC = {
683
+ "T1": "mse", "T2": "median_ape", "T3": "overall_mape",
684
+ "T4": "return_mae_pct", "T5": "median_ape", "T6": "overall_mape",
685
+ "T7": "rent_MAPE",
686
+ }
687
+ primary_key = _PRIMARY_METRIC.get(task)
688
+ primary_mv = (metrics or {}).get(primary_key) if primary_key else None
689
+ primary_value = (
690
+ primary_mv.value if primary_mv is not None
691
+ and hasattr(primary_mv, "value") else None
692
+ )
693
+ if primary_value is None:
694
+ return _make_failed_record(
695
+ method_id=method_id, method_family=method_family,
696
+ task=task, granularity=granularity, seed=seed,
697
+ status="score_failed",
698
+ error=(
699
+ f"primary metric '{primary_key}' is None on {task}; "
700
+ "predictions did not produce any valid (canonical) "
701
+ "match against y_true (e.g. all preds NaN, or non-canonical "
702
+ "field names). Refusing to record status=ok."
703
+ ),
704
+ n_train=n_train, n_test=n_test,
705
+ hyperparams=model.hyperparams(), artifact_sha256=artifact_sha256,
706
+ deterministic_mode=deterministic,
707
+ fit_time_sec=fit_time_sec, predict_time_sec=predict_time_sec,
708
+ peak_mem_mb=peak_mem_mb,
709
+ ablation_setting=ablation_setting,
710
+ )
711
+
712
+ # ── Per-task persistence/constant-floor sanity gate ─────────────────
713
+ # Blow-up guard: when a regression model's primary metric is
714
+ # >> the trivial-baseline floor on the same eval set it is emitting
715
+ # nonsense (e.g. T1 trained on raw close instead of log-returns —
716
+ # MSE 1e10-1e16; T2/T5 mis-scaled valuations; T4 wrong sign on
717
+ # returns; T7 unit-mixed rent/price). The gate covers T1, T2, T4,
718
+ # T5, T7. T3 / T6 are long-form per-field tasks whose floor is
719
+ # implicitly the SectorMedian baseline and are skipped here.
720
+ suspect_reason: str | None = _sanity_gate(
721
+ task, X_test, y_test, y_pred, y_train, meta_test,
722
+ )
723
+ if suspect_reason is not None:
724
+ logger.warning(suspect_reason)
725
+
726
+ return RunRecord(
727
+ method_id=method_id, method_family=method_family,
728
+ task=task, granularity=granularity, seed=seed,
729
+ status="ok", error=suspect_reason,
730
+ n_train=n_train, n_test=n_test,
731
+ hyperparams=model.hyperparams(),
732
+ lib_versions=model.lib_versions(),
733
+ hardware=_detect_hardware(),
734
+ fit_time_sec=fit_time_sec, predict_time_sec=predict_time_sec,
735
+ peak_mem_mb=peak_mem_mb, metrics=metrics,
736
+ artifact_sha256=artifact_sha256,
737
+ timestamp=_now_iso(), git_sha=_git_sha(),
738
+ deterministic_mode=deterministic,
739
+ ablation_setting=meta_test.attrs.get("ablation_setting") if meta_test is not None else None,
740
+ )
741
+
742
+
743
+ def _seed_dispatch(args_tuple: tuple) -> RunRecord:
744
+ """Process-pool entry point — unpack args and call :func:`_run_one`."""
745
+ return _run_one(**args_tuple)
746
+
747
+
748
+ # ── Public API ────────────────────────────────────────────────────────────
749
+
750
+
751
+ def run_all(
752
+ tasks: list[str],
753
+ methods_list: list[str],
754
+ granularity: str = "daily",
755
+ *,
756
+ seeds: Iterable[int] = (42,),
757
+ deterministic: bool = False,
758
+ no_checkpoint: bool = False,
759
+ multi_seed_parallel: bool = False,
760
+ config_overrides: dict[str, dict[str, Any]] | None = None,
761
+ output_path: Path | None = None,
762
+ setting: str | None = None,
763
+ horizon: int | None = None,
764
+ lookback: int | None = None,
765
+ ) -> list[RunRecord]:
766
+ """Run every (task, method, seed) cell and persist :class:`RunRecord` JSON.
767
+
768
+ Parameters
769
+ ----------
770
+ tasks
771
+ Task ids in ``{"T1","T2","T3","T4","T5","T6","T7"}``.
772
+ methods_list
773
+ Registry ids (matching ``ml.methods.ALL_METHODS`` keys).
774
+ granularity
775
+ ``"daily"`` (default) | ``"weekly"`` | ``"monthly"``.
776
+ seeds
777
+ Iterable of integer seeds. Default ``(42,)``.
778
+ deterministic
779
+ When True, set ``MACROLENS_DETERMINISTIC=1`` and call
780
+ ``torch.use_deterministic_algorithms(True)`` once before any
781
+ method runs.
782
+ no_checkpoint
783
+ When True, ignore any existing checkpoint and re-train; new
784
+ checkpoints are still written.
785
+ multi_seed_parallel
786
+ When True, dispatch one process per seed via
787
+ :class:`concurrent.futures.ProcessPoolExecutor`.
788
+ config_overrides
789
+ Mapping ``{method_id: {kwarg: value, ...}}`` forwarded to the
790
+ method ctor (single-step override path used by the runner-side
791
+ ``--config-override`` flag).
792
+ output_path
793
+ When supplied, write the JSON list to this exact path; otherwise
794
+ write to ``<data_root>/results/<git_sha>_<utc_timestamp>.json``.
795
+
796
+ Returns
797
+ -------
798
+ list[RunRecord]
799
+ Every emitted record (including ``status != "ok"`` failures and
800
+ deferred-LLM ``status == "skip"`` placeholders).
801
+ """
802
+ if deterministic:
803
+ os.environ["MACROLENS_DETERMINISTIC"] = "1"
804
+ try:
805
+ import torch # type: ignore
806
+ torch.use_deterministic_algorithms(True)
807
+ if hasattr(torch.backends, "cudnn"):
808
+ torch.backends.cudnn.deterministic = True
809
+ except Exception:
810
+ pass
811
+
812
+ overrides = config_overrides or {}
813
+ seed_list = list(seeds)
814
+ records: list[RunRecord] = []
815
+ adapter = pydantic.TypeAdapter(list[RunRecord])
816
+
817
+ # Resolve the output path eagerly so we can checkpoint after every cell.
818
+ if output_path is None:
819
+ ts = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
820
+ sha_short = _git_sha()[:8] if _git_sha() != "unknown" else "nogit"
821
+ # Experiment outputs live under experiments/, NOT under
822
+ # data_small_caps/ (raw + derived benchmark data only).
823
+ results_dir = Path(__file__).resolve().parent / "results"
824
+ results_dir.mkdir(parents=True, exist_ok=True)
825
+ output_path = results_dir / f"{sha_short}_{ts}.json"
826
+ else:
827
+ output_path = Path(output_path)
828
+ output_path.parent.mkdir(parents=True, exist_ok=True)
829
+
830
+ def _flush() -> None:
831
+ """Atomic-rename incremental write so a SIGTERM mid-run loses ~0 records."""
832
+ tmp = output_path.with_suffix(".json.tmp")
833
+ tmp.write_bytes(adapter.dump_json(records, indent=2))
834
+ tmp.replace(output_path)
835
+
836
+ def _log_cell(method_id: str, task_id: str, family: str, status: str,
837
+ fit_s: float | None, pred_s: float | None,
838
+ metrics: dict | None) -> None:
839
+ m_str = ""
840
+ if metrics:
841
+ primary_keys = ("mse", "mape", "median_ape", "return_mae_pct",
842
+ "rent_MAPE", "overall_mape", "n_predictions")
843
+ for k in primary_keys:
844
+ if k in metrics and hasattr(metrics[k], "value"):
845
+ v = metrics[k].value
846
+ m_str = f" {k}={'None' if v is None else f'{v:.4g}'}"
847
+ break
848
+ ft = f"{fit_s:.1f}s" if fit_s is not None else "-"
849
+ pt = f"{pred_s:.1f}s" if pred_s is not None else "-"
850
+ print(f" [{len(records):>3d}] {family:10s} {method_id:18s} {task_id} "
851
+ f"status={status:14s} fit={ft:>6s} predict={pt:>6s}{m_str}",
852
+ flush=True)
853
+
854
+ print(f"output_path={output_path}", flush=True)
855
+
856
+ if setting is not None:
857
+ valid = {"A", "B", "C", "D", "E"}
858
+ if setting not in valid:
859
+ raise ValueError(f"setting must be in {valid} or None, got {setting!r}")
860
+ print(f"ablation setting={setting}", flush=True)
861
+
862
+ for task in tasks:
863
+ print(f"\n=== task={task} === loading data...", flush=True)
864
+ t0 = time.perf_counter()
865
+ load_kwargs: dict[str, Any] = {"granularity": granularity}
866
+ if horizon is not None and task == "T1":
867
+ load_kwargs["horizon"] = horizon
868
+ if lookback is not None and task in ("T1", "T4"):
869
+ load_kwargs["lookback"] = lookback
870
+ if setting is not None:
871
+ if task in ("T3", "T6", "T7"):
872
+ print(f" skipping task={task} for ablation (not in ABLATION_TASKS)",
873
+ flush=True)
874
+ continue
875
+ load_kwargs["setting"] = setting
876
+ X_train, y_train, meta_train = ml.load(task, "train", **load_kwargs)
877
+ X_test, y_test, meta_test = ml.load(task, "test", **load_kwargs)
878
+ print(f" loaded in {time.perf_counter()-t0:.1f}s "
879
+ f"(n_train={len(X_train)}, n_test={len(X_test)})", flush=True)
880
+
881
+ for method_name in methods_list:
882
+ cls = ml.methods.ALL_METHODS.get(method_name)
883
+ if cls is None:
884
+ logger.warning("method '%s' not registered; skipping", method_name)
885
+ continue
886
+ if task not in cls.tasks:
887
+ continue # silent skip per plan
888
+
889
+ method_family = getattr(cls, "family", "unknown")
890
+ extra_kwargs = _apply_overrides(overrides, method_name)
891
+
892
+ # LLM/LLM-TS/LLM-FT families require an externally-managed vLLM
893
+ # HTTP endpoint. Missing endpoint is a hard error — fail loudly
894
+ # rather than emitting a silent placeholder.
895
+ if method_family in _LLM_FAMILIES:
896
+ engine, err = _resolve_llm_engine(method_name, cls)
897
+ if engine is None:
898
+ raise RuntimeError(
899
+ f"{method_name} requires an LLM endpoint but "
900
+ f"{_llm_endpoint_env_var(method_name)} is unset. "
901
+ f"Reason: {err}. Either serve the endpoint and set "
902
+ f"the env var, or omit this method from --method."
903
+ )
904
+ # Engine resolved — inject via the ctor kwarg path.
905
+ extra_kwargs = {**extra_kwargs, "engine": engine}
906
+
907
+ if multi_seed_parallel and len(seed_list) > 1:
908
+ payloads = [
909
+ {
910
+ "method_id": method_name, "cls": cls,
911
+ "task": task, "granularity": granularity, "seed": seed,
912
+ "X_train": X_train, "y_train": y_train, "meta_train": meta_train,
913
+ "X_test": X_test, "y_test": y_test, "meta_test": meta_test,
914
+ "no_checkpoint": no_checkpoint,
915
+ "deterministic": deterministic,
916
+ "extra_kwargs": extra_kwargs,
917
+ }
918
+ for seed in seed_list
919
+ ]
920
+ with ProcessPoolExecutor(max_workers=len(seed_list)) as ex:
921
+ futs = [ex.submit(_seed_dispatch, p) for p in payloads]
922
+ for fut in as_completed(futs):
923
+ rec = fut.result()
924
+ records.append(rec)
925
+ _log_cell(method_name, task, method_family, rec.status,
926
+ rec.fit_time_sec, rec.predict_time_sec,
927
+ rec.metrics)
928
+ _flush()
929
+ else:
930
+ for seed in seed_list:
931
+ rec = _run_one(
932
+ method_id=method_name, cls=cls,
933
+ task=task, granularity=granularity, seed=seed,
934
+ X_train=X_train, y_train=y_train, meta_train=meta_train,
935
+ X_test=X_test, y_test=y_test, meta_test=meta_test,
936
+ no_checkpoint=no_checkpoint,
937
+ deterministic=deterministic,
938
+ extra_kwargs=extra_kwargs,
939
+ )
940
+ records.append(rec)
941
+ _log_cell(method_name, task, method_family, rec.status,
942
+ rec.fit_time_sec, rec.predict_time_sec, rec.metrics)
943
+ _flush()
944
+
945
+ _flush()
946
+ logger.info("Wrote %d records to %s", len(records), output_path)
947
+ print(f"\n=== {len(records)} records written to {output_path} ===", flush=True)
948
+ return records
949
+
950
+
951
+ # ── CLI plumbing (kept here for `python -m experiments.run_all` callers) ──
952
+
953
+
954
+ def _parse_overrides(raw: list[str]) -> dict[str, dict[str, Any]]:
955
+ """Parse ``--config-override 'method.key=value'`` flags into a dict."""
956
+ overrides: dict[str, dict[str, Any]] = {}
957
+ for spec in raw:
958
+ if "=" not in spec or "." not in spec.split("=", 1)[0]:
959
+ raise ValueError(
960
+ f"--config-override expects 'method.key=value', got {spec!r}"
961
+ )
962
+ lhs, value = spec.split("=", 1)
963
+ method_id, key = lhs.split(".", 1)
964
+ # Coerce value: try int, then float, then bool, else str.
965
+ casted: Any = value
966
+ for caster in (int, float):
967
+ try:
968
+ casted = caster(value)
969
+ break
970
+ except ValueError:
971
+ continue
972
+ if isinstance(casted, str) and casted.lower() in ("true", "false"):
973
+ casted = casted.lower() == "true"
974
+ overrides.setdefault(method_id, {})[key] = casted
975
+ return overrides
976
+
977
+
978
+ def main(argv: list[str] | None = None) -> int:
979
+ parser = argparse.ArgumentParser(description=__doc__)
980
+ parser.add_argument("--task", nargs="+", required=True,
981
+ choices=["T1", "T2", "T3", "T4", "T5", "T6", "T7"])
982
+ parser.add_argument("--method", nargs="+", required=True,
983
+ help="Registry method ids (e.g. persistence lightgbm)")
984
+ parser.add_argument("--granularity", default="daily",
985
+ choices=["daily", "weekly", "monthly"])
986
+ parser.add_argument("--seeds", type=int, nargs="+", default=[42])
987
+ parser.add_argument("--deterministic", action="store_true")
988
+ parser.add_argument("--no-checkpoint", action="store_true")
989
+ parser.add_argument("--multi-seed-parallel", action="store_true")
990
+ parser.add_argument(
991
+ "--config-override", action="append", default=[],
992
+ help=("Override a single method ctor kwarg, e.g. "
993
+ "'lightgbm.n_estimators=20'. Repeatable."),
994
+ )
995
+ parser.add_argument("--output", type=Path, default=None,
996
+ help="Optional explicit output path.")
997
+ parser.add_argument(
998
+ "--setting", choices=["A", "B", "C", "D", "E"], default=None,
999
+ help=("Ablation feature-tier (A: OHLCV; B: +Fundamentals; "
1000
+ "C: +Macro; D: +Scenario flags; E: D + filing text in prompt). "
1001
+ "Applies to T1, T2, T4, T5 only; T3/T6/T7 silently skipped."),
1002
+ )
1003
+ parser.add_argument(
1004
+ "--horizon", type=int, default=None,
1005
+ help=("Forecast horizon for T1; ignored for T2-T7. Default: longest "
1006
+ "canonical horizon for the granularity "
1007
+ "(daily=252, weekly=52, monthly=12)."),
1008
+ )
1009
+ parser.add_argument(
1010
+ "--lookback", type=int, default=None,
1011
+ help=("Lookback window length for T1/T4; ignored for non-sequence "
1012
+ "tasks. Default: shortest canonical lookback for the granularity "
1013
+ "(daily=63, weekly=13, monthly=3). Use a longer value (e.g. "
1014
+ "monthly=12) for architectures whose downsample stack needs "
1015
+ "more timesteps."),
1016
+ )
1017
+ args = parser.parse_args(argv)
1018
+
1019
+ logging.basicConfig(
1020
+ level=logging.INFO,
1021
+ format="%(asctime)s %(levelname)s %(message)s",
1022
+ datefmt="%H:%M:%S",
1023
+ )
1024
+ overrides = _parse_overrides(args.config_override)
1025
+ run_all(
1026
+ tasks=args.task, methods_list=args.method,
1027
+ granularity=args.granularity, seeds=args.seeds,
1028
+ deterministic=args.deterministic,
1029
+ no_checkpoint=args.no_checkpoint,
1030
+ multi_seed_parallel=args.multi_seed_parallel,
1031
+ config_overrides=overrides,
1032
+ output_path=args.output,
1033
+ setting=args.setting,
1034
+ horizon=args.horizon,
1035
+ lookback=args.lookback,
1036
+ )
1037
+ return 0
1038
+
1039
+
1040
+ if __name__ == "__main__": # pragma: no cover
1041
+ sys.exit(main())
code/experiments/run_experiments.sh ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ==================================================================
3
+ # MacroLens: Full Experiment Launch Script (30-method panel)
4
+ # ==================================================================
5
+ # Runs the 28-method panel x 7 tasks x 3 granularities on 4x A100-40GB
6
+ # (physical GPU IDs 5,6,7,8). Other users keep 0-4 for themselves.
7
+ #
8
+ # Usage:
9
+ # # Quick validation (verify code works, ~4-8h)
10
+ # bash run_experiments.sh --quick
11
+ #
12
+ # # Full experiments (all granularities, ~3-5 days)
13
+ # bash run_experiments.sh --full
14
+ #
15
+ # # Single family
16
+ # bash run_experiments.sh --quick --family naive
17
+ # ==================================================================
18
+
19
+ set -euo pipefail
20
+
21
+ MODE="${1:---quick}"
22
+ FAMILY="${3:-all}"
23
+ LOG_DIR="/mnt/local/patara/experiment_logs"
24
+ mkdir -p "$LOG_DIR"
25
+ TIMESTAMP=$(date +%Y%m%d_%H%M%S)
26
+
27
+ # MacroLens-assigned physical GPU IDs. Single source of truth.
28
+ MACROLENS_GPUS="4,5,6,7"
29
+
30
+ # Parse mode
31
+ QUICK_FLAG=""
32
+ SEED_FLAGS=""
33
+ case "$MODE" in
34
+ --quick)
35
+ QUICK_FLAG="--quick"
36
+ echo "=== QUICK VALIDATION MODE ==="
37
+ ;;
38
+ --full)
39
+ # Single-seed primary per panel.PRIMARY_SEED; the headline-T1 multi-seed
40
+ # subset is driven inside the runner by panel.seeds_for().
41
+ SEED_FLAGS=""
42
+ echo "=== FULL EXPERIMENT MODE (single-seed primary) ==="
43
+ ;;
44
+ *)
45
+ echo "Usage: $0 [--quick|--full] [--family FAMILY]"
46
+ exit 1
47
+ ;;
48
+ esac
49
+
50
+ # Allow --family as $2
51
+ if [[ "${2:-}" == "--family" ]]; then
52
+ FAMILY="$3"
53
+ fi
54
+
55
+ run_family() {
56
+ local family=$1
57
+ local gpus=$2 # CUDA_VISIBLE_DEVICES string (physical IDs, e.g. "5,6,7,8")
58
+ local log="$LOG_DIR/${TIMESTAMP}_${family}.log"
59
+
60
+ echo "[$(date +%H:%M:%S)] Starting $family on GPUs $gpus -> $log"
61
+ CUDA_VISIBLE_DEVICES="$gpus" \
62
+ nohup uv run python -m projects.agent_builder.scripts.whatif_bench.baselines \
63
+ $QUICK_FLAG $SEED_FLAGS --family "$family" \
64
+ > "$log" 2>&1 &
65
+ echo " PID: $!"
66
+ }
67
+
68
+ # ==================================================================
69
+ # Batch 1: CPU-only families (no GPU)
70
+ # naive, classical, ablation classical arm - all CPU
71
+ # ==================================================================
72
+ run_batch_1() {
73
+ echo ""
74
+ echo "=== Batch 1: CPU families ==="
75
+ run_family "naive" ""
76
+ run_family "classical" ""
77
+ wait
78
+ echo "Batch 1 complete."
79
+ }
80
+
81
+ # ==================================================================
82
+ # Batch 2: Sequence + TSFM ZS + TSFM FT (share 4 GPUs)
83
+ # sequence -> 1 GPU (4)
84
+ # tsfm ZS -> 1 GPU (5)
85
+ # tsfm FT -> 2 GPUs (6,7)
86
+ # ==================================================================
87
+ run_batch_2() {
88
+ echo ""
89
+ echo "=== Batch 2: Sequence + TSFM ZS + TSFM FT ==="
90
+ run_family "sequence" "4"
91
+ run_family "tsfm" "5"
92
+ run_family "tsfm_ft" "6,7"
93
+ wait
94
+ echo "Batch 2 complete."
95
+ }
96
+
97
+ # ==================================================================
98
+ # Batch 3: LLM-TS Multi-Task (ChatTime, ITFormer, Time-MQA)
99
+ # Uses all 4 GPUs since each framework can benefit from parallel inference
100
+ # on the 7B backbone.
101
+ # ==================================================================
102
+ run_batch_3() {
103
+ echo ""
104
+ echo "=== Batch 3: LLM-TS Multi-Task ==="
105
+ run_family "llm_ts_reason" "$MACROLENS_GPUS"
106
+ wait
107
+ echo "Batch 3 complete."
108
+ }
109
+
110
+ # ==================================================================
111
+ # Batch 4: LLM ZS + FT (use all 4 GPUs; ZS first, then FT)
112
+ # Llama-4 Scout needs tensor-parallel 4 (all GPUs).
113
+ # Gemma-4 / EXAONE are TP=1 but run sequentially inside the runner.
114
+ # ==================================================================
115
+ run_batch_4() {
116
+ echo ""
117
+ echo "=== Batch 4: LLM ZS ==="
118
+ run_family "llm" "$MACROLENS_GPUS"
119
+ wait
120
+
121
+ echo "=== Batch 4: LLM FT (QLoRA NF4 + ZeRO-2) ==="
122
+ run_family "llm_ft" "$MACROLENS_GPUS"
123
+ wait
124
+ echo "Batch 4 complete."
125
+ }
126
+
127
+ # ==================================================================
128
+ # Ablation (5 settings x 5 models on T1 h=21 + T4)
129
+ # ==================================================================
130
+ run_ablation() {
131
+ echo ""
132
+ echo "=== Ablation (5x5 on T1 h=21 + T4) ==="
133
+ run_family "ablation" "$MACROLENS_GPUS"
134
+ wait
135
+ echo "Ablation complete."
136
+ }
137
+
138
+ # ==================================================================
139
+ # Multi-granularity (weekly + monthly, after daily completes)
140
+ # ==================================================================
141
+ run_multi_gran() {
142
+ echo ""
143
+ echo "=== Multi-granularity: weekly ==="
144
+ for family in naive classical sequence tsfm tsfm_ft llm_ts_reason llm llm_ft ablation; do
145
+ CUDA_VISIBLE_DEVICES="$MACROLENS_GPUS" \
146
+ uv run python -m projects.agent_builder.scripts.whatif_bench.baselines \
147
+ $QUICK_FLAG $SEED_FLAGS --family "$family" --granularity weekly \
148
+ >> "$LOG_DIR/${TIMESTAMP}_weekly.log" 2>&1
149
+ done
150
+
151
+ echo "=== Multi-granularity: monthly ==="
152
+ for family in naive classical sequence tsfm tsfm_ft llm_ts_reason llm llm_ft ablation; do
153
+ CUDA_VISIBLE_DEVICES="$MACROLENS_GPUS" \
154
+ uv run python -m projects.agent_builder.scripts.whatif_bench.baselines \
155
+ $QUICK_FLAG $SEED_FLAGS --family "$family" --granularity monthly \
156
+ >> "$LOG_DIR/${TIMESTAMP}_monthly.log" 2>&1
157
+ done
158
+ echo "Multi-granularity complete."
159
+ }
160
+
161
+ # ==================================================================
162
+ # Main
163
+ # ==================================================================
164
+ echo "MacroLens Experiments - $MODE (GPUs: $MACROLENS_GPUS)"
165
+ echo "Logs: $LOG_DIR/${TIMESTAMP}_*.log"
166
+ echo ""
167
+
168
+ if [[ "$FAMILY" != "all" ]]; then
169
+ run_family "$FAMILY" "$MACROLENS_GPUS"
170
+ wait
171
+ else
172
+ run_batch_1
173
+ run_batch_2
174
+ run_batch_3
175
+ run_batch_4
176
+ run_ablation
177
+
178
+ if [[ "$MODE" == "--full" ]]; then
179
+ run_multi_gran
180
+ fi
181
+ fi
182
+
183
+ echo ""
184
+ echo "=== ALL EXPERIMENTS COMPLETE ==="
185
+ echo "Results: data_small_caps/benchmark/daily/all_results*.json"
186
+ echo "Logs: $LOG_DIR/${TIMESTAMP}_*.log"
187
+
188
+ echo ""
189
+ echo "=== Generating LaTeX tables ==="
190
+ CUDA_VISIBLE_DEVICES="$MACROLENS_GPUS" \
191
+ uv run python -m projects.agent_builder.scripts.whatif_bench.baselines.gen_tables
192
+ echo "Tables saved."
code/generate_scenarios.py ADDED
@@ -0,0 +1,1746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer 3 – Step 9: Detect natural-experiment scenarios from raw macro data.
2
+
3
+ Reads raw CSVs from ``data/macro/`` (NOT the processed panel) and identifies
4
+ historically significant macro events. Scenarios are granularity-independent
5
+ calendar-date events.
6
+
7
+ Output: ``data/benchmark/{granularity}/scenarios.parquet``
8
+
9
+ Uses all available FRED series + EIA commodity data to detect 49 event types
10
+ covering rates, equity, commodities, FX, inflation, labor, credit, housing,
11
+ money supply, financial conditions, and cross-asset composite signals.
12
+ Short-term (5-day) and medium-term (21-day) windows are used for daily series.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from . import config
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ # ------------------------------------------------------------------
29
+ # Helpers
30
+ # ------------------------------------------------------------------
31
+
32
+ def _load_fred(series_id: str) -> pd.DataFrame:
33
+ """Load a single FRED CSV, returning (date, value) DataFrame."""
34
+ path = config.MACRO_DIR / f"fred_{series_id}.csv"
35
+ if not path.exists():
36
+ return pd.DataFrame(columns=["date", "value"])
37
+ df = pd.read_csv(path)
38
+ if "date" not in df.columns:
39
+ return pd.DataFrame(columns=["date", "value"])
40
+ df["date"] = pd.to_datetime(df["date"])
41
+ non_date = [c for c in df.columns if c != "date"]
42
+ if not non_date:
43
+ return pd.DataFrame(columns=["date", "value"])
44
+ val_col = series_id if series_id in df.columns else non_date[0]
45
+ df = df[["date", val_col]].rename(columns={val_col: "value"})
46
+ df["value"] = pd.to_numeric(df["value"], errors="coerce")
47
+ return df.dropna(subset=["value"]).sort_values("date").reset_index(drop=True)
48
+
49
+
50
+ def _load_commodity_spot(subdir: str, candidates: list[str]) -> pd.DataFrame:
51
+ """Load a commodity spot CSV from a macro subdirectory."""
52
+ commodity_dir = config.MACRO_DIR / subdir
53
+ if not commodity_dir.is_dir():
54
+ return pd.DataFrame(columns=["date", "value"])
55
+ for candidate in candidates:
56
+ path = commodity_dir / candidate
57
+ if not path.exists():
58
+ continue
59
+ df = pd.read_csv(path)
60
+ date_col = next((c for c in df.columns if "time" in c.lower() or "date" in c.lower()), None)
61
+ if date_col is None:
62
+ continue
63
+ num_cols = df.select_dtypes(include="number").columns.tolist()
64
+ val_col = next((c for c in df.columns if c != date_col and "spot" in c.lower()), None)
65
+ if val_col is None and num_cols:
66
+ val_col = num_cols[0]
67
+ if val_col is None:
68
+ continue
69
+ df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
70
+ df = df[[date_col, val_col]].rename(columns={date_col: "date", val_col: "value"})
71
+ df["value"] = pd.to_numeric(df["value"], errors="coerce")
72
+ return df.dropna(subset=["value"]).sort_values("date").reset_index(drop=True)
73
+ return pd.DataFrame(columns=["date", "value"])
74
+
75
+
76
+ def _load_crude_spot() -> pd.DataFrame:
77
+ return _load_commodity_spot("crude_oil", ["crude_spot_daily.csv"])
78
+
79
+
80
+ def _load_natgas_spot() -> pd.DataFrame:
81
+ return _load_commodity_spot("natural_gas", [
82
+ "natural_gas_spot_weekly.csv",
83
+ "natural_gas_spot_daily.csv",
84
+ ])
85
+
86
+
87
+ # ------------------------------------------------------------------
88
+ # Detectors
89
+ # ------------------------------------------------------------------
90
+
91
+ def _detect_fed_rate_changes(df: pd.DataFrame) -> list[dict]:
92
+ """Detect FEDFUNDS changes >= SCENARIO_FEDFUNDS_DELTA between consecutive observations."""
93
+ if df.empty:
94
+ return []
95
+ events = []
96
+ delta = config.SCENARIO_FEDFUNDS_DELTA
97
+ prev_val = df["value"].iloc[0]
98
+ for _, row in df.iloc[1:].iterrows():
99
+ change = row["value"] - prev_val
100
+ if abs(change) >= delta:
101
+ direction = "raised" if change > 0 else "lowered"
102
+ events.append({
103
+ "event_type": "fed_rate_change",
104
+ "event_date": row["date"],
105
+ "event_description": (
106
+ f"On {row['date'].date()}, the Fed {direction} rates by "
107
+ f"{abs(change)*100:.0f}bps to {row['value']:.2f}%."
108
+ ),
109
+ })
110
+ prev_val = row["value"]
111
+ return events
112
+
113
+
114
+ def _detect_vix_spikes(df: pd.DataFrame) -> list[dict]:
115
+ """Detect VIX > ratio * rolling mean."""
116
+ if len(df) < config.SCENARIO_VIX_ROLLING_WINDOW:
117
+ return []
118
+ events = []
119
+ ratio = config.SCENARIO_VIX_SPIKE_RATIO
120
+ window = config.SCENARIO_VIX_ROLLING_WINDOW
121
+ df = df.copy()
122
+ df["rolling_mean"] = df["value"].rolling(window, min_periods=window).mean()
123
+ df = df.dropna(subset=["rolling_mean"])
124
+ spike_mask = df["value"] > ratio * df["rolling_mean"]
125
+ # Group consecutive spike days; take the first day of each group
126
+ if spike_mask.any():
127
+ spike_idx = spike_mask[spike_mask].index
128
+ groups: list[list[int]] = []
129
+ current: list[int] = [spike_idx[0]]
130
+ for i in spike_idx[1:]:
131
+ if i == current[-1] + 1:
132
+ current.append(i)
133
+ else:
134
+ groups.append(current)
135
+ current = [i]
136
+ groups.append(current)
137
+ for g in groups:
138
+ row = df.loc[g[0]]
139
+ events.append({
140
+ "event_type": "vix_spike",
141
+ "event_date": row["date"],
142
+ "event_description": (
143
+ f"On {row['date'].date()}, VIX spiked to {row['value']:.1f} "
144
+ f"({row['value']/row['rolling_mean']:.1f}x its {window}-day average of "
145
+ f"{row['rolling_mean']:.1f})."
146
+ ),
147
+ })
148
+ return events
149
+
150
+
151
+ def _detect_oil_shocks(df: pd.DataFrame) -> list[dict]:
152
+ """Detect crude-oil moves >= threshold over rolling window."""
153
+ if len(df) < config.SCENARIO_OIL_ROLLING_WINDOW:
154
+ return []
155
+ events = []
156
+ window = config.SCENARIO_OIL_ROLLING_WINDOW
157
+ pct = config.SCENARIO_OIL_PCT_CHANGE
158
+ df = df.copy()
159
+ df["pct_change"] = df["value"].pct_change(periods=window)
160
+ large = df[df["pct_change"].abs() >= pct].copy()
161
+ if large.empty:
162
+ return events
163
+ # De-duplicate: keep events at least `window` days apart
164
+ prev_date = None
165
+ for _, row in large.iterrows():
166
+ if prev_date is not None and (row["date"] - prev_date).days < window:
167
+ continue
168
+ direction = "surged" if row["pct_change"] > 0 else "plunged"
169
+ events.append({
170
+ "event_type": "oil_shock",
171
+ "event_date": row["date"],
172
+ "event_description": (
173
+ f"On {row['date'].date()}, crude oil {direction} "
174
+ f"{abs(row['pct_change'])*100:.1f}% over the prior {window} trading days "
175
+ f"to ${row['value']:.2f}/bbl."
176
+ ),
177
+ })
178
+ prev_date = row["date"]
179
+ return events
180
+
181
+
182
+ def _detect_market_drawdowns(df: pd.DataFrame) -> list[dict]:
183
+ """Detect S&P 500 drops >= threshold over rolling window."""
184
+ if len(df) < config.SCENARIO_SP500_ROLLING_WINDOW:
185
+ return []
186
+ events = []
187
+ window = config.SCENARIO_SP500_ROLLING_WINDOW
188
+ pct = config.SCENARIO_SP500_DRAWDOWN
189
+ df = df.copy()
190
+ df["pct_change"] = df["value"].pct_change(periods=window)
191
+ drops = df[df["pct_change"] <= -pct].copy()
192
+ if drops.empty:
193
+ return events
194
+ prev_date = None
195
+ for _, row in drops.iterrows():
196
+ if prev_date is not None and (row["date"] - prev_date).days < window:
197
+ continue
198
+ events.append({
199
+ "event_type": "market_drawdown",
200
+ "event_date": row["date"],
201
+ "event_description": (
202
+ f"On {row['date'].date()}, the S&P 500 dropped "
203
+ f"{abs(row['pct_change'])*100:.1f}% over the prior {window} trading days "
204
+ f"to {row['value']:.0f}."
205
+ ),
206
+ })
207
+ prev_date = row["date"]
208
+ return events
209
+
210
+
211
+ def _detect_natgas_shocks(df: pd.DataFrame) -> list[dict]:
212
+ """Detect natural-gas spot moves >= threshold over rolling window."""
213
+ window = config.SCENARIO_NATGAS_ROLLING_WINDOW
214
+ if len(df) < window:
215
+ return []
216
+ pct = config.SCENARIO_NATGAS_PCT_CHANGE
217
+ df = df.copy()
218
+ df["pct_change"] = df["value"].pct_change(periods=window)
219
+ large = df[df["pct_change"].abs() >= pct].copy()
220
+ if large.empty:
221
+ return []
222
+ events = []
223
+ prev_date = None
224
+ for _, row in large.iterrows():
225
+ if prev_date is not None and (row["date"] - prev_date).days < window * 7:
226
+ continue
227
+ direction = "surged" if row["pct_change"] > 0 else "plunged"
228
+ events.append({
229
+ "event_type": "natgas_shock",
230
+ "event_date": row["date"],
231
+ "event_description": (
232
+ f"On {row['date'].date()}, natural gas {direction} "
233
+ f"{abs(row['pct_change'])*100:.1f}% over the prior {window} periods "
234
+ f"to ${row['value']:.2f}/MMBtu."
235
+ ),
236
+ })
237
+ prev_date = row["date"]
238
+ return events
239
+
240
+
241
+ def _detect_nasdaq_moves(df: pd.DataFrame) -> list[dict]:
242
+ """Detect NASDAQ large moves (crashes or rallies) over rolling window."""
243
+ window = config.SCENARIO_NASDAQ_ROLLING_WINDOW
244
+ if len(df) < window:
245
+ return []
246
+ pct = config.SCENARIO_NASDAQ_PCT_CHANGE
247
+ df = df.copy()
248
+ df["pct_change"] = df["value"].pct_change(periods=window)
249
+ large = df[df["pct_change"].abs() >= pct].copy()
250
+ if large.empty:
251
+ return []
252
+ events = []
253
+ prev_date = None
254
+ for _, row in large.iterrows():
255
+ if prev_date is not None and (row["date"] - prev_date).days < window:
256
+ continue
257
+ direction = "rallied" if row["pct_change"] > 0 else "dropped"
258
+ events.append({
259
+ "event_type": "nasdaq_move",
260
+ "event_date": row["date"],
261
+ "event_description": (
262
+ f"On {row['date'].date()}, the NASDAQ Composite {direction} "
263
+ f"{abs(row['pct_change'])*100:.1f}% over the prior {window} trading days "
264
+ f"to {row['value']:.0f}."
265
+ ),
266
+ })
267
+ prev_date = row["date"]
268
+ return events
269
+
270
+
271
+ def _detect_yield_curve_events(dgs10: pd.DataFrame, dgs2: pd.DataFrame) -> list[dict]:
272
+ """Detect yield curve inversions and steep re-steepening events."""
273
+ if dgs10.empty or dgs2.empty:
274
+ return []
275
+ merged = pd.merge(dgs10, dgs2, on="date", suffixes=("_10y", "_2y"))
276
+ if merged.empty:
277
+ return []
278
+ merged = merged.sort_values("date").reset_index(drop=True)
279
+ merged["spread"] = merged["value_10y"] - merged["value_2y"]
280
+
281
+ window = config.SCENARIO_YIELD_CURVE_WINDOW
282
+ events = []
283
+
284
+ # Detect inversions: spread crosses below 0
285
+ merged["prev_spread"] = merged["spread"].shift(1)
286
+ inversions = merged[
287
+ (merged["spread"] < config.SCENARIO_YIELD_CURVE_INVERSION) &
288
+ (merged["prev_spread"] >= config.SCENARIO_YIELD_CURVE_INVERSION)
289
+ ]
290
+ prev_date = None
291
+ for _, row in inversions.iterrows():
292
+ if prev_date is not None and (row["date"] - prev_date).days < window:
293
+ continue
294
+ events.append({
295
+ "event_type": "yield_curve_event",
296
+ "event_date": row["date"],
297
+ "event_description": (
298
+ f"On {row['date'].date()}, the yield curve inverted: "
299
+ f"10Y-2Y spread fell to {row['spread']*100:.0f}bps "
300
+ f"(10Y={row['value_10y']:.2f}%, 2Y={row['value_2y']:.2f}%)."
301
+ ),
302
+ })
303
+ prev_date = row["date"]
304
+
305
+ # Detect un-inversions: spread crosses back above 0
306
+ un_inversions = merged[
307
+ (merged["spread"] >= config.SCENARIO_YIELD_CURVE_INVERSION) &
308
+ (merged["prev_spread"] < config.SCENARIO_YIELD_CURVE_INVERSION)
309
+ ]
310
+ prev_date = None
311
+ for _, row in un_inversions.iterrows():
312
+ if prev_date is not None and (row["date"] - prev_date).days < window:
313
+ continue
314
+ events.append({
315
+ "event_type": "yield_curve_event",
316
+ "event_date": row["date"],
317
+ "event_description": (
318
+ f"On {row['date'].date()}, the yield curve un-inverted: "
319
+ f"10Y-2Y spread recovered to {row['spread']*100:.0f}bps "
320
+ f"(10Y={row['value_10y']:.2f}%, 2Y={row['value_2y']:.2f}%)."
321
+ ),
322
+ })
323
+ prev_date = row["date"]
324
+
325
+ # Detect large steepening/flattening moves
326
+ if len(merged) > window:
327
+ merged["spread_change"] = merged["spread"] - merged["spread"].shift(window)
328
+ threshold = config.SCENARIO_YIELD_CURVE_STEEPENING
329
+ large = merged[merged["spread_change"].abs() >= threshold].dropna(subset=["spread_change"])
330
+ prev_date = None
331
+ for _, row in large.iterrows():
332
+ if prev_date is not None and (row["date"] - prev_date).days < window:
333
+ continue
334
+ direction = "steepened" if row["spread_change"] > 0 else "flattened"
335
+ events.append({
336
+ "event_type": "yield_curve_event",
337
+ "event_date": row["date"],
338
+ "event_description": (
339
+ f"On {row['date'].date()}, the yield curve {direction} by "
340
+ f"{abs(row['spread_change'])*100:.0f}bps over {window} days: "
341
+ f"10Y-2Y spread at {row['spread']*100:.0f}bps."
342
+ ),
343
+ })
344
+ prev_date = row["date"]
345
+
346
+ return events
347
+
348
+
349
+ def _detect_treasury_rate_shocks(df: pd.DataFrame) -> list[dict]:
350
+ """Detect large moves in the 10-year Treasury yield."""
351
+ window = config.SCENARIO_DGS10_ROLLING_WINDOW
352
+ if len(df) < window:
353
+ return []
354
+ delta = config.SCENARIO_DGS10_DELTA
355
+ df = df.copy()
356
+ df["abs_change"] = df["value"] - df["value"].shift(window)
357
+ large = df[df["abs_change"].abs() >= delta].dropna(subset=["abs_change"])
358
+ if large.empty:
359
+ return []
360
+ events = []
361
+ prev_date = None
362
+ for _, row in large.iterrows():
363
+ if prev_date is not None and (row["date"] - prev_date).days < window:
364
+ continue
365
+ direction = "surged" if row["abs_change"] > 0 else "plunged"
366
+ events.append({
367
+ "event_type": "treasury_rate_shock",
368
+ "event_date": row["date"],
369
+ "event_description": (
370
+ f"On {row['date'].date()}, the 10-year Treasury yield {direction} "
371
+ f"{abs(row['abs_change'])*100:.0f}bps over {window} trading days "
372
+ f"to {row['value']:.2f}%."
373
+ ),
374
+ })
375
+ prev_date = row["date"]
376
+ return events
377
+
378
+
379
+ def _detect_usd_shocks(df: pd.DataFrame) -> list[dict]:
380
+ """Detect large moves in the trade-weighted USD index."""
381
+ window = config.SCENARIO_USD_ROLLING_WINDOW
382
+ if len(df) < window:
383
+ return []
384
+ pct = config.SCENARIO_USD_PCT_CHANGE
385
+ df = df.copy()
386
+ df["pct_change"] = df["value"].pct_change(periods=window)
387
+ large = df[df["pct_change"].abs() >= pct].copy()
388
+ if large.empty:
389
+ return []
390
+ events = []
391
+ prev_date = None
392
+ for _, row in large.iterrows():
393
+ if prev_date is not None and (row["date"] - prev_date).days < window:
394
+ continue
395
+ direction = "strengthened" if row["pct_change"] > 0 else "weakened"
396
+ events.append({
397
+ "event_type": "usd_shock",
398
+ "event_date": row["date"],
399
+ "event_description": (
400
+ f"On {row['date'].date()}, the trade-weighted USD {direction} "
401
+ f"{abs(row['pct_change'])*100:.1f}% over {window} trading days "
402
+ f"to {row['value']:.1f}."
403
+ ),
404
+ })
405
+ prev_date = row["date"]
406
+ return events
407
+
408
+
409
+ # ------------------------------------------------------------------
410
+ # Generic helpers for monthly / weekly series
411
+ # ------------------------------------------------------------------
412
+
413
+ def _detect_mom_change(df: pd.DataFrame, event_type: str, label: str,
414
+ threshold: float, unit: str = "", fmt: str = ".1f",
415
+ de_dup_days: int = 28) -> list[dict]:
416
+ """Generic month-over-month percentage change detector."""
417
+ if len(df) < 2:
418
+ return []
419
+ df = df.copy()
420
+ df["pct_change"] = df["value"].pct_change()
421
+ large = df[df["pct_change"].abs() >= threshold].dropna(subset=["pct_change"])
422
+ events = []
423
+ prev_date = None
424
+ for _, row in large.iterrows():
425
+ if prev_date is not None and (row["date"] - prev_date).days < de_dup_days:
426
+ continue
427
+ direction = "jumped" if row["pct_change"] > 0 else "dropped"
428
+ events.append({
429
+ "event_type": event_type,
430
+ "event_date": row["date"],
431
+ "event_description": (
432
+ f"On {row['date'].date()}, {label} {direction} "
433
+ f"{abs(row['pct_change'])*100:{fmt}}% month-over-month "
434
+ f"to {row['value']:{fmt}}{unit}."
435
+ ),
436
+ })
437
+ prev_date = row["date"]
438
+ return events
439
+
440
+
441
+ def _detect_level_change(df: pd.DataFrame, event_type: str, label: str,
442
+ delta: float, window: int, unit: str = "%",
443
+ de_dup_days: int | None = None) -> list[dict]:
444
+ """Generic absolute level change detector over a rolling window."""
445
+ if len(df) < window:
446
+ return []
447
+ de_dup = de_dup_days or window
448
+ df = df.copy()
449
+ df["abs_change"] = df["value"] - df["value"].shift(window)
450
+ large = df[df["abs_change"].abs() >= delta].dropna(subset=["abs_change"])
451
+ events = []
452
+ prev_date = None
453
+ for _, row in large.iterrows():
454
+ if prev_date is not None and (row["date"] - prev_date).days < de_dup:
455
+ continue
456
+ direction = "surged" if row["abs_change"] > 0 else "plunged"
457
+ events.append({
458
+ "event_type": event_type,
459
+ "event_date": row["date"],
460
+ "event_description": (
461
+ f"On {row['date'].date()}, {label} {direction} "
462
+ f"{abs(row['abs_change'])*100:.0f}bps over {window} periods "
463
+ f"to {row['value']:.2f}{unit}."
464
+ ),
465
+ })
466
+ prev_date = row["date"]
467
+ return events
468
+
469
+
470
+ def _detect_spike_ratio(df: pd.DataFrame, event_type: str, label: str,
471
+ ratio: float, window: int, unit: str = "",
472
+ de_dup_days: int | None = None) -> list[dict]:
473
+ """Generic spike detector: value > ratio * rolling mean."""
474
+ if len(df) < window:
475
+ return []
476
+ de_dup = de_dup_days or window * 7
477
+ df = df.copy()
478
+ df["rolling_mean"] = df["value"].rolling(window, min_periods=window).mean()
479
+ df = df.dropna(subset=["rolling_mean"])
480
+ spike_mask = df["value"] > ratio * df["rolling_mean"]
481
+ if not spike_mask.any():
482
+ return []
483
+ events = []
484
+ spike_df = df[spike_mask]
485
+ prev_date = None
486
+ for _, row in spike_df.iterrows():
487
+ if prev_date is not None and (row["date"] - prev_date).days < de_dup:
488
+ continue
489
+ events.append({
490
+ "event_type": event_type,
491
+ "event_date": row["date"],
492
+ "event_description": (
493
+ f"On {row['date'].date()}, {label} spiked to {row['value']:.0f}{unit} "
494
+ f"({row['value']/row['rolling_mean']:.1f}x its {window}-period average "
495
+ f"of {row['rolling_mean']:.0f}{unit})."
496
+ ),
497
+ })
498
+ prev_date = row["date"]
499
+ return events
500
+
501
+
502
+ # ------------------------------------------------------------------
503
+ # New detectors: inflation, labor, credit, housing, etc.
504
+ # ------------------------------------------------------------------
505
+
506
+ def _detect_cpi_shocks(df: pd.DataFrame) -> list[dict]:
507
+ """Detect large CPI month-over-month changes."""
508
+ return _detect_mom_change(df, "inflation_shock", "CPI",
509
+ config.SCENARIO_CPI_MOM_THRESHOLD, fmt=".2f")
510
+
511
+
512
+ def _detect_ppi_shocks(df: pd.DataFrame) -> list[dict]:
513
+ """Detect large PPI month-over-month changes."""
514
+ return _detect_mom_change(df, "ppi_shock", "PPI",
515
+ config.SCENARIO_PPI_MOM_THRESHOLD, fmt=".1f")
516
+
517
+
518
+ def _detect_unemployment_shocks(df: pd.DataFrame) -> list[dict]:
519
+ """Detect unemployment rate jumps."""
520
+ if len(df) < 2:
521
+ return []
522
+ df = df.copy()
523
+ df["change"] = df["value"].diff()
524
+ large = df[df["change"].abs() >= config.SCENARIO_UNRATE_DELTA].dropna(subset=["change"])
525
+ events = []
526
+ prev_date = None
527
+ for _, row in large.iterrows():
528
+ if prev_date is not None and (row["date"] - prev_date).days < 28:
529
+ continue
530
+ direction = "rose" if row["change"] > 0 else "fell"
531
+ events.append({
532
+ "event_type": "unemployment_shock",
533
+ "event_date": row["date"],
534
+ "event_description": (
535
+ f"On {row['date'].date()}, the unemployment rate {direction} "
536
+ f"{abs(row['change']):.1f}pp to {row['value']:.1f}%."
537
+ ),
538
+ })
539
+ prev_date = row["date"]
540
+ return events
541
+
542
+
543
+ def _detect_jobless_claims_spikes(df: pd.DataFrame) -> list[dict]:
544
+ """Detect spikes in initial jobless claims."""
545
+ return _detect_spike_ratio(df, "jobless_claims_spike", "initial jobless claims",
546
+ config.SCENARIO_ICSA_SPIKE_RATIO,
547
+ config.SCENARIO_ICSA_ROLLING_WINDOW,
548
+ unit="K", de_dup_days=28)
549
+
550
+
551
+ def _detect_payroll_shocks(df: pd.DataFrame) -> list[dict]:
552
+ """Detect large month-over-month changes in nonfarm payrolls."""
553
+ return _detect_mom_change(df, "payroll_shock", "nonfarm payrolls",
554
+ config.SCENARIO_PAYROLLS_DELTA, fmt=".1f")
555
+
556
+
557
+ def _detect_hy_spread_events(df: pd.DataFrame) -> list[dict]:
558
+ """Detect high-yield credit spread blow-outs."""
559
+ return _detect_level_change(df, "hy_spread_event", "the high-yield credit spread",
560
+ config.SCENARIO_HY_SPREAD_DELTA,
561
+ config.SCENARIO_HY_SPREAD_WINDOW)
562
+
563
+
564
+ def _detect_ig_spread_events(df: pd.DataFrame) -> list[dict]:
565
+ """Detect investment-grade corporate spread moves."""
566
+ return _detect_level_change(df, "ig_spread_event", "the IG corporate spread",
567
+ config.SCENARIO_IG_SPREAD_DELTA,
568
+ config.SCENARIO_IG_SPREAD_WINDOW)
569
+
570
+
571
+ def _detect_ted_spread_spikes(df: pd.DataFrame) -> list[dict]:
572
+ """Detect TED spread crossing above threshold."""
573
+ if df.empty:
574
+ return []
575
+ df = df.copy()
576
+ df["prev"] = df["value"].shift(1)
577
+ crossings = df[(df["value"] >= config.SCENARIO_TED_SPIKE) &
578
+ (df["prev"] < config.SCENARIO_TED_SPIKE)].dropna(subset=["prev"])
579
+ events = []
580
+ prev_date = None
581
+ for _, row in crossings.iterrows():
582
+ if prev_date is not None and (row["date"] - prev_date).days < 30:
583
+ continue
584
+ events.append({
585
+ "event_type": "ted_spread_spike",
586
+ "event_date": row["date"],
587
+ "event_description": (
588
+ f"On {row['date'].date()}, the TED spread spiked to "
589
+ f"{row['value']*100:.0f}bps, signaling interbank stress."
590
+ ),
591
+ })
592
+ prev_date = row["date"]
593
+ return events
594
+
595
+
596
+ def _detect_financial_stress(df: pd.DataFrame) -> list[dict]:
597
+ """Detect financial stress index exceeding threshold."""
598
+ if df.empty:
599
+ return []
600
+ threshold = config.SCENARIO_FSI_THRESHOLD
601
+ df = df.copy()
602
+ df["prev"] = df["value"].shift(1)
603
+ crossings = df[(df["value"] >= threshold) &
604
+ (df["prev"] < threshold)].dropna(subset=["prev"])
605
+ events = []
606
+ prev_date = None
607
+ for _, row in crossings.iterrows():
608
+ if prev_date is not None and (row["date"] - prev_date).days < 60:
609
+ continue
610
+ events.append({
611
+ "event_type": "financial_stress",
612
+ "event_date": row["date"],
613
+ "event_description": (
614
+ f"On {row['date'].date()}, the St. Louis Fed Financial Stress Index "
615
+ f"rose to {row['value']:.2f}, indicating elevated systemic stress."
616
+ ),
617
+ })
618
+ prev_date = row["date"]
619
+ return events
620
+
621
+
622
+ def _detect_mortgage_rate_shocks(df: pd.DataFrame) -> list[dict]:
623
+ """Detect large moves in 30-year mortgage rates."""
624
+ return _detect_level_change(df, "mortgage_rate_shock", "the 30-year mortgage rate",
625
+ config.SCENARIO_MORTGAGE_DELTA,
626
+ config.SCENARIO_MORTGAGE_ROLLING_WINDOW)
627
+
628
+
629
+ def _detect_sentiment_shocks(df: pd.DataFrame) -> list[dict]:
630
+ """Detect large drops in consumer sentiment."""
631
+ if len(df) < config.SCENARIO_SENTIMENT_ROLLING_WINDOW + 1:
632
+ return []
633
+ df = df.copy()
634
+ w = config.SCENARIO_SENTIMENT_ROLLING_WINDOW
635
+ df["pct_change"] = df["value"].pct_change(periods=w)
636
+ large = df[df["pct_change"].abs() >= config.SCENARIO_SENTIMENT_PCT_CHANGE].dropna(subset=["pct_change"])
637
+ events = []
638
+ prev_date = None
639
+ for _, row in large.iterrows():
640
+ if prev_date is not None and (row["date"] - prev_date).days < 28:
641
+ continue
642
+ direction = "surged" if row["pct_change"] > 0 else "plunged"
643
+ events.append({
644
+ "event_type": "sentiment_shock",
645
+ "event_date": row["date"],
646
+ "event_description": (
647
+ f"On {row['date'].date()}, U. of Michigan Consumer Sentiment {direction} "
648
+ f"{abs(row['pct_change'])*100:.1f}% to {row['value']:.1f}."
649
+ ),
650
+ })
651
+ prev_date = row["date"]
652
+ return events
653
+
654
+
655
+ def _detect_industrial_production_shocks(df: pd.DataFrame) -> list[dict]:
656
+ """Detect large changes in industrial production."""
657
+ return _detect_mom_change(df, "industrial_production_shock", "industrial production",
658
+ config.SCENARIO_INDPRO_PCT_CHANGE, fmt=".1f")
659
+
660
+
661
+ def _detect_retail_sales_shocks(df: pd.DataFrame) -> list[dict]:
662
+ """Detect large changes in retail sales."""
663
+ return _detect_mom_change(df, "retail_sales_shock", "retail sales",
664
+ config.SCENARIO_RETAIL_PCT_CHANGE,
665
+ unit="B", fmt=".0f")
666
+
667
+
668
+ def _detect_housing_starts_shocks(df: pd.DataFrame) -> list[dict]:
669
+ """Detect large changes in housing starts."""
670
+ return _detect_mom_change(df, "housing_starts_shock", "housing starts",
671
+ config.SCENARIO_HOUSING_PCT_CHANGE, fmt=".0f",
672
+ de_dup_days=28)
673
+
674
+
675
+ def _detect_home_price_events(df: pd.DataFrame) -> list[dict]:
676
+ """Detect Case-Shiller home price acceleration/deceleration."""
677
+ if len(df) < 13:
678
+ return []
679
+ df = df.copy()
680
+ df["yoy"] = df["value"].pct_change(periods=12)
681
+ df["yoy_change"] = df["yoy"] - df["yoy"].shift(3)
682
+ large = df[df["yoy_change"].abs() >= config.SCENARIO_HOME_PRICE_YOY_DELTA].dropna(subset=["yoy_change"])
683
+ events = []
684
+ prev_date = None
685
+ for _, row in large.iterrows():
686
+ if prev_date is not None and (row["date"] - prev_date).days < 60:
687
+ continue
688
+ direction = "accelerated" if row["yoy_change"] > 0 else "decelerated"
689
+ events.append({
690
+ "event_type": "home_price_event",
691
+ "event_date": row["date"],
692
+ "event_description": (
693
+ f"On {row['date'].date()}, U.S. home price growth {direction}: "
694
+ f"YoY rate shifted {row['yoy_change']*100:+.1f}pp to "
695
+ f"{row['yoy']*100:.1f}% (Case-Shiller index at {row['value']:.1f})."
696
+ ),
697
+ })
698
+ prev_date = row["date"]
699
+ return events
700
+
701
+
702
+ def _detect_m2_events(df: pd.DataFrame) -> list[dict]:
703
+ """Detect M2 money supply contraction or surge."""
704
+ if len(df) < 13:
705
+ return []
706
+ df = df.copy()
707
+ df["yoy"] = df["value"].pct_change(periods=12)
708
+ events = []
709
+ prev_date = None
710
+ # Detect contraction
711
+ contracting = df[df["yoy"] <= config.SCENARIO_M2_YOY_THRESHOLD].dropna(subset=["yoy"])
712
+ for _, row in contracting.iterrows():
713
+ if prev_date is not None and (row["date"] - prev_date).days < 60:
714
+ continue
715
+ events.append({
716
+ "event_type": "m2_contraction",
717
+ "event_date": row["date"],
718
+ "event_description": (
719
+ f"On {row['date'].date()}, M2 money supply contracted "
720
+ f"{abs(row['yoy'])*100:.1f}% year-over-year to "
721
+ f"${row['value']/1e6:.2f}T, a rare monetary tightening signal."
722
+ ),
723
+ })
724
+ prev_date = row["date"]
725
+ # Detect surges (>10% YoY)
726
+ prev_date = None
727
+ surging = df[df["yoy"] >= 0.10].dropna(subset=["yoy"])
728
+ for _, row in surging.iterrows():
729
+ if prev_date is not None and (row["date"] - prev_date).days < 60:
730
+ continue
731
+ events.append({
732
+ "event_type": "m2_surge",
733
+ "event_date": row["date"],
734
+ "event_description": (
735
+ f"On {row['date'].date()}, M2 money supply surged "
736
+ f"{row['yoy']*100:.1f}% year-over-year to "
737
+ f"${row['value']/1e6:.2f}T, signaling aggressive monetary expansion."
738
+ ),
739
+ })
740
+ prev_date = row["date"]
741
+ return events
742
+
743
+
744
+ def _detect_dgs30_shocks(df: pd.DataFrame) -> list[dict]:
745
+ """Detect large moves in the 30-year Treasury yield."""
746
+ return _detect_level_change(df, "long_bond_shock", "the 30-year Treasury yield",
747
+ config.SCENARIO_DGS30_DELTA,
748
+ config.SCENARIO_DGS30_ROLLING_WINDOW)
749
+
750
+
751
+ def _detect_sp_nasdaq_divergence(sp: pd.DataFrame, nq: pd.DataFrame) -> list[dict]:
752
+ """Detect S&P 500 vs NASDAQ divergence (sector rotation signals)."""
753
+ if sp.empty or nq.empty:
754
+ return []
755
+ merged = pd.merge(sp, nq, on="date", suffixes=("_sp", "_nq")).sort_values("date")
756
+ if len(merged) < config.SCENARIO_SP_NASDAQ_WINDOW:
757
+ return []
758
+ w = config.SCENARIO_SP_NASDAQ_WINDOW
759
+ merged["sp_ret"] = merged["value_sp"].pct_change(periods=w)
760
+ merged["nq_ret"] = merged["value_nq"].pct_change(periods=w)
761
+ merged["divergence"] = merged["nq_ret"] - merged["sp_ret"]
762
+ large = merged[merged["divergence"].abs() >= config.SCENARIO_SP_NASDAQ_DIVERGENCE].dropna(subset=["divergence"])
763
+ events = []
764
+ prev_date = None
765
+ for _, row in large.iterrows():
766
+ if prev_date is not None and (row["date"] - prev_date).days < w:
767
+ continue
768
+ if row["divergence"] > 0:
769
+ desc = f"NASDAQ outperformed S&P 500 by {row['divergence']*100:.1f}pp"
770
+ else:
771
+ desc = f"NASDAQ underperformed S&P 500 by {abs(row['divergence'])*100:.1f}pp"
772
+ events.append({
773
+ "event_type": "sector_rotation",
774
+ "event_date": row["date"],
775
+ "event_description": (
776
+ f"On {row['date'].date()}, {desc} over {w} trading days "
777
+ f"(NASDAQ {row['nq_ret']*100:+.1f}% vs S&P {row['sp_ret']*100:+.1f}%), "
778
+ f"signaling sector rotation."
779
+ ),
780
+ })
781
+ prev_date = row["date"]
782
+ return events
783
+
784
+
785
+ def _detect_vix_regime_change(df: pd.DataFrame) -> list[dict]:
786
+ """Detect sustained elevated VIX (regime change)."""
787
+ if df.empty:
788
+ return []
789
+ threshold = config.SCENARIO_VIX_REGIME_THRESHOLD
790
+ min_days = config.SCENARIO_VIX_REGIME_MIN_DAYS
791
+ df = df.copy()
792
+ df["elevated"] = df["value"] >= threshold
793
+ events = []
794
+ in_regime = False
795
+ start_date = None
796
+ for _, row in df.iterrows():
797
+ if row["elevated"] and not in_regime:
798
+ in_regime = True
799
+ start_date = row["date"]
800
+ elif not row["elevated"] and in_regime:
801
+ duration = (row["date"] - start_date).days
802
+ if duration >= min_days:
803
+ events.append({
804
+ "event_type": "volatility_regime",
805
+ "event_date": start_date,
806
+ "event_description": (
807
+ f"Starting {start_date.date()}, VIX remained above "
808
+ f"{threshold:.0f} for {duration} consecutive days, "
809
+ f"indicating a sustained high-volatility regime."
810
+ ),
811
+ })
812
+ in_regime = False
813
+ # Handle ongoing regime at end of data
814
+ if in_regime and start_date is not None:
815
+ duration = (df["date"].iloc[-1] - start_date).days
816
+ if duration >= min_days:
817
+ events.append({
818
+ "event_type": "volatility_regime",
819
+ "event_date": start_date,
820
+ "event_description": (
821
+ f"Starting {start_date.date()}, VIX remained above "
822
+ f"{threshold:.0f} for {duration}+ days (ongoing), "
823
+ f"indicating a sustained high-volatility regime."
824
+ ),
825
+ })
826
+ return events
827
+
828
+
829
+ def _detect_yield_curve_3m10y(df: pd.DataFrame) -> list[dict]:
830
+ """Detect 10Y-3M yield curve inversions (classic recession signal)."""
831
+ if df.empty:
832
+ return []
833
+ df = df.copy()
834
+ df["prev"] = df["value"].shift(1)
835
+ events = []
836
+ # Inversion: spread crosses below 0
837
+ inversions = df[(df["value"] < 0) & (df["prev"] >= 0)].dropna(subset=["prev"])
838
+ prev_date = None
839
+ for _, row in inversions.iterrows():
840
+ if prev_date is not None and (row["date"] - prev_date).days < 60:
841
+ continue
842
+ events.append({
843
+ "event_type": "yield_curve_3m10y_inversion",
844
+ "event_date": row["date"],
845
+ "event_description": (
846
+ f"On {row['date'].date()}, the 10Y-3M yield curve inverted to "
847
+ f"{row['value']*100:.0f}bps — a classic recession warning signal."
848
+ ),
849
+ })
850
+ prev_date = row["date"]
851
+ # Un-inversion
852
+ un_inversions = df[(df["value"] >= 0) & (df["prev"] < 0)].dropna(subset=["prev"])
853
+ prev_date = None
854
+ for _, row in un_inversions.iterrows():
855
+ if prev_date is not None and (row["date"] - prev_date).days < 60:
856
+ continue
857
+ events.append({
858
+ "event_type": "yield_curve_3m10y_uninversion",
859
+ "event_date": row["date"],
860
+ "event_description": (
861
+ f"On {row['date'].date()}, the 10Y-3M yield curve un-inverted to "
862
+ f"{row['value']*100:.0f}bps after a period of inversion."
863
+ ),
864
+ })
865
+ prev_date = row["date"]
866
+ return events
867
+
868
+
869
+ # ------------------------------------------------------------------
870
+ # NEW: FX, DJIA, breakeven inflation, JOLTS, earnings, vehicles,
871
+ # permits, existing home sales, NFCI, Fed balance sheet,
872
+ # monetary base, business loans, PCE inflation, SOFR,
873
+ # WTI oil (FRED), Henry Hub gas (FRED),
874
+ # cross-asset composites, and short-term shock windows
875
+ # ------------------------------------------------------------------
876
+
877
+ def _detect_fx_shocks(df: pd.DataFrame, pair_name: str) -> list[dict]:
878
+ """Detect large moves in an FX pair."""
879
+ window = config.SCENARIO_FX_ROLLING_WINDOW
880
+ if len(df) < window:
881
+ return []
882
+ pct = config.SCENARIO_FX_PCT_CHANGE
883
+ df = df.copy()
884
+ df["pct_change"] = df["value"].pct_change(periods=window)
885
+ large = df[df["pct_change"].abs() >= pct].copy()
886
+ if large.empty:
887
+ return []
888
+ events = []
889
+ prev_date = None
890
+ for _, row in large.iterrows():
891
+ if prev_date is not None and (row["date"] - prev_date).days < window:
892
+ continue
893
+ direction = "strengthened" if row["pct_change"] > 0 else "weakened"
894
+ events.append({
895
+ "event_type": "fx_shock",
896
+ "event_date": row["date"],
897
+ "event_description": (
898
+ f"On {row['date'].date()}, {pair_name} {direction} "
899
+ f"{abs(row['pct_change'])*100:.1f}% over {window} trading days "
900
+ f"to {row['value']:.4f}."
901
+ ),
902
+ })
903
+ prev_date = row["date"]
904
+ return events
905
+
906
+
907
+ def _detect_breakeven_inflation_shocks(df: pd.DataFrame, tenor: str) -> list[dict]:
908
+ """Detect large moves in breakeven inflation rates."""
909
+ return _detect_level_change(
910
+ df, "breakeven_inflation_shock",
911
+ f"the {tenor} breakeven inflation rate",
912
+ config.SCENARIO_BEI_DELTA, config.SCENARIO_BEI_ROLLING_WINDOW,
913
+ )
914
+
915
+
916
+ def _detect_djia_moves(df: pd.DataFrame) -> list[dict]:
917
+ """Detect DJIA large moves over rolling window."""
918
+ window = config.SCENARIO_DJIA_ROLLING_WINDOW
919
+ if len(df) < window:
920
+ return []
921
+ pct = config.SCENARIO_DJIA_PCT_CHANGE
922
+ df = df.copy()
923
+ df["pct_change"] = df["value"].pct_change(periods=window)
924
+ large = df[df["pct_change"].abs() >= pct].copy()
925
+ if large.empty:
926
+ return []
927
+ events = []
928
+ prev_date = None
929
+ for _, row in large.iterrows():
930
+ if prev_date is not None and (row["date"] - prev_date).days < window:
931
+ continue
932
+ direction = "rallied" if row["pct_change"] > 0 else "dropped"
933
+ events.append({
934
+ "event_type": "djia_move",
935
+ "event_date": row["date"],
936
+ "event_description": (
937
+ f"On {row['date'].date()}, the DJIA {direction} "
938
+ f"{abs(row['pct_change'])*100:.1f}% over {window} trading days "
939
+ f"to {row['value']:.0f}."
940
+ ),
941
+ })
942
+ prev_date = row["date"]
943
+ return events
944
+
945
+
946
+ def _detect_jolts_shocks(df: pd.DataFrame) -> list[dict]:
947
+ """Detect large month-over-month changes in JOLTS job openings."""
948
+ return _detect_mom_change(df, "jolts_shock", "JOLTS job openings",
949
+ config.SCENARIO_JOLTS_PCT_CHANGE,
950
+ unit="K", fmt=".0f",
951
+ de_dup_days=config.SCENARIO_JOLTS_DEDUP_DAYS)
952
+
953
+
954
+ def _detect_earnings_shocks(df: pd.DataFrame) -> list[dict]:
955
+ """Detect large month-over-month changes in average hourly earnings."""
956
+ return _detect_mom_change(df, "earnings_shock", "average hourly earnings",
957
+ config.SCENARIO_EARNINGS_MOM_THRESHOLD,
958
+ unit="$/hr", fmt=".2f")
959
+
960
+
961
+ def _detect_vehicle_sales_shocks(df: pd.DataFrame) -> list[dict]:
962
+ """Detect large month-over-month changes in total vehicle sales."""
963
+ return _detect_mom_change(df, "vehicle_sales_shock", "total vehicle sales",
964
+ config.SCENARIO_VEHICLE_PCT_CHANGE,
965
+ unit="M", fmt=".1f")
966
+
967
+
968
+ def _detect_permit_shocks(df: pd.DataFrame) -> list[dict]:
969
+ """Detect large month-over-month changes in building permits."""
970
+ return _detect_mom_change(df, "building_permit_shock", "building permits",
971
+ config.SCENARIO_PERMIT_PCT_CHANGE,
972
+ unit="K", fmt=".0f")
973
+
974
+
975
+ def _detect_existing_home_sales_shocks(df: pd.DataFrame) -> list[dict]:
976
+ """Detect large month-over-month changes in existing home sales."""
977
+ return _detect_mom_change(df, "existing_home_sales_shock", "existing home sales",
978
+ config.SCENARIO_EXISTING_HOME_SALES_PCT,
979
+ unit="K", fmt=".0f")
980
+
981
+
982
+ def _detect_nfci_events(df: pd.DataFrame) -> list[dict]:
983
+ """Detect Chicago Fed NFCI crossing above 0 (tighter than average)."""
984
+ if df.empty:
985
+ return []
986
+ threshold = config.SCENARIO_NFCI_THRESHOLD
987
+ df = df.copy()
988
+ df["prev"] = df["value"].shift(1)
989
+ # Tightening: crosses above threshold
990
+ crossings_up = df[(df["value"] >= threshold) &
991
+ (df["prev"] < threshold)].dropna(subset=["prev"])
992
+ # Loosening: crosses back below from above
993
+ crossings_down = df[(df["value"] < threshold) &
994
+ (df["prev"] >= threshold)].dropna(subset=["prev"])
995
+ events = []
996
+ prev_date = None
997
+ for _, row in crossings_up.iterrows():
998
+ if prev_date is not None and (row["date"] - prev_date).days < 30:
999
+ continue
1000
+ events.append({
1001
+ "event_type": "nfci_tightening",
1002
+ "event_date": row["date"],
1003
+ "event_description": (
1004
+ f"On {row['date'].date()}, the Chicago Fed NFCI rose to "
1005
+ f"{row['value']:.3f}, crossing above 0 — signaling tighter-than-average "
1006
+ f"financial conditions."
1007
+ ),
1008
+ })
1009
+ prev_date = row["date"]
1010
+ prev_date = None
1011
+ for _, row in crossings_down.iterrows():
1012
+ if prev_date is not None and (row["date"] - prev_date).days < 30:
1013
+ continue
1014
+ events.append({
1015
+ "event_type": "nfci_loosening",
1016
+ "event_date": row["date"],
1017
+ "event_description": (
1018
+ f"On {row['date'].date()}, the Chicago Fed NFCI fell to "
1019
+ f"{row['value']:.3f}, crossing below 0 — signaling easing "
1020
+ f"financial conditions."
1021
+ ),
1022
+ })
1023
+ prev_date = row["date"]
1024
+ return events
1025
+
1026
+
1027
+ def _detect_fed_balance_sheet_events(df: pd.DataFrame) -> list[dict]:
1028
+ """Detect large changes in Fed balance sheet (WALCL)."""
1029
+ window = config.SCENARIO_FED_BS_ROLLING_WINDOW
1030
+ if len(df) < window:
1031
+ return []
1032
+ pct = config.SCENARIO_FED_BS_PCT_CHANGE
1033
+ df = df.copy()
1034
+ df["pct_change"] = df["value"].pct_change(periods=window)
1035
+ large = df[df["pct_change"].abs() >= pct].dropna(subset=["pct_change"])
1036
+ events = []
1037
+ prev_date = None
1038
+ for _, row in large.iterrows():
1039
+ if prev_date is not None and (row["date"] - prev_date).days < window * 7:
1040
+ continue
1041
+ direction = "expanded" if row["pct_change"] > 0 else "contracted"
1042
+ events.append({
1043
+ "event_type": "fed_balance_sheet",
1044
+ "event_date": row["date"],
1045
+ "event_description": (
1046
+ f"On {row['date'].date()}, the Fed balance sheet {direction} "
1047
+ f"{abs(row['pct_change'])*100:.1f}% over {window} weeks "
1048
+ f"to ${row['value']/1e6:.2f}T."
1049
+ ),
1050
+ })
1051
+ prev_date = row["date"]
1052
+ return events
1053
+
1054
+
1055
+ def _detect_monetary_base_shocks(df: pd.DataFrame) -> list[dict]:
1056
+ """Detect large month-over-month changes in the monetary base."""
1057
+ return _detect_mom_change(df, "monetary_base_shock", "the monetary base",
1058
+ config.SCENARIO_MONETARY_BASE_PCT,
1059
+ unit="B", fmt=".0f")
1060
+
1061
+
1062
+ def _detect_business_loan_shocks(df: pd.DataFrame) -> list[dict]:
1063
+ """Detect large month-over-month changes in C&I loans."""
1064
+ return _detect_mom_change(df, "business_loan_shock", "C&I loans",
1065
+ config.SCENARIO_BUSLOANS_PCT_CHANGE,
1066
+ unit="B", fmt=".0f")
1067
+
1068
+
1069
+ def _detect_pce_inflation_shocks(df: pd.DataFrame) -> list[dict]:
1070
+ """Detect large month-over-month changes in PCE price index."""
1071
+ return _detect_mom_change(df, "pce_inflation_shock", "PCE price index",
1072
+ config.SCENARIO_PCEPI_MOM_THRESHOLD,
1073
+ fmt=".2f")
1074
+
1075
+
1076
+ def _detect_sofr_shocks(df: pd.DataFrame) -> list[dict]:
1077
+ """Detect large moves in SOFR rate."""
1078
+ return _detect_level_change(df, "sofr_shock", "the SOFR rate",
1079
+ config.SCENARIO_SOFR_DELTA,
1080
+ config.SCENARIO_SOFR_WINDOW)
1081
+
1082
+
1083
+ def _detect_wti_oil_shocks(df: pd.DataFrame) -> list[dict]:
1084
+ """Detect WTI oil shocks from FRED daily data (DCOILWTICO)."""
1085
+ window = config.SCENARIO_OIL_ROLLING_WINDOW
1086
+ if len(df) < window:
1087
+ return []
1088
+ pct = config.SCENARIO_OIL_PCT_CHANGE
1089
+ df = df.copy()
1090
+ df["pct_change"] = df["value"].pct_change(periods=window)
1091
+ large = df[df["pct_change"].abs() >= pct].copy()
1092
+ if large.empty:
1093
+ return []
1094
+ events = []
1095
+ prev_date = None
1096
+ for _, row in large.iterrows():
1097
+ if prev_date is not None and (row["date"] - prev_date).days < window:
1098
+ continue
1099
+ direction = "surged" if row["pct_change"] > 0 else "plunged"
1100
+ events.append({
1101
+ "event_type": "wti_oil_shock",
1102
+ "event_date": row["date"],
1103
+ "event_description": (
1104
+ f"On {row['date'].date()}, WTI crude oil {direction} "
1105
+ f"{abs(row['pct_change'])*100:.1f}% over {window} trading days "
1106
+ f"to ${row['value']:.2f}/bbl."
1107
+ ),
1108
+ })
1109
+ prev_date = row["date"]
1110
+ return events
1111
+
1112
+
1113
+ def _detect_henry_hub_shocks(df: pd.DataFrame) -> list[dict]:
1114
+ """Detect Henry Hub natural gas shocks from FRED daily data (DHHNGSP)."""
1115
+ window = config.SCENARIO_OIL_ROLLING_WINDOW # reuse same window size
1116
+ if len(df) < window:
1117
+ return []
1118
+ pct = config.SCENARIO_NATGAS_PCT_CHANGE
1119
+ df = df.copy()
1120
+ df["pct_change"] = df["value"].pct_change(periods=window)
1121
+ large = df[df["pct_change"].abs() >= pct].copy()
1122
+ if large.empty:
1123
+ return []
1124
+ events = []
1125
+ prev_date = None
1126
+ for _, row in large.iterrows():
1127
+ if prev_date is not None and (row["date"] - prev_date).days < window:
1128
+ continue
1129
+ direction = "surged" if row["pct_change"] > 0 else "plunged"
1130
+ events.append({
1131
+ "event_type": "henry_hub_shock",
1132
+ "event_date": row["date"],
1133
+ "event_description": (
1134
+ f"On {row['date'].date()}, Henry Hub natural gas {direction} "
1135
+ f"{abs(row['pct_change'])*100:.1f}% over {window} trading days "
1136
+ f"to ${row['value']:.2f}/MMBtu."
1137
+ ),
1138
+ })
1139
+ prev_date = row["date"]
1140
+ return events
1141
+
1142
+
1143
+ # ------------------------------------------------------------------
1144
+ # Cross-asset composite detectors
1145
+ # ------------------------------------------------------------------
1146
+
1147
+ def _detect_real_yield_shocks(dgs10: pd.DataFrame, bei: pd.DataFrame) -> list[dict]:
1148
+ """Detect real yield (DGS10 - T10YIE) large moves."""
1149
+ if dgs10.empty or bei.empty:
1150
+ return []
1151
+ merged = pd.merge(dgs10, bei, on="date", suffixes=("_nom", "_bei")).sort_values("date")
1152
+ if merged.empty:
1153
+ return []
1154
+ merged["real_yield"] = merged["value_nom"] - merged["value_bei"]
1155
+ window = config.SCENARIO_REAL_YIELD_WINDOW
1156
+ if len(merged) < window:
1157
+ return []
1158
+ merged["change"] = merged["real_yield"] - merged["real_yield"].shift(window)
1159
+ delta = config.SCENARIO_REAL_YIELD_DELTA
1160
+ large = merged[merged["change"].abs() >= delta].dropna(subset=["change"])
1161
+ events = []
1162
+ prev_date = None
1163
+ for _, row in large.iterrows():
1164
+ if prev_date is not None and (row["date"] - prev_date).days < window:
1165
+ continue
1166
+ direction = "surged" if row["change"] > 0 else "plunged"
1167
+ events.append({
1168
+ "event_type": "real_yield_shock",
1169
+ "event_date": row["date"],
1170
+ "event_description": (
1171
+ f"On {row['date'].date()}, the real yield (10Y nominal - breakeven) "
1172
+ f"{direction} {abs(row['change'])*100:.0f}bps over {window} days "
1173
+ f"to {row['real_yield']:.2f}%."
1174
+ ),
1175
+ })
1176
+ prev_date = row["date"]
1177
+ return events
1178
+
1179
+
1180
+ def _detect_credit_compression(hy: pd.DataFrame, ig: pd.DataFrame) -> list[dict]:
1181
+ """Detect credit compression/expansion (HY spread - IG spread)."""
1182
+ if hy.empty or ig.empty:
1183
+ return []
1184
+ merged = pd.merge(hy, ig, on="date", suffixes=("_hy", "_ig")).sort_values("date")
1185
+ if merged.empty:
1186
+ return []
1187
+ merged["gap"] = merged["value_hy"] - merged["value_ig"]
1188
+ window = config.SCENARIO_CREDIT_COMPRESSION_WINDOW
1189
+ if len(merged) < window:
1190
+ return []
1191
+ merged["change"] = merged["gap"] - merged["gap"].shift(window)
1192
+ delta = config.SCENARIO_CREDIT_COMPRESSION_DELTA
1193
+ large = merged[merged["change"].abs() >= delta].dropna(subset=["change"])
1194
+ events = []
1195
+ prev_date = None
1196
+ for _, row in large.iterrows():
1197
+ if prev_date is not None and (row["date"] - prev_date).days < window:
1198
+ continue
1199
+ if row["change"] > 0:
1200
+ desc = "widened (risk aversion)"
1201
+ else:
1202
+ desc = "compressed (risk appetite)"
1203
+ events.append({
1204
+ "event_type": "credit_compression",
1205
+ "event_date": row["date"],
1206
+ "event_description": (
1207
+ f"On {row['date'].date()}, the HY-IG credit spread gap {desc} "
1208
+ f"by {abs(row['change'])*100:.0f}bps over {window} days "
1209
+ f"to {row['gap']*100:.0f}bps."
1210
+ ),
1211
+ })
1212
+ prev_date = row["date"]
1213
+ return events
1214
+
1215
+
1216
+ def _detect_term_premium_shocks(dgs30: pd.DataFrame, dgs2: pd.DataFrame) -> list[dict]:
1217
+ """Detect term premium (DGS30 - DGS2) large moves."""
1218
+ if dgs30.empty or dgs2.empty:
1219
+ return []
1220
+ merged = pd.merge(dgs30, dgs2, on="date", suffixes=("_30", "_2")).sort_values("date")
1221
+ if merged.empty:
1222
+ return []
1223
+ merged["spread"] = merged["value_30"] - merged["value_2"]
1224
+ window = config.SCENARIO_TERM_PREMIUM_WINDOW
1225
+ if len(merged) < window:
1226
+ return []
1227
+ merged["change"] = merged["spread"] - merged["spread"].shift(window)
1228
+ delta = config.SCENARIO_TERM_PREMIUM_DELTA
1229
+ large = merged[merged["change"].abs() >= delta].dropna(subset=["change"])
1230
+ events = []
1231
+ prev_date = None
1232
+ for _, row in large.iterrows():
1233
+ if prev_date is not None and (row["date"] - prev_date).days < window:
1234
+ continue
1235
+ direction = "steepened" if row["change"] > 0 else "flattened"
1236
+ events.append({
1237
+ "event_type": "term_premium_shock",
1238
+ "event_date": row["date"],
1239
+ "event_description": (
1240
+ f"On {row['date'].date()}, the 30Y-2Y term premium {direction} "
1241
+ f"by {abs(row['change'])*100:.0f}bps over {window} days "
1242
+ f"to {row['spread']*100:.0f}bps "
1243
+ f"(30Y={row['value_30']:.2f}%, 2Y={row['value_2']:.2f}%)."
1244
+ ),
1245
+ })
1246
+ prev_date = row["date"]
1247
+ return events
1248
+
1249
+
1250
+ # ------------------------------------------------------------------
1251
+ # Short-term (5-day) shock detectors for daily series
1252
+ # ------------------------------------------------------------------
1253
+
1254
+ def _detect_short_term_shocks(df: pd.DataFrame, event_type: str, label: str,
1255
+ pct_threshold: float, window: int,
1256
+ unit: str = "", fmt: str = ".0f") -> list[dict]:
1257
+ """Generic short-term percentage shock detector."""
1258
+ if len(df) < window:
1259
+ return []
1260
+ df = df.copy()
1261
+ df["pct_change"] = df["value"].pct_change(periods=window)
1262
+ large = df[df["pct_change"].abs() >= pct_threshold].copy()
1263
+ if large.empty:
1264
+ return []
1265
+ events = []
1266
+ prev_date = None
1267
+ for _, row in large.iterrows():
1268
+ if prev_date is not None and (row["date"] - prev_date).days < window * 2:
1269
+ continue
1270
+ direction = "surged" if row["pct_change"] > 0 else "plunged"
1271
+ events.append({
1272
+ "event_type": event_type,
1273
+ "event_date": row["date"],
1274
+ "event_description": (
1275
+ f"On {row['date'].date()}, {label} {direction} "
1276
+ f"{abs(row['pct_change'])*100:.1f}% over just {window} trading days "
1277
+ f"to {row['value']:{fmt}}{unit} — an acute short-term shock."
1278
+ ),
1279
+ })
1280
+ prev_date = row["date"]
1281
+ return events
1282
+
1283
+
1284
+ def _detect_short_term_level_shocks(df: pd.DataFrame, event_type: str, label: str,
1285
+ delta: float, window: int,
1286
+ unit: str = "%") -> list[dict]:
1287
+ """Generic short-term absolute-level shock detector."""
1288
+ if len(df) < window:
1289
+ return []
1290
+ df = df.copy()
1291
+ df["change"] = df["value"] - df["value"].shift(window)
1292
+ large = df[df["change"].abs() >= delta].dropna(subset=["change"])
1293
+ if large.empty:
1294
+ return []
1295
+ events = []
1296
+ prev_date = None
1297
+ for _, row in large.iterrows():
1298
+ if prev_date is not None and (row["date"] - prev_date).days < window * 2:
1299
+ continue
1300
+ direction = "surged" if row["change"] > 0 else "plunged"
1301
+ events.append({
1302
+ "event_type": event_type,
1303
+ "event_date": row["date"],
1304
+ "event_description": (
1305
+ f"On {row['date'].date()}, {label} {direction} "
1306
+ f"{abs(row['change'])*100:.0f}bps over just {window} trading days "
1307
+ f"to {row['value']:.2f}{unit} — a rapid rate move."
1308
+ ),
1309
+ })
1310
+ prev_date = row["date"]
1311
+ return events
1312
+
1313
+
1314
+ # ------------------------------------------------------------------
1315
+ # Public API
1316
+ # ------------------------------------------------------------------
1317
+
1318
+ def run(granularity: str | None = None) -> pd.DataFrame:
1319
+ """Detect all scenario events and save to benchmark directory.
1320
+
1321
+ Returns the scenarios DataFrame.
1322
+ """
1323
+ if granularity is None:
1324
+ granularity = config.GRANULARITY
1325
+
1326
+ out_dir = config.DATA_DIR / "benchmark" / granularity
1327
+ out_dir.mkdir(parents=True, exist_ok=True)
1328
+
1329
+ all_events: list[dict] = []
1330
+
1331
+ # Fed rate changes
1332
+ fed = _load_fred("FEDFUNDS")
1333
+ fed_events = _detect_fed_rate_changes(fed)
1334
+ all_events.extend(fed_events)
1335
+ logger.info("Fed rate changes: %d events.", len(fed_events))
1336
+
1337
+ # VIX spikes
1338
+ vix = _load_fred("VIXCLS")
1339
+ vix_events = _detect_vix_spikes(vix)
1340
+ all_events.extend(vix_events)
1341
+ logger.info("VIX spikes: %d events.", len(vix_events))
1342
+
1343
+ # Oil shocks
1344
+ crude = _load_crude_spot()
1345
+ if not crude.empty:
1346
+ oil_events = _detect_oil_shocks(crude)
1347
+ all_events.extend(oil_events)
1348
+ logger.info("Oil shocks: %d events.", len(oil_events))
1349
+ else:
1350
+ logger.warning("No crude oil spot data available; skipping oil shock detection.")
1351
+
1352
+ # Natural gas shocks
1353
+ natgas = _load_natgas_spot()
1354
+ if not natgas.empty:
1355
+ ng_events = _detect_natgas_shocks(natgas)
1356
+ all_events.extend(ng_events)
1357
+ logger.info("Natural gas shocks: %d events.", len(ng_events))
1358
+ else:
1359
+ logger.warning("No natural gas spot data available; skipping.")
1360
+
1361
+ # Market drawdowns (S&P 500)
1362
+ sp500 = _load_fred("SP500")
1363
+ dd_events = _detect_market_drawdowns(sp500)
1364
+ all_events.extend(dd_events)
1365
+ logger.info("Market drawdowns: %d events.", len(dd_events))
1366
+
1367
+ # NASDAQ large moves
1368
+ nasdaq = _load_fred("NASDAQCOM")
1369
+ nasdaq_events = _detect_nasdaq_moves(nasdaq)
1370
+ all_events.extend(nasdaq_events)
1371
+ logger.info("NASDAQ moves: %d events.", len(nasdaq_events))
1372
+
1373
+ # Yield curve events (DGS10 - DGS2)
1374
+ dgs10 = _load_fred("DGS10")
1375
+ dgs2 = _load_fred("DGS2")
1376
+ yc_events = _detect_yield_curve_events(dgs10, dgs2)
1377
+ all_events.extend(yc_events)
1378
+ logger.info("Yield curve events: %d events.", len(yc_events))
1379
+
1380
+ # Treasury rate shocks (10-year yield)
1381
+ tr_events = _detect_treasury_rate_shocks(dgs10)
1382
+ all_events.extend(tr_events)
1383
+ logger.info("Treasury rate shocks: %d events.", len(tr_events))
1384
+
1385
+ # USD index shocks
1386
+ usd = _load_fred("DTWEXBGS")
1387
+ usd_events = _detect_usd_shocks(usd)
1388
+ all_events.extend(usd_events)
1389
+ logger.info("USD shocks: %d events.", len(usd_events))
1390
+
1391
+ # 30-year Treasury shocks
1392
+ dgs30 = _load_fred("DGS30")
1393
+ if not dgs30.empty:
1394
+ dgs30_events = _detect_dgs30_shocks(dgs30)
1395
+ all_events.extend(dgs30_events)
1396
+ logger.info("30Y Treasury shocks: %d events.", len(dgs30_events))
1397
+
1398
+ # CPI inflation shocks
1399
+ cpi = _load_fred("CPIAUCSL")
1400
+ if not cpi.empty:
1401
+ cpi_events = _detect_cpi_shocks(cpi)
1402
+ all_events.extend(cpi_events)
1403
+ logger.info("CPI inflation shocks: %d events.", len(cpi_events))
1404
+
1405
+ # PPI shocks
1406
+ ppi = _load_fred("PPIACO")
1407
+ if not ppi.empty:
1408
+ ppi_events = _detect_ppi_shocks(ppi)
1409
+ all_events.extend(ppi_events)
1410
+ logger.info("PPI shocks: %d events.", len(ppi_events))
1411
+
1412
+ # Unemployment shocks
1413
+ unrate = _load_fred("UNRATE")
1414
+ if not unrate.empty:
1415
+ un_events = _detect_unemployment_shocks(unrate)
1416
+ all_events.extend(un_events)
1417
+ logger.info("Unemployment shocks: %d events.", len(un_events))
1418
+
1419
+ # Jobless claims spikes
1420
+ icsa = _load_fred("ICSA")
1421
+ if not icsa.empty:
1422
+ icsa_events = _detect_jobless_claims_spikes(icsa)
1423
+ all_events.extend(icsa_events)
1424
+ logger.info("Jobless claims spikes: %d events.", len(icsa_events))
1425
+
1426
+ # Payroll shocks
1427
+ payems = _load_fred("PAYEMS")
1428
+ if not payems.empty:
1429
+ pay_events = _detect_payroll_shocks(payems)
1430
+ all_events.extend(pay_events)
1431
+ logger.info("Payroll shocks: %d events.", len(pay_events))
1432
+
1433
+ # High-yield credit spread
1434
+ hy = _load_fred("BAMLH0A0HYM2")
1435
+ if not hy.empty:
1436
+ hy_events = _detect_hy_spread_events(hy)
1437
+ all_events.extend(hy_events)
1438
+ logger.info("HY spread events: %d events.", len(hy_events))
1439
+
1440
+ # IG corporate spread
1441
+ ig = _load_fred("BAMLC0A0CM")
1442
+ if not ig.empty:
1443
+ ig_events = _detect_ig_spread_events(ig)
1444
+ all_events.extend(ig_events)
1445
+ logger.info("IG spread events: %d events.", len(ig_events))
1446
+
1447
+ # TED spread spikes
1448
+ ted = _load_fred("TEDRATE")
1449
+ if not ted.empty:
1450
+ ted_events = _detect_ted_spread_spikes(ted)
1451
+ all_events.extend(ted_events)
1452
+ logger.info("TED spread spikes: %d events.", len(ted_events))
1453
+
1454
+ # Financial stress index
1455
+ fsi = _load_fred("STLFSI2")
1456
+ if not fsi.empty:
1457
+ fsi_events = _detect_financial_stress(fsi)
1458
+ all_events.extend(fsi_events)
1459
+ logger.info("Financial stress events: %d events.", len(fsi_events))
1460
+
1461
+ # Mortgage rate shocks
1462
+ mort = _load_fred("MORTGAGE30US")
1463
+ if not mort.empty:
1464
+ mort_events = _detect_mortgage_rate_shocks(mort)
1465
+ all_events.extend(mort_events)
1466
+ logger.info("Mortgage rate shocks: %d events.", len(mort_events))
1467
+
1468
+ # Consumer sentiment shocks
1469
+ sent = _load_fred("UMCSENT")
1470
+ if not sent.empty:
1471
+ sent_events = _detect_sentiment_shocks(sent)
1472
+ all_events.extend(sent_events)
1473
+ logger.info("Sentiment shocks: %d events.", len(sent_events))
1474
+
1475
+ # Industrial production shocks
1476
+ indpro = _load_fred("INDPRO")
1477
+ if not indpro.empty:
1478
+ ip_events = _detect_industrial_production_shocks(indpro)
1479
+ all_events.extend(ip_events)
1480
+ logger.info("Industrial production shocks: %d events.", len(ip_events))
1481
+
1482
+ # Retail sales shocks
1483
+ retail = _load_fred("RSAFS")
1484
+ if not retail.empty:
1485
+ rs_events = _detect_retail_sales_shocks(retail)
1486
+ all_events.extend(rs_events)
1487
+ logger.info("Retail sales shocks: %d events.", len(rs_events))
1488
+
1489
+ # Housing starts shocks
1490
+ houst = _load_fred("HOUST")
1491
+ if not houst.empty:
1492
+ hs_events = _detect_housing_starts_shocks(houst)
1493
+ all_events.extend(hs_events)
1494
+ logger.info("Housing starts shocks: %d events.", len(hs_events))
1495
+
1496
+ # Home price events
1497
+ cshpi = _load_fred("CSUSHPISA")
1498
+ if not cshpi.empty:
1499
+ hp_events = _detect_home_price_events(cshpi)
1500
+ all_events.extend(hp_events)
1501
+ logger.info("Home price events: %d events.", len(hp_events))
1502
+
1503
+ # M2 money supply events
1504
+ m2 = _load_fred("M2SL")
1505
+ if not m2.empty:
1506
+ m2_events = _detect_m2_events(m2)
1507
+ all_events.extend(m2_events)
1508
+ logger.info("M2 money supply events: %d events.", len(m2_events))
1509
+
1510
+ # S&P vs NASDAQ divergence (sector rotation)
1511
+ if not sp500.empty and not nasdaq.empty:
1512
+ div_events = _detect_sp_nasdaq_divergence(sp500, nasdaq)
1513
+ all_events.extend(div_events)
1514
+ logger.info("Sector rotation events: %d events.", len(div_events))
1515
+
1516
+ # VIX regime changes
1517
+ if not vix.empty:
1518
+ regime_events = _detect_vix_regime_change(vix)
1519
+ all_events.extend(regime_events)
1520
+ logger.info("Volatility regime events: %d events.", len(regime_events))
1521
+
1522
+ # 10Y-3M yield curve (T10Y3M) — direct spread from FRED
1523
+ t10y3m = _load_fred("T10Y3M")
1524
+ if not t10y3m.empty:
1525
+ yc3m_events = _detect_yield_curve_3m10y(t10y3m)
1526
+ all_events.extend(yc3m_events)
1527
+ logger.info("Yield curve 3M-10Y events: %d events.", len(yc3m_events))
1528
+
1529
+ # ── NEW: DJIA large moves ──
1530
+ djia = _load_fred("DJIA")
1531
+ if not djia.empty:
1532
+ djia_events = _detect_djia_moves(djia)
1533
+ all_events.extend(djia_events)
1534
+ logger.info("DJIA moves: %d events.", len(djia_events))
1535
+
1536
+ # ── NEW: WTI crude oil from FRED daily ──
1537
+ wti = _load_fred("DCOILWTICO")
1538
+ if not wti.empty:
1539
+ wti_events = _detect_wti_oil_shocks(wti)
1540
+ all_events.extend(wti_events)
1541
+ logger.info("WTI oil shocks (FRED): %d events.", len(wti_events))
1542
+
1543
+ # ── NEW: Henry Hub natural gas from FRED daily ──
1544
+ hh = _load_fred("DHHNGSP")
1545
+ if not hh.empty:
1546
+ hh_events = _detect_henry_hub_shocks(hh)
1547
+ all_events.extend(hh_events)
1548
+ logger.info("Henry Hub gas shocks (FRED): %d events.", len(hh_events))
1549
+
1550
+ # ── NEW: FX pair shocks ──
1551
+ for series_id, pair_name in [
1552
+ ("DEXUSEU", "USD/EUR"), ("DEXJPUS", "JPY/USD"),
1553
+ ("DEXUSUK", "USD/GBP"), ("DEXCHUS", "CNY/USD"),
1554
+ ]:
1555
+ fx = _load_fred(series_id)
1556
+ if not fx.empty:
1557
+ fx_events = _detect_fx_shocks(fx, pair_name)
1558
+ all_events.extend(fx_events)
1559
+ logger.info("FX shocks (%s): %d events.", pair_name, len(fx_events))
1560
+
1561
+ # ── NEW: Breakeven inflation shocks ──
1562
+ for series_id, tenor in [("T10YIE", "10-year"), ("T5YIE", "5-year")]:
1563
+ bei = _load_fred(series_id)
1564
+ if not bei.empty:
1565
+ bei_events = _detect_breakeven_inflation_shocks(bei, tenor)
1566
+ all_events.extend(bei_events)
1567
+ logger.info("Breakeven inflation (%s): %d events.", tenor, len(bei_events))
1568
+
1569
+ # ── NEW: PCE inflation ──
1570
+ pcepi = _load_fred("PCEPI")
1571
+ if not pcepi.empty:
1572
+ pce_events = _detect_pce_inflation_shocks(pcepi)
1573
+ all_events.extend(pce_events)
1574
+ logger.info("PCE inflation shocks: %d events.", len(pce_events))
1575
+
1576
+ # ── NEW: SOFR rate shocks ──
1577
+ sofr = _load_fred("SOFR")
1578
+ if not sofr.empty:
1579
+ sofr_events = _detect_sofr_shocks(sofr)
1580
+ all_events.extend(sofr_events)
1581
+ logger.info("SOFR shocks: %d events.", len(sofr_events))
1582
+
1583
+ # ── NEW: JOLTS job openings ──
1584
+ jolts = _load_fred("JTSJOL")
1585
+ if not jolts.empty:
1586
+ jolts_events = _detect_jolts_shocks(jolts)
1587
+ all_events.extend(jolts_events)
1588
+ logger.info("JOLTS shocks: %d events.", len(jolts_events))
1589
+
1590
+ # ── NEW: Average hourly earnings ──
1591
+ earnings = _load_fred("CES0500000003")
1592
+ if not earnings.empty:
1593
+ earn_events = _detect_earnings_shocks(earnings)
1594
+ all_events.extend(earn_events)
1595
+ logger.info("Earnings shocks: %d events.", len(earn_events))
1596
+
1597
+ # ── NEW: Total vehicle sales ──
1598
+ vehicles = _load_fred("TOTALSA")
1599
+ if not vehicles.empty:
1600
+ veh_events = _detect_vehicle_sales_shocks(vehicles)
1601
+ all_events.extend(veh_events)
1602
+ logger.info("Vehicle sales shocks: %d events.", len(veh_events))
1603
+
1604
+ # ── NEW: Building permits ──
1605
+ permits = _load_fred("PERMIT")
1606
+ if not permits.empty:
1607
+ perm_events = _detect_permit_shocks(permits)
1608
+ all_events.extend(perm_events)
1609
+ logger.info("Building permit shocks: %d events.", len(perm_events))
1610
+
1611
+ # ── NEW: Existing home sales ──
1612
+ ehs = _load_fred("EXHOSLUSM495S")
1613
+ if not ehs.empty:
1614
+ ehs_events = _detect_existing_home_sales_shocks(ehs)
1615
+ all_events.extend(ehs_events)
1616
+ logger.info("Existing home sales shocks: %d events.", len(ehs_events))
1617
+
1618
+ # ── NEW: Chicago Fed NFCI ──
1619
+ nfci = _load_fred("NFCI")
1620
+ if not nfci.empty:
1621
+ nfci_events = _detect_nfci_events(nfci)
1622
+ all_events.extend(nfci_events)
1623
+ logger.info("NFCI events: %d events.", len(nfci_events))
1624
+
1625
+ # ── NEW: Fed balance sheet ──
1626
+ walcl = _load_fred("WALCL")
1627
+ if not walcl.empty:
1628
+ bs_events = _detect_fed_balance_sheet_events(walcl)
1629
+ all_events.extend(bs_events)
1630
+ logger.info("Fed balance sheet events: %d events.", len(bs_events))
1631
+
1632
+ # ── NEW: Monetary base ──
1633
+ bogm = _load_fred("BOGMBASE")
1634
+ if not bogm.empty:
1635
+ bogm_events = _detect_monetary_base_shocks(bogm)
1636
+ all_events.extend(bogm_events)
1637
+ logger.info("Monetary base shocks: %d events.", len(bogm_events))
1638
+
1639
+ # ── NEW: Business / C&I loans ──
1640
+ busloans = _load_fred("BUSLOANS")
1641
+ if not busloans.empty:
1642
+ bl_events = _detect_business_loan_shocks(busloans)
1643
+ all_events.extend(bl_events)
1644
+ logger.info("Business loan shocks: %d events.", len(bl_events))
1645
+
1646
+ # ── NEW: Cross-asset composites ──
1647
+
1648
+ # Real yield: DGS10 - T10YIE
1649
+ bei_10y = _load_fred("T10YIE")
1650
+ if not dgs10.empty and not bei_10y.empty:
1651
+ ry_events = _detect_real_yield_shocks(dgs10, bei_10y)
1652
+ all_events.extend(ry_events)
1653
+ logger.info("Real yield shocks: %d events.", len(ry_events))
1654
+
1655
+ # Credit compression: HY - IG spread gap
1656
+ if not hy.empty and not ig.empty:
1657
+ cc_events = _detect_credit_compression(hy, ig)
1658
+ all_events.extend(cc_events)
1659
+ logger.info("Credit compression events: %d events.", len(cc_events))
1660
+
1661
+ # Term premium: DGS30 - DGS2
1662
+ if not dgs30.empty and not dgs2.empty:
1663
+ tp_events = _detect_term_premium_shocks(dgs30, dgs2)
1664
+ all_events.extend(tp_events)
1665
+ logger.info("Term premium shocks: %d events.", len(tp_events))
1666
+
1667
+ # ── NEW: Short-term (5-day) shocks for acute market events ──
1668
+
1669
+ # S&P 500 acute crash
1670
+ if not sp500.empty:
1671
+ sp_short = _detect_short_term_shocks(
1672
+ sp500, "sp500_acute_shock", "the S&P 500",
1673
+ config.SCENARIO_SP500_SHORT_DRAWDOWN,
1674
+ config.SCENARIO_SP500_SHORT_WINDOW)
1675
+ all_events.extend(sp_short)
1676
+ logger.info("S&P 500 acute shocks (5d): %d events.", len(sp_short))
1677
+
1678
+ # NASDAQ acute shock
1679
+ if not nasdaq.empty:
1680
+ nq_short = _detect_short_term_shocks(
1681
+ nasdaq, "nasdaq_acute_shock", "the NASDAQ",
1682
+ config.SCENARIO_NASDAQ_SHORT_PCT,
1683
+ config.SCENARIO_NASDAQ_SHORT_WINDOW)
1684
+ all_events.extend(nq_short)
1685
+ logger.info("NASDAQ acute shocks (5d): %d events.", len(nq_short))
1686
+
1687
+ # Oil acute shock
1688
+ if not wti.empty:
1689
+ oil_short = _detect_short_term_shocks(
1690
+ wti, "oil_acute_shock", "WTI crude oil",
1691
+ config.SCENARIO_OIL_SHORT_PCT,
1692
+ config.SCENARIO_OIL_SHORT_WINDOW,
1693
+ unit="$/bbl", fmt=".2f")
1694
+ all_events.extend(oil_short)
1695
+ logger.info("Oil acute shocks (5d): %d events.", len(oil_short))
1696
+
1697
+ # 10Y Treasury acute rate move
1698
+ if not dgs10.empty:
1699
+ dgs10_short = _detect_short_term_level_shocks(
1700
+ dgs10, "treasury_acute_shock", "the 10Y Treasury yield",
1701
+ config.SCENARIO_DGS10_SHORT_DELTA,
1702
+ config.SCENARIO_DGS10_SHORT_WINDOW)
1703
+ all_events.extend(dgs10_short)
1704
+ logger.info("10Y Treasury acute shocks (5d): %d events.", len(dgs10_short))
1705
+
1706
+ # Build DataFrame
1707
+ if all_events:
1708
+ df = pd.DataFrame(all_events)
1709
+ df["event_date"] = pd.to_datetime(df["event_date"])
1710
+ df = df.sort_values("event_date").reset_index(drop=True)
1711
+ df["scenario_id"] = [f"sc_{i:04d}" for i in range(len(df))]
1712
+ df["pre_window_start"] = df["event_date"] - pd.Timedelta(days=config.SCENARIO_PRE_WINDOW_DAYS)
1713
+ df["post_window_end"] = df["event_date"] + pd.Timedelta(days=config.SCENARIO_POST_WINDOW_DAYS)
1714
+ # Reorder columns
1715
+ df = df[["scenario_id", "event_type", "event_date", "event_description",
1716
+ "pre_window_start", "post_window_end"]]
1717
+ else:
1718
+ df = pd.DataFrame(columns=[
1719
+ "scenario_id", "event_type", "event_date", "event_description",
1720
+ "pre_window_start", "post_window_end",
1721
+ ])
1722
+
1723
+ # Filter out scenarios whose event_date falls outside the valid panel
1724
+ # window. Scenarios before START_DATE have no pre-event prices; those
1725
+ # at the very end have no post-event prices. Both produce empty ground
1726
+ # truth and should be dropped to keep scenarios.parquet = GT set.
1727
+ if not df.empty:
1728
+ panel_start = pd.Timestamp(config.START_DATE)
1729
+ panel_end = pd.Timestamp(config.END_DATE)
1730
+ # Leave at least 21 trading days after the event for post-window returns
1731
+ # AND at least 21 trading days before for pre-event baseline
1732
+ min_event = panel_start + pd.Timedelta(days=35)
1733
+ max_event = panel_end - pd.Timedelta(days=35)
1734
+ before = len(df)
1735
+ df = df[(df["event_date"] >= min_event) & (df["event_date"] <= max_event)].copy()
1736
+ # Re-number scenario_ids to keep them contiguous after filtering
1737
+ df = df.sort_values("event_date").reset_index(drop=True)
1738
+ df["scenario_id"] = [f"sc_{i:04d}" for i in range(len(df))]
1739
+ dropped = before - len(df)
1740
+ if dropped > 0:
1741
+ logger.info("Filtered %d scenarios outside valid panel window [%s, %s]",
1742
+ dropped, panel_start.date(), max_event.date())
1743
+
1744
+ df.to_parquet(out_dir / "scenarios.parquet", index=False)
1745
+ logger.info("Saved %d scenario events -> %s", len(df), out_dir / "scenarios.parquet")
1746
+ return df
code/macrolens/__init__.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MacroLens — public unified API (v0.2).
2
+
3
+ The 10-line workflow::
4
+
5
+ import macrolens as ml
6
+
7
+ X_train, y_train, meta_train = ml.load("T1", "train", granularity="daily")
8
+ X_test, y_test, meta_test = ml.load("T1", "test")
9
+
10
+ model = ml.methods.LightGBMRegressor(task="T1")
11
+ model.fit(X_train, y_train, seed=42)
12
+ y_pred = model.predict(X_test)
13
+
14
+ metrics = ml.score("T1", y_test, y_pred,
15
+ cluster_keys=meta_test["ticker"].values)
16
+ print(metrics["mse"].value, metrics["mse"].ci_lo, metrics["mse"].ci_hi)
17
+
18
+ Public surface
19
+ --------------
20
+
21
+ * :func:`load` — sklearn-style ``(X, y, meta)`` data layer.
22
+ * :func:`score` / :func:`compare_methods` — eval layer.
23
+ * :func:`info` / :func:`features` — benchmark metadata.
24
+ * :func:`list_methods` — registered method names (filterable by family / task).
25
+ * :data:`methods` — sub-namespace; ``ml.methods.<ClassName>(task=...)``.
26
+ * :class:`LoadedData`, :class:`MetricValue`, :class:`RunRecord` — types.
27
+
28
+ Legacy v0.1 entry points (``load_tsf``, ``to_arrays``, ``evaluate``,
29
+ ``ask_lumina``, ...) remain importable during the v0.1 → v0.2 transition;
30
+ they will be removed in Phase 7.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ # ── v0.2 unified API (primary surface) ────────────────────────────────────
36
+ from . import methods # noqa: F401 (sub-namespace; ml.methods.<Name>)
37
+ from ._types import LoadedData, MetricValue, RunRecord
38
+ from .data import load
39
+ from .eval import compare_methods, score
40
+ from .meta import BENCHMARK_NAME, __version__, features, info
41
+ from .methods import ALL_METHODS, list_methods
42
+
43
+
44
+ # ── Legacy v0.1 entry points (transitional) ───────────────────────────────
45
+ # These are imported lazily below so the new public surface stays usable
46
+ # even when the legacy modules grow new dependencies. Failures during the
47
+ # transitional period are captured and surfaced as ImportError on first
48
+ # attribute access (rather than crashing every ``import macrolens`` call).
49
+ def _import_legacy() -> dict[str, object]:
50
+ out: dict[str, object] = {}
51
+ try:
52
+ from ._evaluate import evaluate, format_submission
53
+ out["evaluate"] = evaluate
54
+ out["format_submission"] = format_submission
55
+ except Exception: # pragma: no cover -- legacy module surface drift
56
+ pass
57
+ try:
58
+ from ._fast import TSFTorchDataset, load_torch, to_arrays
59
+ out["TSFTorchDataset"] = TSFTorchDataset
60
+ out["load_torch"] = load_torch
61
+ out["to_arrays"] = to_arrays
62
+ # legacy `features` function on _fast shadowed by meta.features in
63
+ # the v0.2 surface; expose under a private alias for back-compat.
64
+ from ._fast import features as _legacy_features
65
+ out["_legacy_features"] = _legacy_features
66
+ except Exception: # pragma: no cover
67
+ pass
68
+ try:
69
+ from ._loaders import load_panel, load_scenarios, load_task, load_tsf
70
+ out["load_panel"] = load_panel
71
+ out["load_scenarios"] = load_scenarios
72
+ out["load_task"] = load_task
73
+ out["load_tsf"] = load_tsf
74
+ except Exception: # pragma: no cover
75
+ pass
76
+ try:
77
+ from ._meta import BENCHMARK_VERSION
78
+ out["BENCHMARK_VERSION"] = BENCHMARK_VERSION
79
+ except Exception: # pragma: no cover
80
+ pass
81
+ try:
82
+ from ._types import (
83
+ BenchmarkInfo,
84
+ GenerationMetrics,
85
+ REValuationMetrics,
86
+ ScenarioMetrics,
87
+ TaskSample,
88
+ TSFMetrics,
89
+ TSFSample,
90
+ ValuationMetrics,
91
+ )
92
+ out["BenchmarkInfo"] = BenchmarkInfo
93
+ out["GenerationMetrics"] = GenerationMetrics
94
+ out["REValuationMetrics"] = REValuationMetrics
95
+ out["ScenarioMetrics"] = ScenarioMetrics
96
+ out["TaskSample"] = TaskSample
97
+ out["TSFMetrics"] = TSFMetrics
98
+ out["TSFSample"] = TSFSample
99
+ out["ValuationMetrics"] = ValuationMetrics
100
+ except Exception: # pragma: no cover
101
+ pass
102
+ return out
103
+
104
+
105
+ _LEGACY = _import_legacy()
106
+
107
+
108
+ def __getattr__(name: str):
109
+ """Resolve legacy attributes lazily (and ``ask_lumina`` even more so)."""
110
+ if name in _LEGACY:
111
+ return _LEGACY[name]
112
+ if name == "ask_lumina":
113
+ # The lumina agent imports openrouter / vector store deps that may
114
+ # not be installed in CPU-only paper-scope environments. Defer the
115
+ # import to first call.
116
+ from ..agents.lumina import ask as ask_lumina
117
+ return ask_lumina
118
+ if name == "lakehouse":
119
+ def _lakehouse(tag: str = "macrolens-v1.0"):
120
+ from ..lakehouse import Client
121
+ return Client.from_release(tag)
122
+ return _lakehouse
123
+ raise AttributeError(f"module 'macrolens' has no attribute {name!r}")
124
+
125
+
126
+ __all__ = [
127
+ # v0.2 unified API
128
+ "load",
129
+ "score",
130
+ "compare_methods",
131
+ "info",
132
+ "features",
133
+ "list_methods",
134
+ "methods",
135
+ "ALL_METHODS",
136
+ "LoadedData",
137
+ "MetricValue",
138
+ "RunRecord",
139
+ "BENCHMARK_NAME",
140
+ "__version__",
141
+ # legacy (lazy)
142
+ "evaluate",
143
+ "format_submission",
144
+ "TSFTorchDataset",
145
+ "load_torch",
146
+ "to_arrays",
147
+ "load_panel",
148
+ "load_scenarios",
149
+ "load_task",
150
+ "load_tsf",
151
+ "ask_lumina",
152
+ "lakehouse",
153
+ "BENCHMARK_VERSION",
154
+ "BenchmarkInfo",
155
+ "GenerationMetrics",
156
+ "REValuationMetrics",
157
+ "ScenarioMetrics",
158
+ "TaskSample",
159
+ "TSFMetrics",
160
+ "TSFSample",
161
+ "ValuationMetrics",
162
+ ]