"""Canonical-indices generator. Reads the immutable benchmark artifacts and produces deterministic, stratified train/eval index lists per task. Every family runner reads from here so cross-method comparison is fair: same N, same instances, same indices. The cache lives under `experiments/cache/canonical_indices//` where `` encodes (n_eval, n_train, seed, stratifier_version) -- so changing any sample-budget parameter produces a new cache directory. The cache is an experiment-side speed optimisation; the canonical dataset tree under `data_small_caps/` contains only raw and derived benchmark artifacts (which are immutable). Per-task stratification: T1 (TSF): sector x market_cap_quartile -> (ticker, anchor_date) T2 (Val-PT): full 30% ticker holdout -> (ticker, date) T3 (Stmt-Gen): per-(ticker, fiscal_year) holdout -> (ticker, fiscal_year) T4 (Scen-Ret): sector x mcap_q x event_type -> (scenario_id, ticker) T5 (Val-Priv): full 30% ticker holdout -> (ticker, date) T6 (Gen-Eval): per-(ticker, fiscal_year) holdout -> (ticker, fiscal_year) T7 (RE-Val): property_type x state -> address """ from __future__ import annotations import logging from pathlib import Path from typing import Literal import numpy as np import pandas as pd from .. import config from . import budgets from .budgets import EVAL_N_PER_TASK, TRAIN_N_PER_TASK, SEED, Task logger = logging.getLogger(__name__) Split = Literal["train", "eval"] def _cfg_get_lookback(granularity: str) -> int: """Return the canonical (shortest) lookback for ``granularity``.""" return config.get_lookback_windows(granularity)[0] if hasattr(config, "get_lookback_windows") else 63 def _provenance_suffix(granularity: str) -> str: """16-char SHA-256-derived suffix encoding the relevant benchmark parquets for ``granularity``. Mutating any of those parquets changes the cache key, forcing canonical-indices regeneration. """ from ._provenance import sha256_combined bench_dir = config.get_benchmark_dir(granularity) candidates = [ bench_dir / "panel_train.parquet", bench_dir / "panel_test.parquet", bench_dir / "valuation_inputs.parquet", bench_dir / "valuation_ground_truth.parquet", bench_dir / "private_valuation_inputs.parquet", bench_dir / "private_valuation_ground_truth.parquet", bench_dir / "generation_inputs.parquet", bench_dir / "generation_ground_truth.parquet", bench_dir / "generator_eval_inputs.parquet", bench_dir / "generator_eval_ground_truth.parquet", bench_dir / "scenario_forecast_ground_truth.parquet", bench_dir / "scenarios.parquet", bench_dir / "re_train_properties.parquet", bench_dir / "re_eval_inputs.parquet", bench_dir / "re_eval_ground_truth.parquet", ] existing = [p for p in candidates if p.exists()] if not existing: return "noprov" return sha256_combined(existing) def _cache_dir(granularity: str, key: str | None = None) -> Path: """Return the cache directory for a given budget key. Lives under ``experiments/cache/canonical_indices/`` (experiment-side speed optimisation, regenerable on miss). The canonical dataset tree under ``data_small_caps/`` contains only raw and derived benchmark artifacts; experiment-side caches NEVER live there. The cache key suffix encodes (i) a SHA-256 over the benchmark parquets and (ii) the current ``max(lookback)`` and ``max(horizon)`` for ``granularity``. Either upstream-data drift or a horizon/lookback config change atomically invalidates the cache. """ k = key or budgets.cache_key() suffix = _provenance_suffix(granularity) max_lb = max(config.get_lookback_windows(granularity)) max_h = max(config.get_horizons(granularity)) # Resolve experiments/ as a sibling of dataloader/ (this file lives # at projects/.../whatif_bench/dataloader/canonical_indices.py). experiments_dir = Path(__file__).resolve().parents[1] / "experiments" return ( experiments_dir / "cache" / "canonical_indices" / granularity / f"{k}_prov={suffix}_lb={max_lb}_h={max_h}" ) def _stratified_sample( df: pd.DataFrame, n: int, strata_cols: list[str], seed: int, ) -> pd.DataFrame: """Stratified subsample of `df` to size `n`, preserving the joint distribution of `strata_cols` (Cartesian-product strata, with proportional allocation and remainder spread by row order). Deterministic at fixed `seed`. If `n >= len(df)`, returns df shuffled. """ if n >= len(df): return df.sample(frac=1.0, random_state=seed).reset_index(drop=True) # Drop rows with NaN in any stratifier column -- they would form a # spurious "missing" stratum. valid_mask = df[strata_cols].notna().all(axis=1) df_valid = df[valid_mask].copy() if df_valid.empty: # Fall back to uniform random return df.sample(n=n, random_state=seed).reset_index(drop=True) df_valid["_stratum"] = df_valid[strata_cols].astype(str).agg("|".join, axis=1) rng = np.random.RandomState(seed) out_rows: list[pd.DataFrame] = [] total = len(df_valid) for stratum, grp in df_valid.groupby("_stratum"): # Proportional allocation; at least 1 if stratum has rows. q = max(1, round(len(grp) * n / total)) q = min(q, len(grp)) out_rows.append(grp.sample(n=q, random_state=rng.randint(0, 2**31 - 1))) out = pd.concat(out_rows, ignore_index=True) # Trim or top-up to exactly n if len(out) > n: out = out.sample(n=n, random_state=seed).reset_index(drop=True) elif len(out) < n: # Top up with non-selected rows (still stratified by selection above) remaining = df_valid.loc[~df_valid.index.isin(out.index)] extra = remaining.sample(n=min(n - len(out), len(remaining)), random_state=seed) out = pd.concat([out, extra], ignore_index=True) return out.drop(columns=["_stratum"]).reset_index(drop=True) # ── Per-task generators ─────────────────────────────────────────────────── def _gen_t1( granularity: str, n_eval: int, n_train: int, seed: int, ) -> dict[Split, pd.DataFrame]: """T1 TSF: stratified by sector x market_cap_quartile. Each (ticker, anchor_date) pair must admit a complete ``(lookback, max_horizon)`` window inside the corresponding split's panel, so every horizon evaluated by every T1 runner reuses the same anchor set. Concretely, for a ticker with ``T`` panel rows we keep only anchor dates at per-ticker positions ``[lookback, T - max_horizon - 1]``. Returns DataFrames with columns (ticker, anchor_date, sector, mcap_q). """ from .. import config as _cfg # Build the canonical anchor pool against the SHORTEST lookback and # the LONGEST horizon. The test panel (post-2024-09-03) is ~378 # trading days; pairing max_lookback (252) with max_horizon (252) # exhausts it. Methods that want a longer lookback can request it # at load time (load(..., lookback=252)); anchors with insufficient # history will be dropped by _build_t1_x_y and counted in # ``meta.attrs["n_canonical_dropped"]``. lookback = _cfg.get_lookback_windows(granularity)[0] max_horizon = max(_cfg.get_horizons(granularity)) bench_dir = config.get_benchmark_dir(granularity) train = pd.read_parquet( bench_dir / "panel_train.parquet", columns=["ticker", "date", "sector", "derived_market_cap"], ) test = pd.read_parquet( bench_dir / "panel_test.parquet", columns=["ticker", "date", "sector", "derived_market_cap"], ) # Latest market_cap per ticker for the quartile assignment (across the # full panel, so train and eval split on the same definition). latest = ( pd.concat([train, test], ignore_index=True) .sort_values("date") .groupby("ticker") .tail(1)[["ticker", "derived_market_cap"]] ) latest["mcap_q"] = pd.qcut( latest["derived_market_cap"].clip(lower=1), 4, labels=["Q1", "Q2", "Q3", "Q4"], duplicates="drop", ) mcap_q = dict(zip(latest["ticker"], latest["mcap_q"])) def _restrict_to_valid_anchors(df: pd.DataFrame) -> pd.DataFrame: """Keep only rows at per-ticker positions [lookback, T-max_horizon-1] so a complete (lookback + max_horizon) window fits.""" df = df.sort_values(["ticker", "date"]).reset_index(drop=True) df["_row_in_ticker"] = df.groupby("ticker", sort=False).cumcount() df["_ticker_len"] = df.groupby("ticker", sort=False)["date"].transform("size") valid = (df["_row_in_ticker"] >= lookback) & ( df["_row_in_ticker"] < df["_ticker_len"] - max_horizon ) return df.loc[valid].drop(columns=["_row_in_ticker", "_ticker_len"]) out: dict[Split, pd.DataFrame] = {} for split, df in (("train", train), ("eval", test)): df = _restrict_to_valid_anchors(df) df = df.rename(columns={"date": "anchor_date"}).copy() df["mcap_q"] = df["ticker"].map(mcap_q) n = n_train if split == "train" else n_eval sampled = _stratified_sample(df, n, ["sector", "mcap_q"], seed) out[split] = sampled[["ticker", "anchor_date", "sector", "mcap_q"]] return out def _gen_t2_t5( granularity: str, task: str, n_eval: int, n_train: int, seed: int, ) -> dict[Split, pd.DataFrame]: """T2 (Val-PT) and T5 (Val-Priv): full 30% ticker holdout for eval; latest snapshot per non-holdout ticker for train. Returns DataFrames with columns (ticker, date). """ bench_dir = config.get_benchmark_dir(granularity) if task == "T2": inputs_path = bench_dir / "valuation_inputs.parquet" gt_path = bench_dir / "valuation_ground_truth.parquet" else: inputs_path = bench_dir / "private_valuation_inputs.parquet" gt_path = bench_dir / "private_valuation_ground_truth.parquet" inputs = pd.read_parquet(inputs_path, columns=["ticker", "date", "sector"]) gt = pd.read_parquet(gt_path, columns=["ticker", "date"]) # Restrict the eval pool to (ticker, date) pairs that are present in # BOTH inputs and gt. Without this, ~21 quarter-end snapshots per # task have inputs but no gt (close or shares_outstanding missing # on that date), and the loader silently dropped them at merge # time so canonical-eval N came up short of the budget. inputs["date"] = pd.to_datetime(inputs["date"]) gt["date"] = pd.to_datetime(gt["date"]) eval_pool = inputs.merge(gt, on=["ticker", "date"], how="inner") train_panel = pd.read_parquet( bench_dir / "panel_train.parquet", columns=["ticker", "date", "sector"], ) holdout_tickers = set(inputs["ticker"].unique()) non_holdout = train_panel[~train_panel["ticker"].isin(holdout_tickers)] # Latest snapshot per non-holdout ticker as the train set. train_latest = ( non_holdout.sort_values("date").groupby("ticker").tail(1) .reset_index(drop=True) ) rng = np.random.RandomState(seed) train_idx = train_latest.sample( n=min(n_train, len(train_latest)), random_state=rng.randint(0, 2**31 - 1), ).reset_index(drop=True) eval_idx = eval_pool.sample( n=min(n_eval, len(eval_pool)), random_state=rng.randint(0, 2**31 - 1), ).reset_index(drop=True) return {"train": train_idx, "eval": eval_idx} def _gen_t3_t6( granularity: str, task: str, n_eval: int, n_train: int, seed: int, ) -> dict[Split, pd.DataFrame]: """T3 (Stmt-Gen) and T6 (Gen-Eval): per-(ticker, fiscal_year) split. Every ticker in the per-task ground-truth file is also in the holdout (`*_inputs.parquet` lists holdout tickers only), so a plain ``~ticker.isin(holdout)`` train pool would always be empty. Instead: per ticker, the **latest** fiscal year is the eval anchor and **earlier** fiscal years are train anchors. Train-eval are cleanly separated by fiscal year within ticker; both pools are non-empty as long as a ticker has >=2 reported fiscal years. Eval = unique (ticker, latest_fiscal_year) pairs across all tickers. Train = unique (ticker, prior_fiscal_year) pairs across all tickers. """ bench_dir = config.get_benchmark_dir(granularity) if task == "T3": gt_path = bench_dir / "generation_ground_truth.parquet" else: gt_path = bench_dir / "generator_eval_ground_truth.parquet" gt = pd.read_parquet(gt_path) if "fiscal_year" not in gt.columns: if "filing_date" in gt.columns: gt["fiscal_year"] = pd.to_datetime(gt["filing_date"]).dt.year else: gt["fiscal_year"] = 0 pairs = gt[["ticker", "fiscal_year"]].drop_duplicates().reset_index(drop=True) pairs["fiscal_year"] = pd.to_numeric(pairs["fiscal_year"], errors="coerce") pairs = pairs.dropna(subset=["fiscal_year"]).copy() pairs["fiscal_year"] = pairs["fiscal_year"].astype(int) # Per-ticker: latest FY -> eval, earlier FYs -> train pairs = pairs.sort_values(["ticker", "fiscal_year"]).reset_index(drop=True) pairs["_rank_desc"] = pairs.groupby("ticker")["fiscal_year"].rank( method="first", ascending=False, ) eval_pairs = pairs[pairs["_rank_desc"] == 1][["ticker", "fiscal_year"]] train_pairs = pairs[pairs["_rank_desc"] > 1][["ticker", "fiscal_year"]] rng = np.random.RandomState(seed) eval_idx = eval_pairs.sample( n=min(n_eval, len(eval_pairs)), random_state=rng.randint(0, 2**31 - 1), ).reset_index(drop=True) train_idx = train_pairs.sample( n=min(n_train, len(train_pairs)), random_state=rng.randint(0, 2**31 - 1), ).reset_index(drop=True) return {"train": train_idx, "eval": eval_idx} def _gen_t4( granularity: str, n_eval: int, n_train: int, seed: int, ) -> dict[Split, pd.DataFrame]: """T4 Scen-Ret: stratified by sector x mcap_q x event_type. Returns DataFrames with columns (scenario_id, ticker, event_type). """ bench_dir = config.get_benchmark_dir(granularity) gt = pd.read_parquet( bench_dir / "scenario_forecast_ground_truth.parquet", columns=["scenario_id", "ticker", "event_type", "event_date", "actual_return_pct"], ) gt = gt.dropna(subset=["actual_return_pct"]) # Use the panel-train cutoff as the train/eval split anchor (matches # the canonical T1 split semantics). panel_train_df = pd.read_parquet( bench_dir / "panel_train.parquet", columns=["ticker", "date"], ) panel_test_df = pd.read_parquet( bench_dir / "panel_test.parquet", columns=["ticker", "date"], ) panel_train_df["date"] = pd.to_datetime(panel_train_df["date"]) panel_test_df["date"] = pd.to_datetime(panel_test_df["date"]) split_date = panel_train_df["date"].max() gt["event_date"] = pd.to_datetime(gt["event_date"]) # Restrict the eval/train pools to events whose ticker has at least # ``min_history`` panel days BEFORE the event date in the combined # panel. Without this filter, ~6.5% of train events sampled at the # canonical step cannot produce a valid 63-day lookback at load # time and were silently zero-padded then dropped. min_history = max(_cfg_get_lookback(granularity), 63) panel_full = pd.concat([panel_train_df, panel_test_df], ignore_index=True) panel_full = panel_full.drop_duplicates(subset=["ticker", "date"]) panel_dates_per_ticker = ( panel_full.sort_values(["ticker", "date"]).groupby("ticker")["date"] ) first_panel_date = panel_dates_per_ticker.first().to_dict() def _has_lookback_history(row) -> bool: first = first_panel_date.get(row["ticker"]) if first is None: return False # need at least min_history trading-day rows prior (use calendar # days as a fast upper bound: 252 trading days ~ 365 calendar days). return (row["event_date"] - first).days >= int(min_history * 1.45) gt = gt[gt.apply(_has_lookback_history, axis=1)].copy() train_pool = gt[gt["event_date"] <= split_date].copy() eval_pool = gt[gt["event_date"] > split_date].copy() # Sector and mcap_q come from the panel (across full date range). full_panel = pd.read_parquet( bench_dir / "panel_train.parquet", columns=["ticker", "sector", "derived_market_cap"], ) latest = full_panel.groupby("ticker").tail(1)[["ticker", "sector", "derived_market_cap"]] latest["mcap_q"] = pd.qcut( latest["derived_market_cap"].clip(lower=1), 4, labels=["Q1", "Q2", "Q3", "Q4"], duplicates="drop", ) sector_map = dict(zip(latest["ticker"], latest["sector"])) mcap_map = dict(zip(latest["ticker"], latest["mcap_q"])) out: dict[Split, pd.DataFrame] = {} for split, pool in (("train", train_pool), ("eval", eval_pool)): pool = pool.copy() pool["sector"] = pool["ticker"].map(sector_map) pool["mcap_q"] = pool["ticker"].map(mcap_map) n = n_train if split == "train" else n_eval sampled = _stratified_sample( pool, n, ["sector", "mcap_q", "event_type"], seed, ) out[split] = sampled[["scenario_id", "ticker", "event_type"]] return out def _gen_t7( granularity: str, n_eval: int, n_train: int, seed: int, ) -> dict[Split, pd.DataFrame]: """T7 RE-Val: stratified by property_type x state.""" bench_dir = config.get_benchmark_dir(granularity) train = pd.read_parquet(bench_dir / "re_train_properties.parquet") eval_in = pd.read_parquet(bench_dir / "re_eval_inputs.parquet") # ``re_train_properties`` carries 854 duplicate-address rows from # multiple RentCast variants of the same listing. Dedup BEFORE # sampling so the canonical eval set has unique addresses (the # loader otherwise dedups, leaving the canon n short of budget). if "address" in train.columns: train = train.drop_duplicates(subset="address", keep="first").reset_index(drop=True) if "address" in eval_in.columns: eval_in = eval_in.drop_duplicates(subset="address", keep="first").reset_index(drop=True) def _sample(df: pd.DataFrame, n: int) -> pd.DataFrame: ptype_col = next( (c for c in ("property_type", "propertyType", "type") if c in df.columns), None, ) state_col = next( (c for c in ("state", "State") if c in df.columns), None, ) addr_col = next( (c for c in ("address", "addressLine1", "Address") if c in df.columns), None, ) strata = [c for c in (ptype_col, state_col) if c is not None] if not strata or addr_col is None: return df.sample(n=min(n, len(df)), random_state=seed).reset_index(drop=True) sampled = _stratified_sample(df, n, strata, seed) cols_to_keep = [addr_col] + strata return sampled[cols_to_keep].rename(columns={addr_col: "address"}) return {"train": _sample(train, n_train), "eval": _sample(eval_in, n_eval)} _GENERATORS = { "T1": _gen_t1, "T2": lambda g, ne, nt, s: _gen_t2_t5(g, "T2", ne, nt, s), "T3": lambda g, ne, nt, s: _gen_t3_t6(g, "T3", ne, nt, s), "T4": _gen_t4, "T5": lambda g, ne, nt, s: _gen_t2_t5(g, "T5", ne, nt, s), "T6": lambda g, ne, nt, s: _gen_t3_t6(g, "T6", ne, nt, s), "T7": _gen_t7, } # ── Public API ──────────────────────────────────────────────────────────── def get_canonical_indices( task: Task, split: Split = "eval", *, granularity: str = "daily", n_eval: dict[Task, int] | None = None, n_train: dict[Task, int] | None = None, seed: int | None = None, ) -> pd.DataFrame: """Return the canonical index list for `(task, split)`. Reads from cache if available; otherwise generates, persists to cache, and returns. The cache key encodes (n_eval, n_train, seed, stratifier_version) so non-canonical re-tunes get their own cache dir. Smoke-mode override: when ``MACROLENS_N_TRAIN`` and / or ``MACROLENS_N_EVAL`` env vars are set (positive int), they replace the default budget for every task in this call. This lets the runner do an end-to-end smoke (e.g. n_train=2, n_eval=1 across all 22 methods × 7 tasks) without touching the canonical cache or the CLI signature. Explicit ``n_eval`` / ``n_train`` kwargs still take precedence. """ import os as _os env_n_eval = _os.environ.get("MACROLENS_N_EVAL") env_n_train = _os.environ.get("MACROLENS_N_TRAIN") if n_eval is None and env_n_eval is not None: try: v = int(env_n_eval) if v > 0: n_eval = {t: v for t in EVAL_N_PER_TASK} except ValueError: pass if n_train is None and env_n_train is not None: try: v = int(env_n_train) if v > 0: n_train = {t: v for t in TRAIN_N_PER_TASK} except ValueError: pass n_eval_map = n_eval or EVAL_N_PER_TASK n_train_map = n_train or TRAIN_N_PER_TASK s = SEED if seed is None else seed key = budgets.cache_key(n_eval=n_eval_map, n_train=n_train_map, seed=s) cache_dir = _cache_dir(granularity, key) cache_path = cache_dir / f"{split}_{task}.parquet" if cache_path.exists(): return pd.read_parquet(cache_path) # Cache miss: generate both splits for this task and persist. gen = _GENERATORS[task] pair = gen(granularity, n_eval_map[task], n_train_map[task], s) cache_dir.mkdir(parents=True, exist_ok=True) for sp, df in pair.items(): df.to_parquet(cache_dir / f"{sp}_{task}.parquet", index=False) logger.info( "Canonical-indices cache write: %s (%d rows)", cache_dir / f"{sp}_{task}.parquet", len(df), ) return pair[split] def build_all( granularity: str = "daily", *, n_eval: dict[Task, int] | None = None, n_train: dict[Task, int] | None = None, seed: int | None = None, ) -> dict[str, int]: """Build canonical indices for every (task, split) pair. Returns a summary dict mapping `_` -> n_rows. Idempotent: re-running with the same budgets is a no-op (cache hits). """ summary: dict[str, int] = {} for task in ("T1", "T2", "T3", "T4", "T5", "T6", "T7"): for split in ("train", "eval"): df = get_canonical_indices( task, split, granularity=granularity, n_eval=n_eval, n_train=n_train, seed=seed, ) summary[f"{task}_{split}"] = len(df) return summary