MacroLens / code /dataloader /_ablation.py
itouchz's picture
Add code/macrolens/ + code/dataloader/ packages; fix README path prefixes
f02626b verified
Raw
History Blame Contribute Delete
8.07 kB
"""Feature-group filter for the 5-step context ablation (A--E).
The ablation isolates the marginal value of each context source on the
panel-best LLM. Settings nest:
A: OHLCV only
B: A + Fundamentals (XBRL stmt_* + derived_* + shares_outstanding + fullTimeEmployees)
C: B + Macro (fred_* + eia_*)
D: C + Scenario flags (days_since_filing, filing_8k_count_30d,
news_count_7d, has_press_release_7d)
E: D + Filing text (handled in the LLM prompt; numeric features
identical to D)
Only the LLM ablation runs use this filter; classical / sequence / TSFM
methods always see the full feature set in the main panel results.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
ABLATION_SETTINGS: tuple[str, ...] = ("A", "B", "C", "D", "E")
OHLCV: tuple[str, ...] = (
"open", "high", "low", "close", "volume", "adj_close",
)
# Static fundamentals not following a prefix
_STATIC_FUNDAMENTALS: tuple[str, ...] = (
"shares_outstanding", "fullTimeEmployees",
)
# Scenario / event flags (proxy for macro-event signal in the panel;
# the broader 1,130-event scenario layer enters via the prompt for T4
# and via news/8K density features here).
SCENARIO_FLAGS: tuple[str, ...] = (
"days_since_filing",
"filing_8k_count_30d",
"news_count_7d",
"has_press_release_7d",
)
def _is_fundamentals(name: str) -> bool:
return (
name.startswith("stmt_")
or name.startswith("derived_")
or name in _STATIC_FUNDAMENTALS
)
def _is_macro(name: str) -> bool:
return name.startswith("fred_") or name.startswith("eia_")
def _is_scenario(name: str) -> bool:
return name in SCENARIO_FLAGS
def column_mask(feature_names: list[str], setting: str) -> list[bool]:
"""Return a per-column bool mask for the requested setting.
The mask is over ``feature_names``; elements set to True are KEPT.
"""
if setting not in ABLATION_SETTINGS:
raise ValueError(
f"setting must be one of {ABLATION_SETTINGS}, got {setting!r}"
)
keep: list[bool] = []
for n in feature_names:
if n in OHLCV:
keep.append(True)
continue
if setting == "A":
keep.append(False)
continue
if _is_fundamentals(n):
keep.append(True)
continue
if setting == "B":
keep.append(False)
continue
if _is_macro(n):
keep.append(True)
continue
if setting == "C":
keep.append(False)
continue
if _is_scenario(n):
keep.append(True)
continue
# setting D or E: keep nothing else (unknown columns excluded)
keep.append(False)
return keep
def filter_columns(
feature_names: list[str], setting: str,
) -> list[str]:
"""Return the kept feature names for ``setting``."""
mask = column_mask(feature_names, setting)
return [n for n, k in zip(feature_names, mask) if k]
def apply_to_t1_array(
X: np.ndarray, feature_names: list[str], setting: str,
) -> tuple[np.ndarray, list[str]]:
"""Filter T1 ``(N, L, F)`` array to the columns of ``setting``."""
if X.ndim != 3:
raise ValueError(f"T1 X must be 3D (N,L,F); got shape={X.shape}")
if X.shape[2] != len(feature_names):
raise ValueError(
f"T1 X feature dim {X.shape[2]} != len(feature_names) "
f"{len(feature_names)}"
)
mask = column_mask(feature_names, setting)
keep_idx = [i for i, k in enumerate(mask) if k]
if not keep_idx:
raise RuntimeError(
f"setting={setting!r} produced 0 kept columns from "
f"{len(feature_names)} features"
)
new_X = X[:, :, keep_idx].astype(X.dtype, copy=False)
new_names = [feature_names[i] for i in keep_idx]
return new_X, new_names
def apply_to_dataframe(
X: pd.DataFrame, setting: str, *, lookback_cell_col: str | None = None,
) -> pd.DataFrame:
"""Filter a 2D DataFrame to the columns of ``setting``.
For T4 the dataframe carries a ``lookback`` cell column whose values
are ``(L, F)`` numpy arrays; pass ``lookback_cell_col`` so we can also
project the cell-arrays to the same column subset. The prefix-based
test on the dataframe's own columns still runs for any side-by-side
numeric columns.
"""
df = X.copy()
if lookback_cell_col and lookback_cell_col in df.columns:
# The (L, F) arrays in this column do not carry their feature
# names with them. Trust meta.attrs["feature_names"]; resolve at
# the call site that has access to it. This branch is wired
# through ``apply_to_loaded`` below.
pass
# Project numeric columns if any exist
keep = []
for c in df.columns:
if c in OHLCV:
keep.append(c)
continue
if setting == "A":
continue
if _is_fundamentals(c):
keep.append(c)
continue
if setting == "B":
continue
if _is_macro(c):
keep.append(c)
continue
if setting == "C":
continue
if _is_scenario(c):
keep.append(c)
continue
# Always preserve non-feature object cols (sector dummies, text fields
# that the method may consume) by keeping any column that has no
# known prefix and is not numeric.
extra = [c for c in df.columns if c not in keep and df[c].dtype == object]
return df[keep + extra]
def apply_to_loaded(
loaded: "Any", setting: str, # type: ignore[name-defined]
): # -> LoadedData
"""Filter a ``LoadedData`` tuple in-place semantics; returns a new tuple.
Handles the four ablation tasks:
T1: 3D ndarray (N, L, F) -- mask axis 2
T2 / T5: 2D DataFrame -- drop columns
T4: DataFrame with `lookback` cell column -- project each cell
"""
from typing import NamedTuple
X, y, meta = loaded
feat_names = list(meta.attrs.get("feature_names") or [])
task = meta.attrs.get("task")
if task == "T1":
new_X, new_names = apply_to_t1_array(X, feat_names, setting)
new_meta = meta.copy()
new_meta.attrs.update(meta.attrs)
new_meta.attrs["feature_names"] = new_names
new_meta.attrs["ablation_setting"] = setting
return type(loaded)(new_X, y, new_meta)
if task in ("T2", "T5"):
if not isinstance(X, pd.DataFrame):
raise TypeError(f"T2/T5 X expected DataFrame, got {type(X)}")
new_X = apply_to_dataframe(X, setting)
new_meta = meta.copy()
new_meta.attrs.update(meta.attrs)
new_meta.attrs["feature_names"] = list(new_X.columns)
new_meta.attrs["ablation_setting"] = setting
return type(loaded)(new_X, y, new_meta)
if task == "T4":
if not isinstance(X, pd.DataFrame):
raise TypeError(f"T4 X expected DataFrame, got {type(X)}")
if not feat_names:
raise RuntimeError(
"T4 ablation requires meta.attrs['feature_names'] to be "
"set by the loader; was None/empty."
)
mask = column_mask(feat_names, setting)
keep_idx = [i for i, k in enumerate(mask) if k]
new_X = X.copy()
if "lookback" in new_X.columns:
def _project(arr):
if arr is None:
return arr
if hasattr(arr, "shape") and arr.ndim == 2:
return arr[:, keep_idx]
return arr
new_X["lookback"] = new_X["lookback"].apply(_project)
new_meta = meta.copy()
new_meta.attrs.update(meta.attrs)
new_meta.attrs["feature_names"] = [feat_names[i] for i in keep_idx]
new_meta.attrs["ablation_setting"] = setting
return type(loaded)(new_X, y, new_meta)
raise ValueError(
f"Ablation not supported for task={task!r}; "
"ABLATION_TASKS = (T1, T2, T4, T5)"
)