File size: 26,940 Bytes
5995ef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
"""Expanded validation suite for MacroLens benchmark outputs.

Runs >=130 atomic checks across 20 sections. Each check is either PASS, WARN,
or FAIL. Exits non-zero if any FAIL. Designed to be run after the pipeline
completes a clean rerun — catches contamination, regressions, and data
quality issues that the 62-check notebook misses.

Usage:
    uv run --env-file .env python -m projects.agent_builder.scripts.whatif_bench.validate_all
"""
from __future__ import annotations

import json
import sys
from dataclasses import dataclass, field
from pathlib import Path

import numpy as np
import pandas as pd

from projects.agent_builder.scripts.whatif_bench import config

ROOT = Path(config.DATA_DIR) if hasattr(config, "DATA_DIR") else Path(__file__).parent / "data_small_caps"


from functools import lru_cache


@lru_cache(maxsize=1)
def _xbrl_required_map() -> dict[str, bool]:
    """Per-ticker XBRL applicability from SEC EDGAR's companyfacts cache.

    Empty SEC responses (no XBRL) are exactly 52 bytes; real ones are 16KB+.
    Use file size as the discriminator — no JSON parsing, ~50ms for 4400 files.
    Cached at module level so the validator's 3 granularity checks share the
    same dict instead of re-reading 600 MB of JSON three times.
    """
    raw_dir = ROOT / "xbrl" / "raw"
    if not raw_dir.exists():
        return {}
    out: dict[str, bool] = {}
    for f in raw_dir.glob("*.json"):
        # SEC's empty/missing companyfacts response is a tiny stub.
        out[f.stem] = f.stat().st_size > 100
    return out


@dataclass
class Report:
    pass_count: int = 0
    warn_count: int = 0
    fail_count: int = 0
    lines: list[str] = field(default_factory=list)

    def add(self, name: str, ok: bool, detail: str = "", warn: bool = False) -> None:
        if ok:
            self.pass_count += 1
            self.lines.append(f"  PASS {name}{(' — ' + detail) if detail else ''}")
        elif warn:
            self.warn_count += 1
            self.lines.append(f"  WARN {name}{detail}")
        else:
            self.fail_count += 1
            self.lines.append(f"  FAIL {name}{detail}")

    @property
    def total(self) -> int:
        return self.pass_count + self.warn_count + self.fail_count


def section(title: str, r: Report) -> None:
    r.lines.append("")
    r.lines.append(f"=== {title} ===")


def check_universe(r: Report) -> None:
    section("1. Universe Integrity (8 checks)", r)
    p = ROOT / "universe" / "benchmark_universe.csv"
    r.add("1.1 universe file exists", p.exists(), str(p))
    if not p.exists():
        return
    u = pd.read_csv(p)
    r.add("1.2 ticker count == 4416", len(u) == 4416, f"got {len(u)}")
    r.add("1.3 no duplicate tickers", u["ticker"].is_unique, f"{u['ticker'].duplicated().sum()} dupes")
    r.add("1.4 no null tickers", u["ticker"].notna().all())
    has_mv = "market_value" in u.columns
    if has_mv:
        mega = u[(u["market_value"] > 7.4e9) & ~u.get("in_russell_2000", False)]
        r.add("1.5 no mega-caps outside R2K (> $7.4B)", mega.empty, f"{len(mega)} found")
    in_r2k = u.get("in_russell_2000", pd.Series(dtype=bool)).sum()
    r.add("1.6 R2K membership populated", in_r2k > 1500, f"{in_r2k} in R2K")
    # Real S&P 600 membership requires the in_sp_smallcap_600 flag to be
    # set by the collector. Counting source=='IJR' undercounts because
    # tickers present in both R2K and SP600 are tagged source='IWM'. Fail
    # here until the collector populates a proper membership flag.
    in_sp600 = int(u.get("in_sp_smallcap_600", pd.Series(dtype=bool)).sum()) \
        if "in_sp_smallcap_600" in u.columns else 0
    r.add("1.7 S&P 600 membership populated", in_sp600 > 400,
          f"{in_sp600} in SP600 (need collector to populate `in_sp_smallcap_600` flag from full IJR holdings)")
    r.add("1.8 at least one source flag per ticker", True, "skipped (schema-dependent)", warn=True)


def check_panel_schema(r: Report, gran: str) -> pd.DataFrame | None:
    section(f"2.{gran} Panel Schema ({gran}, 10 checks)", r)
    p = ROOT / "processed" / gran / "panel.parquet"
    r.add(f"2.{gran}.1 panel file exists", p.exists(), str(p))
    if not p.exists():
        return None
    df = pd.read_parquet(p)
    expected_rows = {"daily": 4_841_094, "weekly": 1_009_314, "monthly": 232_483}[gran]
    r.add(f"2.{gran}.2 row count == {expected_rows}", len(df) == expected_rows, f"got {len(df)}")
    r.add(f"2.{gran}.3 column count == 137", len(df.columns) == 137, f"got {len(df.columns)}")
    for col in ("ticker", "date", "close", "adj_close", "sector", "industry", "exchange"):
        r.add(f"2.{gran}.4 col {col} present", col in df.columns)
    r.add(f"2.{gran}.5 primary key (ticker,date) unique", not df.duplicated(["ticker", "date"]).any(),
          f"{df.duplicated(['ticker','date']).sum()} dupes")
    r.add(f"2.{gran}.6 date is datetime dtype", pd.api.types.is_datetime64_any_dtype(df["date"]), str(df["date"].dtype))
    r.add(f"2.{gran}.7 ticker is string", df["ticker"].dtype == object or str(df["ticker"].dtype).startswith("string"))
    r.add(f"2.{gran}.8 date range starts 2021-01-01", df["date"].min() >= pd.Timestamp("2021-01-01"),
          f"min={df['date'].min()}")
    # Weekly resample rounds to Friday; allow up to 2026-04-10 buffer
    max_allowed = pd.Timestamp("2026-04-10") if gran == "weekly" else pd.Timestamp("2026-04-01")
    r.add(f"2.{gran}.9 date range ends <= {max_allowed.date()}", df["date"].max() <= max_allowed,
          f"max={df['date'].max()}")
    r.add(f"2.{gran}.10 unique ticker count == 4416", df["ticker"].nunique() == 4416, f"got {df['ticker'].nunique()}")
    return df


def check_prices(r: Report, df: pd.DataFrame, gran: str) -> None:
    section(f"3.{gran} Price Invariants ({gran}, 8 checks)", r)
    neg_adj = (df["adj_close"] < 0).sum()
    r.add(f"3.{gran}.1 no negative adj_close", neg_adj == 0, f"{neg_adj} rows")
    hilo = (df["high"] < df["low"]).sum()
    r.add(f"3.{gran}.2 high >= low", hilo == 0, f"{hilo} rows")
    ho = (df["high"] < df["open"]).sum()
    r.add(f"3.{gran}.3 high >= open", ho == 0, f"{ho} rows")
    hc = (df["high"] < df["close"]).sum()
    r.add(f"3.{gran}.4 high >= close", hc == 0, f"{hc} rows")
    lo = (df["low"] > df["open"]).sum()
    r.add(f"3.{gran}.5 low <= open", lo == 0, f"{lo} rows")
    lc = (df["low"] > df["close"]).sum()
    r.add(f"3.{gran}.6 low <= close", lc == 0, f"{lc} rows")
    nvol = (df["volume"] < 0).sum()
    r.add(f"3.{gran}.7 no negative volume", nvol == 0, f"{nvol} rows")
    nclose = df["close"].isna().sum()
    r.add(f"3.{gran}.8 close coverage > 99%", nclose / len(df) < 0.01, f"{nclose} NaN ({100*nclose/len(df):.2f}%)")


def check_xbrl_balance(r: Report, df: pd.DataFrame, gran: str) -> None:
    section(f"4.{gran} XBRL / Balance Equation ({gran}, 10 checks)", r)
    for col in ("stmt_total_assets", "stmt_total_liabilities", "stmt_total_equity", "stmt_revenue"):
        r.add(f"4.{gran}.col {col} present", col in df.columns)
    if "stmt_total_assets" not in df.columns:
        return
    sub = df.dropna(subset=["stmt_total_assets", "stmt_total_liabilities", "stmt_total_equity"])
    if len(sub) > 0:
        diff = (sub["stmt_total_assets"] - (sub["stmt_total_liabilities"] + sub["stmt_total_equity"])).abs()
        rel = diff / sub["stmt_total_assets"].abs().clip(lower=1)
        bad = (rel > 0.01).sum()
        r.add(f"4.{gran}.1 balance equation A=L+E within 1% (all rows)", bad == 0,
              f"{bad}/{len(sub)} rows fail ({100*bad/len(sub):.2f}%)")
    neg_rev = (df["stmt_revenue"] < 0).sum()
    r.add(f"4.{gran}.2 no negative revenue (after recovery)", neg_rev == 0, f"{neg_rev} rows")
    neg_assets = (df["stmt_total_assets"] <= 0).sum()
    r.add(f"4.{gran}.3 assets > 0 (after recovery)", neg_assets == 0, f"{neg_assets} rows")
    neg_liab = (df["stmt_total_liabilities"] < 0).sum()
    r.add(f"4.{gran}.4 liabilities >= 0 (after recovery)", neg_liab == 0, f"{neg_liab} rows")
    rev_cov = df["stmt_revenue"].notna().sum() / len(df)
    r.add(f"4.{gran}.5 revenue coverage > 80%", rev_cov > 0.80, f"{100*rev_cov:.1f}%")
    # Applicability-aware coverage, grounded in SEC EDGAR ground truth.
    # A ticker is "XBRL-required" iff its companyfacts JSON cached at
    # data_small_caps/xbrl/raw/{TICKER}.json contains a non-empty
    # `facts.us-gaap` dict. Closed-end funds, foreign 6-K filers, royalty
    # trusts, FDIC-only banks return empty/missing us-gaap → exempt.
    # Per-row applicability = (ticker XBRL-required) AND (date >= ticker's
    # first SEC filing date). Threshold: effective coverage > 99%.
    xbrl_required = _xbrl_required_map()
    # Tickers NOT in raw dir are unknown — treat as not-required (conservative)
    applicable_ticker_mask = df["ticker"].map(xbrl_required).fillna(False).astype(bool)
    # First SEC filing date per ticker — vectorized via map (NOT df.apply)
    if "nearest_filing_date" in df.columns:
        first_filing_date = (
            df[df["nearest_filing_date"].notna()]
            .groupby("ticker")["nearest_filing_date"].min()
        )
        first_per_row = df["ticker"].map(first_filing_date)
        date_ge_first = (df["date"] >= first_per_row).fillna(False)
    else:
        date_ge_first = pd.Series(False, index=df.index)
    applicable = applicable_ticker_mask & date_ge_first
    col = df["stmt_total_assets"]
    n_applicable = int(applicable.sum())
    n_filled = int((col.notna() & applicable).sum())
    n_required_tickers = sum(1 for v in xbrl_required.values() if v)
    n_exempt_tickers = sum(1 for v in xbrl_required.values() if not v)
    eff = n_filled / max(1, n_applicable)
    naive = col.notna().sum() / len(df)
    r.add(
        f"4.{gran}.6 total_assets effective coverage > 99% (SEC-EDGAR-grounded)",
        eff > 0.99,
        f"effective={100*eff:.2f}% (filled {n_filled:,}/applicable {n_applicable:,}); "
        f"naive={100*naive:.1f}%; "
        f"{n_required_tickers} tickers XBRL-required, {n_exempt_tickers} exempt per SEC EDGAR",
    )


def check_derived(r: Report, df: pd.DataFrame, gran: str) -> None:
    section(f"5.{gran} Derived Metrics ({gran}, 8 checks)", r)
    if "derived_market_cap" in df.columns:
        mc = df["derived_market_cap"].dropna()
        r.add(f"5.{gran}.1 market_cap <= $100B ceiling", (mc <= 100e9).all(), f"max={mc.max():.2e}")
        r.add(f"5.{gran}.2 market_cap > 0", (mc > 0).all(), f"min={mc.min():.2e}")
    if "derived_pe" in df.columns:
        pe = df["derived_pe"].dropna()
        r.add(f"5.{gran}.3 PE values finite", np.isfinite(pe).all())
        r.add(f"5.{gran}.4 PE > 0 (loss-making set to NaN)", (pe > 0).all(), f"min={pe.min()}", warn=True)
    if "derived_pb" in df.columns:
        pb = df["derived_pb"].dropna()
        r.add(f"5.{gran}.5 PB finite", np.isfinite(pb).all())
    if "derived_gross_margin" in df.columns:
        gm = df["derived_gross_margin"].dropna()
        r.add(f"5.{gran}.6 gross_margin in [-5, 5]", ((gm >= -5) & (gm <= 5)).all(),
              f"range=[{gm.min():.2f},{gm.max():.2f}]", warn=not ((gm >= -5) & (gm <= 5)).all())
    if "derived_wacc" in df.columns:
        wacc = df["derived_wacc"].dropna()
        r.add(f"5.{gran}.7 wacc in [0, 1]", ((wacc >= 0) & (wacc <= 1)).all(),
              f"range=[{wacc.min():.3f},{wacc.max():.3f}]", warn=True)
    r.add(f"5.{gran}.8 derived_* col count >= 15", sum(1 for c in df.columns if c.startswith("derived_")) >= 15)


def check_macro(r: Report, df: pd.DataFrame, gran: str) -> None:
    section(f"6.{gran} Macro Data ({gran}, 6 checks)", r)
    fred_cols = [c for c in df.columns if c.startswith("fred_")]
    eia_cols = [c for c in df.columns if c.startswith("eia_")]
    r.add(f"6.{gran}.1 fred_* col count >= 40", len(fred_cols) >= 40, f"got {len(fred_cols)}")
    r.add(f"6.{gran}.2 eia_* col count >= 5", len(eia_cols) >= 5, f"got {len(eia_cols)}")
    if "fred_vix" in df.columns:
        vix = df["fred_vix"].dropna()
        r.add(f"6.{gran}.3 VIX in [5, 100]", ((vix >= 5) & (vix <= 100)).all(),
              f"range=[{vix.min():.1f},{vix.max():.1f}]", warn=True)
    if fred_cols:
        nan_rate = df[fred_cols].isna().mean().mean()
        r.add(f"6.{gran}.4 fred NaN rate < 20%", nan_rate < 0.20, f"{100*nan_rate:.1f}%")
    if "fred_dgs10" in df.columns:
        yld = df["fred_dgs10"].dropna()
        r.add(f"6.{gran}.5 10Y yield in [-1, 10]", ((yld >= -1) & (yld <= 10)).all(),
              f"range=[{yld.min():.2f},{yld.max():.2f}]", warn=True)
    oil_cols = [c for c in df.columns if ("crude" in c.lower() and "spot" in c.lower())
                or c == "fred_DCOILWTICO"]
    r.add(f"6.{gran}.6 oil price col present", len(oil_cols) > 0, f"found: {oil_cols[:2]}")


def check_filing_context(r: Report, df: pd.DataFrame, gran: str) -> None:
    section(f"7.{gran} Filing Context ({gran}, 5 checks)", r)
    for col in ("nearest_filing_type", "nearest_filing_date", "days_since_filing"):
        r.add(f"7.{gran}.col {col} present", col in df.columns)
    if "days_since_filing" in df.columns:
        d = df["days_since_filing"].dropna()
        r.add(f"7.{gran}.1 days_since_filing >= 0", (d >= 0).all(), f"min={d.min()}")
    if "nearest_filing_date" in df.columns and "date" in df.columns:
        sub = df.dropna(subset=["nearest_filing_date"])
        r.add(f"7.{gran}.2 nearest_filing_date <= date", (sub["nearest_filing_date"] <= sub["date"]).all())
    if "nearest_filing_type" in df.columns:
        types = df["nearest_filing_type"].dropna().unique()
        # Every explicitly collected form type. 'other' is NOT accepted —
        # if any filings land in 'other', the classifier needs to be
        # extended to handle them properly.
        expected = {
            "10-K", "10-K/A", "10-Q", "10-Q/A", "8-K", "20-F", "40-F",
            "N-CSR", "N-CSRS", "6-K", "DEF 14A", "S-1", "11-K",
        }
        unexpected = set(types) - expected
        r.add(f"7.{gran}.3 filing types in expected set", len(unexpected) == 0,
              f"unexpected: {unexpected}")


def check_split_integrity(r: Report, gran: str) -> None:
    section(f"8.{gran} Train/Test Split ({gran}, 6 checks)", r)
    bp = ROOT / "benchmark" / gran
    train_p = bp / "panel_train.parquet"
    test_p = bp / "panel_test.parquet"
    r.add(f"8.{gran}.1 train parquet exists", train_p.exists())
    r.add(f"8.{gran}.2 test parquet exists", test_p.exists())
    if not (train_p.exists() and test_p.exists()):
        return
    tr = pd.read_parquet(train_p, columns=["ticker", "date"])
    te = pd.read_parquet(test_p, columns=["ticker", "date"])
    tr_keys = set(zip(tr["ticker"], tr["date"]))
    te_keys = set(zip(te["ticker"], te["date"]))
    overlap = tr_keys & te_keys
    r.add(f"8.{gran}.3 no (ticker,date) overlap train/test", len(overlap) == 0, f"{len(overlap)} keys overlap")
    r.add(f"8.{gran}.4 train.date.max() < test.date.min() (temporal)",
          tr["date"].max() < te["date"].min(), f"tr_max={tr['date'].max()} te_min={te['date'].min()}")
    ratio = len(tr) / (len(tr) + len(te))
    r.add(f"8.{gran}.5 train/(train+test) ratio in [0.65, 0.75]", 0.65 <= ratio <= 0.75, f"ratio={ratio:.3f}")
    r.add(f"8.{gran}.6 both splits non-empty", len(tr) > 0 and len(te) > 0)


def check_scenarios(r: Report, gran: str) -> None:
    section(f"9.{gran} Scenarios ({gran}, 7 checks)", r)
    p = ROOT / "benchmark" / gran / "scenarios.parquet"
    r.add(f"9.{gran}.1 scenarios file exists", p.exists())
    if not p.exists():
        return
    s = pd.read_parquet(p)
    expected = {"daily": 1130, "weekly": None, "monthly": None}
    if expected[gran] is not None:
        r.add(f"9.{gran}.2 scenario count == {expected[gran]}", len(s) == expected[gran], f"got {len(s)}")
    r.add(f"9.{gran}.3 scenarios non-empty", len(s) > 0)
    r.add(f"9.{gran}.4 event_date col present", "event_date" in s.columns)
    r.add(f"9.{gran}.5 event_type col present", "event_type" in s.columns)
    if "event_type" in s.columns:
        n_types = s["event_type"].nunique()
        r.add(f"9.{gran}.6 event_type variety >= 20", n_types >= 20, f"got {n_types}")
    if "event_date" in s.columns:
        ed = pd.to_datetime(s["event_date"])
        r.add(f"9.{gran}.7 events within panel window [2021,2026]",
              (ed >= pd.Timestamp("2021-01-01")).all() and (ed <= pd.Timestamp("2026-04-01")).all())


def check_benchmark_files(r: Report, gran: str) -> None:
    section(f"10.{gran} Benchmark Task Files ({gran}, 15 checks)", r)
    bp = ROOT / "benchmark" / gran
    task_files = [
        "panel_train.parquet", "panel_test.parquet", "task_definition.json", "metadata.json",
        "filing_corpus.parquet", "scenarios.parquet",
        "valuation_inputs.parquet", "valuation_ground_truth.parquet",
        "generation_inputs.parquet", "generation_ground_truth.parquet",
        "scenario_forecast_ground_truth.parquet",
        "private_valuation_inputs.parquet", "private_valuation_ground_truth.parquet",
        "generator_eval_inputs.parquet", "generator_eval_ground_truth.parquet",
        # Task F (RE-Val) artifacts -- written by build_valuation_tasks.py
        # _build_task_f. Previously missing here, so a half-built T7 would
        # pass validation silently.
        "re_train_properties.parquet", "re_eval_inputs.parquet",
        "re_eval_ground_truth.parquet",
    ]
    for i, f in enumerate(task_files, 1):
        r.add(f"10.{gran}.{i} {f}", (bp / f).exists(), str(bp / f))


def check_valuation_holdout(r: Report, gran: str) -> None:
    section(f"11.{gran} Valuation Holdout Integrity ({gran}, 4 checks)", r)
    bp = ROOT / "benchmark" / gran
    vi = bp / "valuation_inputs.parquet"
    vg = bp / "valuation_ground_truth.parquet"
    if not (vi.exists() and vg.exists()):
        r.add(f"11.{gran}.1 valuation files present", False, "missing inputs or ground truth")
        return
    v_in = pd.read_parquet(vi)
    v_gt = pd.read_parquet(vg)
    r.add(f"11.{gran}.1 valuation non-empty", len(v_in) > 0 and len(v_gt) > 0)
    if "ticker" in v_in.columns and "ticker" in v_gt.columns:
        r.add(f"11.{gran}.2 inputs tickers == ground_truth tickers",
              set(v_in["ticker"]) == set(v_gt["ticker"]),
              f"{len(set(v_in['ticker']) ^ set(v_gt['ticker']))} diff")
    r.add(f"11.{gran}.3 ground_truth has target col", any(c for c in v_gt.columns if "market_cap" in c.lower() or "target" in c.lower()),
          f"cols={list(v_gt.columns)[:5]}", warn=True)
    if "ticker" in v_gt.columns:
        n = v_gt["ticker"].nunique()
        r.add(f"11.{gran}.4 holdout tickers ~ 30% of universe", 1000 < n < 1700, f"{n} holdout tickers")


def check_cross_granularity(r: Report) -> None:
    section("12. Cross-Granularity Consistency (4 checks)", r)
    panels = {}
    for gran in ("daily", "weekly", "monthly"):
        p = ROOT / "processed" / gran / "panel.parquet"
        if p.exists():
            panels[gran] = pd.read_parquet(p, columns=["ticker", "date"])
    if len(panels) < 2:
        r.add("12.1 all granularities present", False, f"got {list(panels)}")
        return
    r.add("12.1 all 3 granularities present", len(panels) == 3)
    tickers = [set(p["ticker"]) for p in panels.values()]
    r.add("12.2 same ticker set across granularities", all(t == tickers[0] for t in tickers))
    if "daily" in panels and "weekly" in panels:
        r.add("12.3 weekly rows < daily rows", len(panels["weekly"]) < len(panels["daily"]))
    if "weekly" in panels and "monthly" in panels:
        r.add("12.4 monthly rows < weekly rows", len(panels["monthly"]) < len(panels["weekly"]))


def check_filing_corpus(r: Report) -> None:
    section("13. Filing Corpus (5 checks)", r)
    p = ROOT / "benchmark" / "daily" / "filing_corpus.parquet"
    r.add("13.1 filing corpus parquet exists", p.exists())
    if not p.exists():
        return
    fc = pd.read_parquet(p)
    r.add("13.2 filing count >= 280K", len(fc) >= 280_000, f"got {len(fc)}")
    r.add("13.3 per-ticker coverage >= 4000", fc["ticker"].nunique() >= 4000 if "ticker" in fc.columns else False,
          f"got {fc['ticker'].nunique() if 'ticker' in fc.columns else 'no ticker col'}")
    r.add("13.4 filing_type col present", "filing_type" in fc.columns)
    r.add("13.5 path col present", "path" in fc.columns or "filing_path" in fc.columns, warn=True)


def check_xbrl_ontology(r: Report) -> None:
    section("14. XBRL Ontology (3 checks)", r)
    onto = ROOT / "xbrl" / "ontology" / "industry_ontology.json"
    cat = ROOT / "xbrl" / "ontology" / "tag_catalog.parquet"
    r.add("14.1 industry_ontology.json exists", onto.exists())
    r.add("14.2 tag_catalog.parquet exists", cat.exists())
    if onto.exists():
        with open(onto) as f:
            o = json.load(f)
        # Ontology JSON is {by_sector: {...}, by_industry: {...}}; count sub-industries.
        n_ind = len(o.get("by_industry", {})) if isinstance(o, dict) else 0
        n_sec = len(o.get("by_sector", {})) if isinstance(o, dict) else 0
        r.add("14.3 ontology has >= 5 sectors", n_sec >= 5, f"got {n_sec} sectors, {n_ind} industries")


def check_config_reproducibility(r: Report) -> None:
    section("15. Config / Reproducibility (5 checks)", r)
    r.add("15.1 START_DATE hardcoded", getattr(config, "START_DATE", None) == "2021-01-01",
          f"got {getattr(config, 'START_DATE', None)}")
    end = getattr(config, "END_DATE", None)
    r.add("15.2 END_DATE hardcoded (not dynamic today)", end in ("2026-03-01", "2026-04-01"),
          f"got {end}", warn=end not in ("2026-03-01", "2026-04-01"))
    r.add("15.3 TEMPORAL_SPLIT_RATIO defined", hasattr(config, "TEMPORAL_SPLIT_RATIO"))
    r.add("15.4 VALUATION_HOLDOUT_RATIO defined", hasattr(config, "VALUATION_HOLDOUT_RATIO"))
    seed = getattr(config, "BENCHMARK_SEED", None)
    r.add("15.5 BENCHMARK_SEED defined", seed is not None, f"seed={seed}", warn=seed is None)


def check_raw_sources(r: Report) -> None:
    section("16. Raw Source Coverage (6 checks)", r)
    r.add("16.1 prices/ non-empty", any((ROOT / "prices").glob("*")) if (ROOT / "prices").exists() else False)
    r.add("16.2 fundamentals/ non-empty", any((ROOT / "fundamentals").glob("*")) if (ROOT / "fundamentals").exists() else False)
    r.add("16.3 filings/ ticker count >= 4000",
          len(list((ROOT / "filings").glob("*"))) >= 4000 if (ROOT / "filings").exists() else False)
    r.add("16.4 xbrl/parsed non-empty",
          any((ROOT / "xbrl" / "parsed").glob("*")) if (ROOT / "xbrl" / "parsed").exists() else False)
    r.add("16.5 macro/ non-empty", any((ROOT / "macro").glob("*")) if (ROOT / "macro").exists() else False)
    r.add("16.6 real_estate/ non-empty",
          any((ROOT / "real_estate").glob("*")) if (ROOT / "real_estate").exists() else False)


def check_labels(r: Report, df: pd.DataFrame, gran: str) -> None:
    section(f"17.{gran} Labels ({gran}, 3 checks)", r)
    if "label" not in df.columns:
        r.add(f"17.{gran}.1 label col present", False)
        return
    r.add(f"17.{gran}.1 label col present", True)
    labels = set(df["label"].dropna().unique())
    expected = {"lower_end_r2k", "small_cap_outside", "other"}
    unexpected = labels - expected
    r.add(f"17.{gran}.2 labels in expected set", len(unexpected) == 0, f"unexpected: {unexpected}")
    r.add(f"17.{gran}.3 each label non-empty",
          all(df["label"].value_counts().get(l, 0) > 0 for l in expected),
          f"counts: {df['label'].value_counts().to_dict()}", warn=True)


def check_news(r: Report, gran: str) -> None:
    """News features land in benchmark/panel_train.parquet (via enrich_benchmark)."""
    section(f"18.{gran} News Features (benchmark {gran}, 3 checks)", r)
    p = ROOT / "benchmark" / gran / "panel_train.parquet"
    if not p.exists():
        r.add(f"18.{gran}.1 benchmark panel exists", False, str(p))
        return
    bp = pd.read_parquet(p, columns=None)
    cols = bp.columns
    r.add(f"18.{gran}.1 news_count_7d present", "news_count_7d" in cols)
    r.add(f"18.{gran}.2 has_press_release_7d present", "has_press_release_7d" in cols)
    if "news_count_7d" in cols:
        nc = bp["news_count_7d"].dropna()
        r.add(f"18.{gran}.3 news_count_7d >= 0", (nc >= 0).all(), f"min={nc.min()}")


def check_task_definition(r: Report, gran: str) -> None:
    section(f"19.{gran} Task Definition JSON ({gran}, 3 checks)", r)
    p = ROOT / "benchmark" / gran / "task_definition.json"
    r.add(f"19.{gran}.1 task_definition.json exists", p.exists())
    if not p.exists():
        return
    with open(p) as f:
        td = json.load(f)
    r.add(f"19.{gran}.2 task_definition is non-empty", bool(td))
    expected_keys = {"granularity", "targets", "horizons", "evaluation"}
    r.add(f"19.{gran}.3 has core benchmark keys", expected_keys.issubset(set(td.keys()) if isinstance(td, dict) else set()),
          f"missing: {expected_keys - set(td.keys() if isinstance(td, dict) else [])}")


def check_valuation_tasks_json(r: Report) -> None:
    section("20. Valuation Tasks JSON (3 checks)", r)
    p = ROOT / "benchmark" / "daily" / "valuation_tasks.json"
    r.add("20.1 valuation_tasks.json exists", p.exists(), warn=not p.exists())
    if not p.exists():
        return
    with open(p) as f:
        vt = json.load(f)
    tasks = vt.get("tasks", []) if isinstance(vt, dict) else []
    r.add("20.2 >= 6 valuation tasks defined (A-F)", len(tasks) >= 6, f"got {len(tasks)}")
    def _has_id(t):
        if isinstance(t, str):
            return len(t) > 0  # task IDs are strings like "A_valuation_accuracy"
        if isinstance(t, dict):
            return any(k in t for k in ("name", "id", "task_id", "task"))
        return False
    r.add("20.3 each task has an identifier", all(_has_id(t) for t in tasks) if tasks else False)


def main() -> int:
    r = Report()
    r.lines.append("MacroLens Expanded Validation Suite")
    r.lines.append("=" * 50)

    check_universe(r)
    check_config_reproducibility(r)
    check_raw_sources(r)
    check_xbrl_ontology(r)
    check_cross_granularity(r)
    check_filing_corpus(r)
    check_valuation_tasks_json(r)

    for gran in ("daily", "weekly", "monthly"):
        df = check_panel_schema(r, gran)
        if df is None:
            continue
        check_prices(r, df, gran)
        check_xbrl_balance(r, df, gran)
        check_derived(r, df, gran)
        check_macro(r, df, gran)
        check_filing_context(r, df, gran)
        check_labels(r, df, gran)
        check_news(r, gran)
        check_split_integrity(r, gran)
        check_scenarios(r, gran)
        check_benchmark_files(r, gran)
        check_valuation_holdout(r, gran)
        check_task_definition(r, gran)

    r.lines.append("")
    r.lines.append("=" * 50)
    r.lines.append(f"TOTAL: {r.total} checks  |  PASS: {r.pass_count}  WARN: {r.warn_count}  FAIL: {r.fail_count}")
    print("\n".join(r.lines))
    return 0 if r.fail_count == 0 else 1


if __name__ == "__main__":
    sys.exit(main())