Download code/dataloader/load.py from DeepAuto-AI/MacroLens: direct link, hf CLI and curl.
- Browser
- Download file 28.9 kB
-
https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/dataloader/load.py
- Command line
-
hf download hf://datasets/DeepAuto-AI/MacroLens/code/dataloader/load.py
-
curl -L -o load.py https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/dataloader/load.py
28.9 kB
| """Canonical data loader for the MacroLens benchmark. | |
| Sklearn-style: every call to ``load(task, split)`` returns a | |
| ``LoadedData = NamedTuple[X, y, meta]`` triple. Train and test schemas are | |
| identical for every task (the v0.1 T2/T5 schema-mismatch bug is fixed | |
| here). Methods MUST consume only ``X`` (and at fit time, ``y``); they | |
| must NOT consume ``meta``. The runner uses ``meta`` to join predictions | |
| back to canonical keys. | |
| Per-task contract (definitive): | |
| * T1 (TSF): X = (N, lookback, F) float32, y = (N, horizon) float32 | |
| * T2 (Val-PT): X = pd.DataFrame, y = (N,) float32 actual_market_cap | |
| * T3 (Stmt-Gen): X = pd.DataFrame keyed by (ticker, fiscal_year), | |
| y = long-form pd.DataFrame[ticker, fiscal_year, field, value] | |
| * T4 (Scen-Ret): X = pd.DataFrame[lookback (object), event_type, event_description], | |
| y = (N,) float32 return_pct | |
| * T5 (Val-Priv): same shape as T2; price-derived inputs stripped | |
| * T6 (Gen-Eval): same shape as T3; X has no stmt_*, only NL company_description | |
| * T7 (RE-Val): X = pd.DataFrame[property attrs], | |
| y = pd.DataFrame[address, rent, price] | |
| ``meta.attrs`` is populated by every loader with:: | |
| { | |
| "task": str, "split": str, "granularity": str, | |
| "lookback": int | None, "horizon": int | None, | |
| "feature_names": list[str], # T1 / T4 only (lookback panel column names) | |
| "schema_version": int, | |
| "data_sha256": dict[str, str], # SHA-256 of every upstream parquet read | |
| "n_canonical_dropped": int, # canonical anchors lost (T1 only); RuntimeError if > 1% | |
| } | |
| """ | |
| from __future__ import annotations | |
| from typing import Any, NamedTuple | |
| import numpy as np | |
| import pandas as pd | |
| from .. import config | |
| from ._provenance import sha256_dataset | |
| from .canonical_indices import get_canonical_indices | |
| _LOADED_DATA_SCHEMA_VERSION = 2 | |
| # Curated dense-field panel for T3 (Stmt-Gen). The released T3 ground truth | |
| # parquet carries the full XBRL field universe (~10K tags, ~467K rows), but | |
| # long-tail company-extension tags appear in only 1–2 (ticker, fiscal_year) | |
| # pairs each, which makes whole-universe scoring scientifically meaningless. | |
| # We project T3's `y` to the same 11 standard XBRL line items released in | |
| # T6's curated panel. Projection lives in the loader; the on-disk parquet | |
| # is untouched. | |
| _T3_DENSE_FIELDS = frozenset({ | |
| "Assets", | |
| "Liabilities", | |
| "StockholdersEquity", | |
| "Revenues", | |
| "NetIncomeLoss", | |
| "OperatingIncomeLoss", | |
| "CashAndCashEquivalentsAtCarryingValue", | |
| "PropertyPlantAndEquipmentNet", | |
| "LongTermDebt", | |
| "ResearchAndDevelopmentExpense", | |
| "NetCashProvidedByUsedInOperatingActivities", | |
| }) | |
| # ── Public NamedTuple ───────────────────────────────────────────────────── | |
| class LoadedData(NamedTuple): | |
| """Sklearn-style ``(X, y, meta)`` triple returned by :func:`load`.""" | |
| X: Any | |
| y: Any | |
| meta: pd.DataFrame | |
| # ── Public entrypoint ───────────────────────────────────────────────────── | |
| def load( | |
| task: str, | |
| split: str, | |
| *, | |
| granularity: str = "daily", | |
| lookback: int | None = None, | |
| horizon: int | None = None, | |
| setting: str | None = None, | |
| ) -> LoadedData: | |
| """Load canonical task data for one ``(task, split)``. Identical across methods. | |
| ``setting`` (optional, one of ``"A".."E"``) projects the panel feature | |
| space to the named ablation tier. Applies only to T1, T2, T4, T5. | |
| """ | |
| if split not in ("train", "test"): | |
| raise ValueError(f"split must be 'train' or 'test', got {split!r}") | |
| canon_split = "eval" if split == "test" else "train" | |
| if lookback is None: | |
| lookback = config.get_lookback_windows(granularity)[0] | |
| if horizon is None: | |
| # Use the LONGEST horizon as the default (e.g. daily 63 trading days): | |
| # the headline T1 evaluation horizon per the project plan. | |
| horizon = config.get_horizons(granularity)[-1] | |
| if task == "T1": | |
| loaded = _load_t1(canon_split, split, granularity, lookback, horizon) | |
| elif task in ("T2", "T5"): | |
| loaded = _load_t2_t5(task, canon_split, split, granularity) | |
| elif task in ("T3", "T6"): | |
| loaded = _load_t3_t6(task, canon_split, split, granularity) | |
| elif task == "T4": | |
| loaded = _load_t4(canon_split, split, granularity, lookback) | |
| elif task == "T7": | |
| loaded = _load_t7(canon_split, split, granularity) | |
| else: | |
| raise ValueError(f"Unknown task: {task!r}") | |
| if setting is not None: | |
| from ._ablation import apply_to_loaded, ABLATION_SETTINGS | |
| if setting not in ABLATION_SETTINGS: | |
| raise ValueError( | |
| f"setting must be one of {ABLATION_SETTINGS} or None, " | |
| f"got {setting!r}" | |
| ) | |
| if task in ("T3", "T6", "T7"): | |
| raise ValueError( | |
| f"Ablation setting={setting!r} not supported for task={task!r}; " | |
| "ABLATION_TASKS = (T1, T2, T4, T5)" | |
| ) | |
| loaded = apply_to_loaded(loaded, setting) | |
| return loaded | |
| # ── Helpers ─────────────────────────────────────────────────────────────── | |
| def _panel_path(granularity: str, split: str) -> str: | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| return str(bench_dir / f"panel_{split}.parquet") | |
| def _set_meta_attrs( | |
| meta: pd.DataFrame, | |
| *, | |
| task: str, | |
| split: str, | |
| granularity: str, | |
| parquets_read: list, | |
| lookback: int | None = None, | |
| horizon: int | None = None, | |
| feature_names: list[str] | None = None, | |
| n_canonical_dropped: int = 0, | |
| ) -> None: | |
| meta.attrs.update({ | |
| "task": task, | |
| "split": split, | |
| "granularity": granularity, | |
| "lookback": lookback, | |
| "horizon": horizon, | |
| "feature_names": list(feature_names) if feature_names is not None else None, | |
| "schema_version": _LOADED_DATA_SCHEMA_VERSION, | |
| "data_sha256": sha256_dataset([str(p) for p in parquets_read]), | |
| "n_canonical_dropped": n_canonical_dropped, | |
| }) | |
| # ── T1 ──────────────────────────────────────────────────────────────────── | |
| def _build_t1_x_y( | |
| panel: pd.DataFrame, | |
| canon: pd.DataFrame, | |
| lookback: int, | |
| horizon: int, | |
| ) -> tuple[np.ndarray, np.ndarray, np.ndarray, list[str], np.ndarray]: | |
| """Build T1 ``(X, y, close_last, feat_names, keep_rows)`` given the | |
| canonical anchor pairs. | |
| """ | |
| panel = panel.sort_values(["ticker", "date"]).reset_index(drop=True) | |
| panel["date"] = pd.to_datetime(panel["date"]) | |
| exclude = { | |
| "ticker", "date", "label", "split", | |
| "nearest_filing_type", "nearest_filing_date", "nearest_filing_path", | |
| } | |
| feat_cols = [ | |
| c for c in panel.columns | |
| if c not in exclude and panel[c].dtype.kind in "fiub" | |
| ] | |
| per_ticker_feats: dict[str, np.ndarray] = {} | |
| per_ticker_close: dict[str, np.ndarray] = {} | |
| per_ticker_dates: dict[str, np.ndarray] = {} | |
| for ticker, grp in panel.groupby("ticker", sort=False): | |
| per_ticker_feats[str(ticker)] = grp[feat_cols].values.astype(np.float32) | |
| per_ticker_close[str(ticker)] = grp["close"].values.astype(np.float32) | |
| per_ticker_dates[str(ticker)] = grp["date"].values.astype("datetime64[ns]") | |
| canon = canon.copy() | |
| canon["ticker"] = canon["ticker"].astype(str) | |
| canon["anchor_date"] = pd.to_datetime(canon["anchor_date"]).values.astype("datetime64[ns]") | |
| X_list, y_list, cl_list, keep_rows = [], [], [], [] | |
| for i, (ticker, anchor) in enumerate(zip(canon["ticker"].values, canon["anchor_date"].values)): | |
| feats = per_ticker_feats.get(ticker) | |
| if feats is None: | |
| continue | |
| dates = per_ticker_dates[ticker] | |
| close = per_ticker_close[ticker] | |
| idx = np.searchsorted(dates, anchor) | |
| if idx >= len(dates) or dates[idx] != anchor: | |
| continue | |
| if idx + 1 < lookback or idx + horizon >= len(dates): | |
| continue | |
| lb = feats[idx - lookback + 1 : idx + 1] | |
| tg = close[idx + 1 : idx + 1 + horizon] | |
| if lb.shape != (lookback, len(feat_cols)) or tg.shape != (horizon,): | |
| continue | |
| X_list.append(lb) | |
| y_list.append(tg) | |
| cl_list.append(float(close[idx])) | |
| keep_rows.append(i) | |
| if not X_list: | |
| raise RuntimeError( | |
| f"T1 loader produced 0 windows from {len(canon)} canonical anchors; " | |
| "panel and canonical-index cache are out of sync." | |
| ) | |
| X = np.stack(X_list, axis=0) | |
| y = np.stack(y_list, axis=0) | |
| cl = np.array(cl_list, dtype=np.float32) | |
| return X, y, cl, feat_cols, np.array(keep_rows, dtype=np.int64) | |
| def _load_t1( | |
| canon_split: str, | |
| out_split: str, | |
| granularity: str, | |
| lookback: int, | |
| horizon: int, | |
| ) -> LoadedData: | |
| canon = get_canonical_indices("T1", canon_split, granularity=granularity) | |
| if canon.empty: | |
| raise RuntimeError(f"Canonical T1/{canon_split} index set is empty.") | |
| panel_path = _panel_path(granularity, out_split) | |
| panel = pd.read_parquet(panel_path) | |
| X, y, close_last, feat_cols, keep_rows = _build_t1_x_y(panel, canon, lookback, horizon) | |
| n_dropped = len(canon) - len(keep_rows) | |
| drop_frac = n_dropped / max(1, len(canon)) | |
| if drop_frac > 0.01: | |
| raise RuntimeError( | |
| f"T1/{out_split} loader dropped {n_dropped}/{len(canon)} canonical " | |
| f"anchors ({drop_frac:.1%} > 1% tolerance). The canonical generator " | |
| "and the benchmark panel are out of sync; rebuild the canonical-indices " | |
| "cache or fix the benchmark parquet." | |
| ) | |
| meta = canon.iloc[keep_rows][["ticker", "anchor_date", "sector", "mcap_q"]].copy() | |
| meta["close_last"] = close_last | |
| meta = meta.reset_index(drop=True) | |
| _set_meta_attrs( | |
| meta, task="T1", split=out_split, granularity=granularity, | |
| parquets_read=[panel_path], lookback=lookback, horizon=horizon, | |
| feature_names=feat_cols, n_canonical_dropped=n_dropped, | |
| ) | |
| return LoadedData(X=X, y=y, meta=meta) | |
| # ── T2 / T5 ─────────────────────────────────────────────────────────────── | |
| def _t2_t5_paths(task: str, granularity: str): | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| if task == "T2": | |
| return bench_dir / "valuation_inputs.parquet", bench_dir / "valuation_ground_truth.parquet" | |
| return bench_dir / "private_valuation_inputs.parquet", bench_dir / "private_valuation_ground_truth.parquet" | |
| def _load_t2_t5( | |
| task: str, canon_split: str, out_split: str, granularity: str, | |
| ) -> LoadedData: | |
| canon = get_canonical_indices(task, canon_split, granularity=granularity) | |
| if canon.empty: | |
| raise RuntimeError(f"Canonical {task}/{canon_split} index set is empty.") | |
| inputs_path, gt_path = _t2_t5_paths(task, granularity) | |
| panel_train_path = _panel_path(granularity, "train") | |
| panel_test_path = _panel_path(granularity, "test") | |
| inputs = pd.read_parquet(inputs_path) | |
| gt = pd.read_parquet(gt_path) | |
| inputs["date"] = pd.to_datetime(inputs["date"]) | |
| gt["date"] = pd.to_datetime(gt["date"]) | |
| canon = canon.copy() | |
| canon["date"] = pd.to_datetime(canon["date"]) | |
| parquets_read: list = [inputs_path, gt_path] | |
| # Schema = inputs-file columns + macro snapshot (fred_*/eia_*) joined | |
| # from the panel. The construction pipeline emits identical macro | |
| # columns in panel_train and panel_test, so the train/test schemas | |
| # match exactly after the merge. | |
| inputs_feature_cols = [c for c in inputs.columns if c not in {"ticker", "date"}] | |
| panel_train = pd.read_parquet(panel_train_path) | |
| panel_train["date"] = pd.to_datetime(panel_train["date"]) | |
| parquets_read.append(panel_train_path) | |
| macro_cols = sorted([ | |
| c for c in panel_train.columns | |
| if c.startswith("fred_") or c.startswith("eia_") | |
| ]) | |
| feature_cols = inputs_feature_cols + macro_cols | |
| if out_split == "train": | |
| # panel_train carries both the inputs-file columns AND the macro | |
| # snapshot, so a single inner merge populates everything. | |
| canon_keep = ["ticker", "date"] | |
| present = [c for c in inputs_feature_cols if c in panel_train.columns] | |
| missing = [c for c in inputs_feature_cols if c not in panel_train.columns] | |
| merged = canon[canon_keep].merge( | |
| panel_train[["ticker", "date", *present, *macro_cols]], | |
| on=["ticker", "date"], how="inner", | |
| ) | |
| for c in missing: | |
| merged[c] = np.nan | |
| # Train labels: derived_market_cap from panel_train (already merged). | |
| if "derived_market_cap" in panel_train.columns: | |
| mcap = canon.merge( | |
| panel_train[["ticker", "date", "derived_market_cap"]], | |
| on=["ticker", "date"], how="inner", | |
| )["derived_market_cap"] | |
| y_series = pd.to_numeric(mcap, errors="coerce").reset_index(drop=True) | |
| else: | |
| raise RuntimeError( | |
| f"{task}/train: panel_train has no derived_market_cap column" | |
| ) | |
| else: | |
| # Test side: inputs file does not carry fred_*/eia_*; left-join | |
| # the macro snapshot from the panel. T2/T5 use a company-level | |
| # holdout (not chronological), so a holdout-ticker's anchor date | |
| # can fall in either the pre- or post-cutoff window. Union both | |
| # panels so the macro lookup covers the full 2021–2026 range. | |
| panel_test = pd.read_parquet(panel_test_path) | |
| panel_test["date"] = pd.to_datetime(panel_test["date"]) | |
| parquets_read.append(panel_test_path) | |
| macro_present_train = [c for c in macro_cols if c in panel_train.columns] | |
| macro_present_test = [c for c in macro_cols if c in panel_test.columns] | |
| macro_present = sorted(set(macro_present_train) & set(macro_present_test)) | |
| macro_lookup = pd.concat([ | |
| panel_train[["ticker", "date", *macro_present]], | |
| panel_test[["ticker", "date", *macro_present]], | |
| ], ignore_index=True).drop_duplicates( | |
| subset=["ticker", "date"], keep="first", | |
| ) | |
| merged = canon[["ticker", "date"]].merge( | |
| inputs, on=["ticker", "date"], how="inner", | |
| ).merge( | |
| gt[["ticker", "date", "actual_market_cap"]], | |
| on=["ticker", "date"], how="inner", | |
| ).merge( | |
| macro_lookup, on=["ticker", "date"], how="left", | |
| ) | |
| for c in macro_cols: | |
| if c not in merged.columns: | |
| merged[c] = np.nan | |
| y_series = pd.to_numeric( | |
| merged.pop("actual_market_cap"), errors="coerce", | |
| ).reset_index(drop=True) | |
| if merged.empty: | |
| raise RuntimeError( | |
| f"{task}/{out_split} loader: zero rows after canonical join." | |
| ) | |
| # Project to the unified schema (inputs cols + macro cols). Train and | |
| # test now produce the exact same columns. | |
| feat_cols_present = [c for c in feature_cols if c in merged.columns] | |
| X = merged[feat_cols_present].copy().reset_index(drop=True) | |
| meta_cols = ["ticker", "date"] | |
| if "sector" in merged.columns: | |
| meta_cols.append("sector") | |
| meta = merged[meta_cols].copy().reset_index(drop=True) | |
| # mcap_q (market-cap quartile) — derived from y on the held-out test | |
| # rows so cross-sectional stratification can run without leaking the | |
| # train distribution. For train rows we still compute quartiles over | |
| # the train y for parity but downstream callers only stratify test. | |
| if y_series.size: | |
| try: | |
| qs = pd.qcut(y_series, q=4, labels=["Q1", "Q2", "Q3", "Q4"], | |
| duplicates="drop") | |
| meta["mcap_q"] = qs.astype(str).values | |
| except ValueError: | |
| meta["mcap_q"] = "Q?" | |
| _set_meta_attrs( | |
| meta, task=task, split=out_split, granularity=granularity, | |
| parquets_read=parquets_read, feature_names=list(X.columns), | |
| ) | |
| return LoadedData(X=X, y=y_series.to_numpy(dtype=np.float32), meta=meta) | |
| # ── T3 / T6 ─────────────────────────────────────────────────────────────── | |
| def _t3_t6_paths(task: str, granularity: str): | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| if task == "T3": | |
| return bench_dir / "generation_inputs.parquet", bench_dir / "generation_ground_truth.parquet", "field" | |
| return bench_dir / "generator_eval_inputs.parquet", bench_dir / "generator_eval_ground_truth.parquet", "generator_field" | |
| def _load_t3_t6( | |
| task: str, canon_split: str, out_split: str, granularity: str, | |
| ) -> LoadedData: | |
| canon = get_canonical_indices(task, canon_split, granularity=granularity) | |
| if canon.empty: | |
| raise RuntimeError(f"Canonical {task}/{canon_split} index set is empty.") | |
| inputs_path, gt_path, field_col = _t3_t6_paths(task, granularity) | |
| inputs = pd.read_parquet(inputs_path) | |
| gt = pd.read_parquet(gt_path) | |
| if field_col not in gt.columns and "field" in gt.columns: | |
| field_col = "field" | |
| 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 | |
| canon = canon.copy() | |
| canon["fiscal_year"] = pd.to_numeric(canon["fiscal_year"], errors="coerce").astype("Int64") | |
| # X: per-(ticker, fiscal_year). For T3 inputs file is per-ticker (one | |
| # row per holdout ticker); broadcast across the canonical (ticker, | |
| # fiscal_year) pairs. | |
| if "fiscal_year" in inputs.columns: | |
| X = canon.merge(inputs, on=["ticker", "fiscal_year"], how="left") | |
| else: | |
| X = canon.merge(inputs, on="ticker", how="left") | |
| # y: long-form restricted to canonical (ticker, fiscal_year) pairs. | |
| canon_keys = set(zip( | |
| canon["ticker"].astype(str), | |
| canon["fiscal_year"].astype("Int64").astype(str), | |
| )) | |
| gt_filt = gt.copy() | |
| gt_filt["fiscal_year"] = pd.to_numeric(gt_filt["fiscal_year"], errors="coerce").astype("Int64") | |
| gt_filt["_key"] = list(zip( | |
| gt_filt["ticker"].astype(str), | |
| gt_filt["fiscal_year"].astype(str), | |
| )) | |
| gt_filt = gt_filt[gt_filt["_key"].isin(canon_keys)].drop(columns=["_key"]).reset_index(drop=True) | |
| if field_col != "field": | |
| gt_filt = gt_filt.rename(columns={field_col: "field"}) | |
| if task == "T3": | |
| # T3 evaluates on the dense 11-field panel (same fields T6 uses). | |
| # The released ``generation_ground_truth.parquet`` ships the full | |
| # XBRL universe (10,279 unique tags including company-extension | |
| # tags filed once by one issuer); per-field MAPE on those is noise. | |
| # Projection happens at load time so the on-disk parquet is | |
| # preserved; evaluation runs on the meaningful subset. | |
| gt_filt = gt_filt[gt_filt["field"].astype(str).isin(_T3_DENSE_FIELDS)].reset_index(drop=True) | |
| y = gt_filt[["ticker", "fiscal_year", "field", "value"]].copy() | |
| meta = canon[["ticker", "fiscal_year"]].copy().reset_index(drop=True) | |
| X = X.reset_index(drop=True) | |
| _set_meta_attrs( | |
| meta, task=task, split=out_split, granularity=granularity, | |
| parquets_read=[inputs_path, gt_path], | |
| feature_names=[c for c in X.columns if c not in {"ticker", "fiscal_year"}], | |
| ) | |
| return LoadedData(X=X, y=y, meta=meta) | |
| # ── T4 ──────────────────────────────────────────────────────────────────── | |
| def _load_t4( | |
| canon_split: str, out_split: str, granularity: str, lookback: int, | |
| ) -> LoadedData: | |
| canon = get_canonical_indices("T4", canon_split, granularity=granularity) | |
| if canon.empty: | |
| raise RuntimeError(f"Canonical T4/{canon_split} index set is empty.") | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| gt_path = bench_dir / "scenario_forecast_ground_truth.parquet" | |
| scen_path = bench_dir / "scenarios.parquet" | |
| # T4 lookback windows can span the train/test split (an event close to | |
| # the cutoff needs ~63 trading days of history that may sit on the | |
| # other side). Read both panels and merge for the lookback build. | |
| panel_train_path = _panel_path(granularity, "train") | |
| panel_test_path = _panel_path(granularity, "test") | |
| gt = pd.read_parquet(gt_path).dropna(subset=["actual_return_pct"]) | |
| gt["event_date"] = pd.to_datetime(gt["event_date"]) | |
| scen_full = pd.read_parquet(scen_path) | |
| desc_col = "event_description" if "event_description" in scen_full.columns else None | |
| keep_scen_cols = ["scenario_id"] + ([desc_col] if desc_col else []) | |
| scen = scen_full[keep_scen_cols].drop_duplicates("scenario_id") | |
| canon = canon.copy() | |
| canon["scenario_id"] = canon["scenario_id"].astype(str) | |
| canon["ticker"] = canon["ticker"].astype(str) | |
| gt["scenario_id"] = gt["scenario_id"].astype(str) | |
| gt["ticker"] = gt["ticker"].astype(str) | |
| scen["scenario_id"] = scen["scenario_id"].astype(str) | |
| # Filter ground truth to canonical pairs | |
| canon_keys = set(zip(canon["scenario_id"], canon["ticker"])) | |
| gt["_key"] = list(zip(gt["scenario_id"], gt["ticker"])) | |
| gt_filt = gt[gt["_key"].isin(canon_keys)].drop(columns=["_key"]).reset_index(drop=True) | |
| if gt_filt.empty: | |
| raise RuntimeError(f"T4/{out_split} loader: zero rows after canonical join.") | |
| if desc_col is not None: | |
| gt_filt = gt_filt.merge( | |
| scen[["scenario_id", desc_col]], on="scenario_id", how="left", | |
| ) | |
| # Lookback windows from the COMBINED panel (train + test) — a T4 | |
| # event near the chronological cutoff needs lookback rows on the | |
| # other side of the split. | |
| panel_train_df = pd.read_parquet(panel_train_path) | |
| panel_test_df = pd.read_parquet(panel_test_path) | |
| panel = pd.concat([panel_train_df, panel_test_df], ignore_index=True) | |
| del panel_train_df, panel_test_df | |
| panel["date"] = pd.to_datetime(panel["date"]) | |
| panel = panel.sort_values(["ticker", "date"]).drop_duplicates( | |
| subset=["ticker", "date"], keep="first", | |
| ).reset_index(drop=True) | |
| exclude = { | |
| "ticker", "date", "label", "split", | |
| "nearest_filing_type", "nearest_filing_date", "nearest_filing_path", | |
| } | |
| feat_cols = [ | |
| c for c in panel.columns | |
| if c not in exclude and panel[c].dtype.kind in "fiub" | |
| ] | |
| per_ticker_feats: dict[str, np.ndarray] = {} | |
| per_ticker_dates: dict[str, np.ndarray] = {} | |
| for ticker, grp in panel.groupby("ticker", sort=False): | |
| per_ticker_feats[str(ticker)] = grp[feat_cols].values.astype(np.float32) | |
| per_ticker_dates[str(ticker)] = grp["date"].values.astype("datetime64[ns]") | |
| lb_list: list[np.ndarray] = [] | |
| valid = np.zeros(len(gt_filt), dtype=bool) | |
| for i, (ticker, ev_date) in enumerate(zip( | |
| gt_filt["ticker"].values, | |
| gt_filt["event_date"].values.astype("datetime64[ns]"), | |
| )): | |
| feats = per_ticker_feats.get(str(ticker)) | |
| if feats is None: | |
| lb_list.append(np.zeros((lookback, len(feat_cols)), dtype=np.float32)) | |
| continue | |
| dates = per_ticker_dates[str(ticker)] | |
| idx = np.searchsorted(dates, ev_date, side="right") - 1 | |
| if idx + 1 < lookback: | |
| lb_list.append(np.zeros((lookback, len(feat_cols)), dtype=np.float32)) | |
| continue | |
| lb = feats[idx - lookback + 1 : idx + 1] | |
| if lb.shape != (lookback, len(feat_cols)): | |
| lb_list.append(np.zeros((lookback, len(feat_cols)), dtype=np.float32)) | |
| continue | |
| lb_list.append(lb) | |
| valid[i] = True | |
| keep = np.where(valid)[0] | |
| if len(keep) == 0: | |
| raise RuntimeError(f"T4/{out_split} loader: no valid lookback windows after panel join.") | |
| gt_filt = gt_filt.iloc[keep].reset_index(drop=True) | |
| lb_arr = [lb_list[i] for i in keep] | |
| # T4 X is a DataFrame (not a dict): one row per (scenario_id, ticker), | |
| # with `lookback` as an object-dtype column where each cell is a | |
| # (lookback, F) np.ndarray. event_type and event_description are string | |
| # columns. Methods consume X uniformly. | |
| X = pd.DataFrame({ | |
| "lookback": lb_arr, | |
| "event_type": gt_filt["event_type"].astype(str).values, | |
| "event_description": ( | |
| gt_filt[desc_col].astype(str).values if desc_col is not None | |
| else np.array([""] * len(gt_filt)) | |
| ), | |
| }) | |
| y = gt_filt["actual_return_pct"].astype(np.float32).to_numpy() | |
| meta = gt_filt[["scenario_id", "ticker", "event_type", "event_date"]].copy().reset_index(drop=True) | |
| _set_meta_attrs( | |
| meta, task="T4", split=out_split, granularity=granularity, | |
| parquets_read=[gt_path, scen_path, panel_train_path, panel_test_path], | |
| lookback=lookback, feature_names=feat_cols, | |
| ) | |
| return LoadedData(X=X, y=y, meta=meta) | |
| # ── T7 ──────────────────────────────────────────────────────────────────── | |
| def _load_t7(canon_split: str, out_split: str, granularity: str) -> LoadedData: | |
| canon = get_canonical_indices("T7", canon_split, granularity=granularity) | |
| if canon.empty: | |
| raise RuntimeError(f"Canonical T7/{canon_split} index set is empty.") | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| train_src_path = bench_dir / "re_train_properties.parquet" | |
| test_src_path = bench_dir / "re_eval_inputs.parquet" | |
| test_gt_path = bench_dir / "re_eval_ground_truth.parquet" | |
| # Read BOTH src files to compute the column intersection (the smaller | |
| # test schema is the canonical one; train rows are projected onto it | |
| # so train ↔ test are schema-identical). | |
| test_src = pd.read_parquet(test_src_path) | |
| train_src = pd.read_parquet(train_src_path) | |
| common_cols = [c for c in test_src.columns if c in train_src.columns] | |
| if "address" not in common_cols: | |
| raise RuntimeError( | |
| "T7 loader: 'address' missing from re_eval_inputs ∩ re_train_properties columns" | |
| ) | |
| if out_split == "train": | |
| src = train_src[common_cols].copy() | |
| # Train ground truth comes from re_train_properties' rent/price columns; | |
| # they're already in train_src. | |
| gt_cols = [c for c in ("address", "rent", "price") if c in train_src.columns] | |
| gt = train_src[gt_cols].copy() | |
| parquets_read = [train_src_path] | |
| else: | |
| src = test_src[common_cols].copy() | |
| gt = pd.read_parquet(test_gt_path) | |
| parquets_read = [test_src_path, test_gt_path] | |
| canon = canon.copy() | |
| canon["address"] = canon["address"].astype(str) | |
| src["address"] = src["address"].astype(str) | |
| gt["address"] = gt["address"].astype(str) | |
| # Fix the v0.1 T7 duplicate-address Cartesian product bug. Dedup | |
| # canon, src, and gt — canon itself can carry duplicates (the T7 | |
| # canonical sampler does not enforce address-uniqueness on the train | |
| # pool), and an upstream duplicate quietly multiplies on the merge. | |
| canon_dedup = canon.drop_duplicates(subset="address", keep="first").reset_index(drop=True) | |
| src_dedup = src.drop_duplicates(subset="address", keep="first").reset_index(drop=True) | |
| gt_dedup = gt.drop_duplicates(subset="address", keep="first").reset_index(drop=True) | |
| X = canon_dedup[["address"]].merge(src_dedup, on="address", how="left") | |
| y_join = canon_dedup[["address"]].merge(gt_dedup, on="address", how="left") | |
| if X.empty: | |
| raise RuntimeError( | |
| f"T7/{out_split} loader: zero rows after canonical address join." | |
| ) | |
| # Lock the y column order so train and test produce identical column | |
| # ordering. Methods may rely on positional column access. | |
| y = y_join.reindex(columns=["address", "rent", "price"]).reset_index(drop=True) | |
| X = X.reset_index(drop=True) | |
| meta_cols = ["address"] + [c for c in ("property_type", "state") if c in canon_dedup.columns] | |
| meta = canon_dedup[meta_cols].reset_index(drop=True) | |
| _set_meta_attrs( | |
| meta, task="T7", split=out_split, granularity=granularity, | |
| parquets_read=parquets_read, | |
| feature_names=[c for c in X.columns if c != "address"], | |
| ) | |
| return LoadedData(X=X, y=y, meta=meta) | |