MacroLens / code /methods /classical.py
itouchz's picture
Upload methods/ (18-method baseline panel implementations)
02412f8 verified
Raw
History Blame Contribute Delete
76.4 kB
"""Classical (gradient-boosted) methods for the MacroLens unified API.
One concrete class — :class:`LightGBMRegressor` — that covers all 7 tasks
via task-specific private methods. Sklearn-style ``Method`` contract::
LightGBMRegressor(*, task=..., config=...) ↦
.fit(X, y, *, seed=42) ↦ self
.predict(X) ↦ ndarray | DataFrame
.save(path) / .load(path)
Per-task feature engineering mirrors the legacy ``baselines/classical.py``
recipe verbatim (numerics preserved); only the IO / canonical-indices /
eval / subsampling layer is stripped. See plan §9 for the predict-output
shape per task.
Per-task summary (definitive — runner asserts ``predict`` shape):
T1 — Time-series forecasting:
X : ``np.ndarray`` ``(N, lookback, F)`` float32.
y : ``np.ndarray`` ``(N, horizon)`` float32 close trajectory.
Pipeline: per-horizon-step LightGBM. One booster per horizon
index ``h ∈ [0, horizon)`` predicting ``y[:, h]`` from the
flattened ``(lookback × F)`` panel + rolling-close stats.
NO scalar+tile broadcasting hack.
Output: ``(N, horizon)`` float32.
T2 / T5 — Valuation:
X : ``pd.DataFrame`` of ``stmt_*`` (+ ``derived_*`` for T2)
numeric features plus sector / industry one-hot.
y : ``np.ndarray`` ``(N,)`` market_cap.
Pipeline: log-target via sklearn ``Pipeline([scale, lgbm])``
wrapped in ``TransformedTargetRegressor`` (log1p / expm1).
Output: ``(N,)`` float32 — predicted equity value.
T3 / T6 — Per-field generation:
X : ``pd.DataFrame`` keyed by ``(ticker, fiscal_year)`` with
numeric snapshot fields + sector + industry; T6 also has a
``company_description`` text column which is DROPPED in the
default branch (``t6_text_handling="sector_industry_only"``).
y : long-form ``pd.DataFrame[ticker, fiscal_year, field, value]``.
Pipeline: ensemble of one booster per ``field``. ``fitted_fields``
is locked at fit time to ``sorted(y["field"].unique())``. At
predict, every (ticker, fiscal_year) row in ``X`` emits one row
per fitted field.
Output: long-form ``[ticker, fiscal_year, field, pred]``.
T4 — Scenario return:
X : ``pd.DataFrame`` with object-dtype ``lookback`` cells (each
a ``(L, F)`` ndarray) plus ``event_type`` and
``event_description`` string columns. ``event_description`` is
DROPPED in v1.
y : ``np.ndarray`` ``(N,)`` return_pct.
Pipeline: flatten lookback (full L*F) + event_type one-hot.
Output: ``(N,)`` float32 — predicted return %.
T7 — Real-estate valuation:
X : ``pd.DataFrame`` with property attributes (``sqft``, ``beds``,
``baths``, ``year_built``, optionally ``years_since_last_sale``)
and a property-type column.
y : ``pd.DataFrame[address, rent, price]``.
Pipeline: two boosters (one for rent, one for price) with
log-target via ``TransformedTargetRegressor``.
Output: ``pd.DataFrame[address, pred_rent, pred_price]``.
Hard rules (enforced by ``tests/test_layer_isolation.py``):
* Zero IO (no ``pd.read_parquet``, no file reads, no ``config`` imports).
* Zero ``meta`` consumption — methods take only ``X`` (and at fit time,
``y``).
* Zero canonical-indices imports / subsampling.
* Zero eval imports.
"""
from __future__ import annotations
import importlib.metadata
from typing import Any, ClassVar
import numpy as np
import pandas as pd
from ._config import LightGBMConfig, RandomForestConfig
from ._registry import register
from .base import Method, _JoblibSaveMixin
# ── Internal lib_versions helper ──────────────────────────────────────────
def _classical_lib_versions() -> dict[str, str]:
"""Versions of the libs the classical family actually uses.
Restricts the broader default in :class:`Method` (which probes torch /
transformers / vllm too) — those are not imported here.
"""
out: dict[str, str] = {}
for pkg in ("numpy", "pandas", "scikit-learn", "lightgbm"):
try:
out[pkg] = importlib.metadata.version(pkg)
except importlib.metadata.PackageNotFoundError:
pass
return out
# ── Internal helpers (private to LightGBMRegressor) ───────────────────────
def _flatten_panel(
X: np.ndarray,
*,
add_rolling_close: bool = True,
close_idx: int | None = None,
) -> np.ndarray:
"""Flatten an ``(N, L, F)`` panel and append rolling-close stats.
Rolling stats over the lookback window: mean, std, min, max, last.
Mirrors the recipe used by the legacy classical T1 baseline.
"""
if X.ndim != 3:
raise ValueError(f"_flatten_panel: expected (N, L, F); got {X.shape}")
n, lb, f = X.shape
flat = X.reshape(n, lb * f).astype(np.float32)
if not add_rolling_close or close_idx is None or close_idx < 0 or close_idx >= f:
return flat
close = X[:, :, close_idx].astype(np.float32)
stats = np.stack(
[
close.mean(axis=1),
close.std(axis=1),
close.min(axis=1),
close.max(axis=1),
close[:, -1],
],
axis=1,
)
return np.concatenate([flat, stats], axis=1)
def _align_columns(
X: pd.DataFrame,
train_columns: list[str],
*,
fillna: bool = True,
) -> pd.DataFrame:
"""Align ``X`` to ``train_columns``: add missing as zero, drop extras.
``fillna=True`` (legacy / default): zero-fill any remaining NaN cells.
``fillna=False``: preserve NaN cells (used by the LightGBM-pipeline
paths in T2/T5/T7 — LightGBM has native NaN handling and zero-filling
distorts its learned splits).
"""
df = X.copy()
for c in train_columns:
if c not in df.columns:
df[c] = 0.0
df = df[train_columns]
return df.fillna(0.0) if fillna else df
def _numeric_feature_cols(
df: pd.DataFrame, prefixes: tuple[str, ...] | None = None,
) -> list[str]:
"""Return numeric columns of ``df``, optionally filtered by prefix."""
if prefixes is None:
return [c for c in df.columns if df[c].dtype.kind in "fiub"]
return [
c for c in df.columns
if df[c].dtype.kind in "fiub" and c.startswith(prefixes)
]
# ── Concrete method ───────────────────────────────────────────────────────
@register(
name="lightgbm",
family="classical",
tasks=frozenset({"T1", "T2", "T3", "T4", "T5", "T6", "T7"}),
config_class=LightGBMConfig,
)
class LightGBMRegressor(_JoblibSaveMixin, Method):
"""LightGBM regressor with per-task private dispatch.
One class, one config (:class:`LightGBMConfig`); the task is fixed at
construction time. Internally ``fit`` / ``predict`` dispatch on
``self.task`` to a private per-task implementation that owns its
feature-engineering recipe and fitted state.
"""
name: ClassVar[str] = "lightgbm"
family: ClassVar[str] = "classical"
tasks: ClassVar[frozenset[str]] = frozenset(
{"T1", "T2", "T3", "T4", "T5", "T6", "T7"}
)
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: LightGBMConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"LightGBMRegressor: unsupported task {task!r}; "
f"supported = {sorted(self.tasks)}"
)
self.task = task
if config is None:
config = LightGBMConfig(**kwargs) if kwargs else LightGBMConfig()
elif kwargs:
raise ValueError(
"LightGBMRegressor: pass either ``config=`` or kwargs, not both"
)
self.config = config
# Per-task fitted state — populated by .fit().
self._state: dict[str, Any] = {}
# ── public API ────────────────────────────────────────────────────────
def fit(self, X: Any, y: Any, *, seed: int = 42) -> "LightGBMRegressor":
"""Fit the regressor on ``(X, y)``. Returns ``self`` for chaining."""
self._seed = int(seed)
if self.task == "T1":
self._fit_t1(X, y)
elif self.task in ("T2", "T5"):
self._fit_t2_t5(X, y)
elif self.task in ("T3", "T6"):
self._fit_t3_t6(X, y)
elif self.task == "T4":
self._fit_t4(X, y)
elif self.task == "T7":
self._fit_t7(X, y)
else: # pragma: no cover -- gated by __init__
raise ValueError(self.task)
return self
def predict(self, X: Any) -> np.ndarray | pd.DataFrame:
if not self._state:
raise RuntimeError(
"LightGBMRegressor: call .fit(X, y) before .predict()."
)
if self.task == "T1":
return self._predict_t1(X)
if self.task in ("T2", "T5"):
return self._predict_t2_t5(X)
if self.task in ("T3", "T6"):
return self._predict_t3_t6(X)
if self.task == "T4":
return self._predict_t4(X)
if self.task == "T7":
return self._predict_t7(X)
raise ValueError(self.task) # pragma: no cover
def lib_versions(self) -> dict[str, str]:
return _classical_lib_versions()
@classmethod
def default_config(cls) -> LightGBMConfig:
return LightGBMConfig()
# ── LightGBM kwarg builder ────────────────────────────────────────────
def _lgbm_kwargs(self) -> dict[str, Any]:
"""Translate :class:`LightGBMConfig` → ``LGBMRegressor`` kwargs.
Drops config keys that are not LGBM hyperparameters (e.g.,
``t6_text_handling`` is a method-level switch).
"""
d = self.config.model_dump()
d.pop("t6_text_handling", None)
d["random_state"] = getattr(self, "_seed", 42)
return d
def _make_lgbm(self) -> Any:
from lightgbm import LGBMRegressor
return LGBMRegressor(**self._lgbm_kwargs())
def _make_log_pipeline(self) -> Any:
"""LightGBM wrapped in a log1p/expm1 target transform.
Used by T2 / T5 / T7 (positive-target regression).
Drops the previous ``StandardScaler`` step: LightGBM is
scale-invariant AND handles NaN natively, while ``StandardScaler``
does not tolerate NaN. With high-NaN-density T2/T5 inputs (~28%
NaN), the scaler step would either fail or, after a defensive
``np.nan_to_num(...,0)`` upstream, corrupt LightGBM's learned
missing-direction splits.
"""
from sklearn.compose import TransformedTargetRegressor
return TransformedTargetRegressor(
regressor=self._make_lgbm(), func=np.log1p, inverse_func=np.expm1,
)
# ── T1 — multi-output regression on per-window log-returns ────────────
def _fit_t1(self, X: np.ndarray, y: np.ndarray) -> None:
"""Multi-output regression on log-returns relative to last close.
T1 close prices span $0.50 to $5,000+ across the 4,416-ticker
small-cap universe. Training a regressor on raw close prices makes
per-step error scale with price level — high-price tickers dominate
the loss, low-price tickers see un-bounded predictions, and
post-hoc MSE blows up by ten or more orders of magnitude
(LightGBM T1 hit MSE 1.18e+16 on this codepath before the fix).
Fix: target the *log-return relative to the per-window last close*::
c_i = X_i[-1, close_idx] # last close in window i
y_log[i, h] = log(y[i, h] / c_i) # dimensionless O(1) target
At predict time we exponentiate and rescale by the test window's
last close. This matches Persistence's tile-last-close behaviour
as the zero-output limit, and matches what every TSFM (Chronos /
Moirai / TimesFM) does internally.
NaN handling: LightGBM still handles NaN inputs natively; we
scrub +/-inf only. Rows with non-positive c or y are dropped from
training (log undefined).
"""
from sklearn.multioutput import MultiOutputRegressor
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 fit: expected ndarray X (N, L, F); got "
f"{type(X).__name__} {getattr(X, 'shape', '?')}"
)
if not isinstance(y, np.ndarray) or y.ndim != 2:
raise ValueError(
f"T1 fit: expected ndarray y (N, horizon); got "
f"{type(y).__name__} {getattr(y, 'shape', '?')}"
)
if y.shape[0] != X.shape[0]:
raise ValueError(
f"T1 fit: y/X length mismatch ({y.shape[0]} vs {X.shape[0]})."
)
horizon = int(y.shape[1])
close_idx = 0
c = X[:, -1, close_idx].astype(np.float64) # (N,) last close
y_f = y.astype(np.float64) # (N, H)
# Drop windows where log target is undefined / unstable.
keep = (
np.isfinite(c) & (c > 0.0) &
np.isfinite(y_f).all(axis=1) & (y_f > 0.0).all(axis=1)
)
n_total = int(X.shape[0])
n_keep = int(keep.sum())
if n_keep < 1:
raise RuntimeError(
f"T1 fit: only {n_keep}/{n_total} training windows have "
"positive finite close + horizon prices; cannot fit "
"log-return target."
)
X_kept = X[keep]
c_kept = c[keep]
y_log = np.log(y_f[keep] / c_kept[:, None]).astype(np.float32)
X_flat = _flatten_panel(X_kept, add_rolling_close=True, close_idx=close_idx)
# Scrub +/-inf only (preserve NaN — LightGBM handles it natively).
X_flat = np.where(np.isposinf(X_flat) | np.isneginf(X_flat),
np.nan, X_flat)
model = MultiOutputRegressor(
self._make_lgbm(),
n_jobs=int(self.config.n_jobs),
)
model.fit(X_flat, y_log)
self._state = {
"model": model,
"close_idx": close_idx,
"horizon": horizon,
"n_features_flat": X_flat.shape[1],
"n_train_total": n_total,
"n_train_kept": n_keep,
# Log-return clip range: [-2, 2] = ~14% to ~700% of last close.
"log_clip": 2.0,
}
self._horizon = horizon
def _predict_t1(self, X: np.ndarray) -> np.ndarray:
st = self._state
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 predict: expected ndarray (N, L, F); got "
f"{type(X).__name__} {getattr(X, 'shape', '?')}"
)
close_idx = int(st["close_idx"])
c_test = X[:, -1, close_idx].astype(np.float64) # (N,)
# Where last close is missing or non-positive we cannot rescale; tile
# last close as the safest fallback (matches Persistence in that cell).
c_safe = np.where(np.isfinite(c_test) & (c_test > 0.0), c_test, np.nan)
X_flat = _flatten_panel(
X, add_rolling_close=True, close_idx=close_idx,
)
X_flat = np.where(np.isposinf(X_flat) | np.isneginf(X_flat),
np.nan, X_flat)
n_train_cols = st["n_features_flat"]
if X_flat.shape[1] > n_train_cols:
X_flat = X_flat[:, :n_train_cols]
elif X_flat.shape[1] < n_train_cols:
pad = np.zeros(
(X_flat.shape[0], n_train_cols - X_flat.shape[1]),
dtype=np.float32,
)
X_flat = np.concatenate([X_flat, pad], axis=1)
log_pred = st["model"].predict(X_flat).astype(np.float64)
if log_pred.ndim == 1:
log_pred = log_pred.reshape(-1, st["horizon"])
clip = float(st.get("log_clip", 2.0))
log_pred = np.clip(log_pred, -clip, clip)
# Rescale: y_pred = c * exp(log_return).
out = c_safe[:, None] * np.exp(log_pred)
# Where c was missing, fall back to last-close tile (NaN here would
# poison the eval; prefer Persistence-equivalent in degenerate cells).
bad = ~np.isfinite(out)
if bad.any():
tile = np.broadcast_to(c_test[:, None], out.shape).astype(np.float64)
out = np.where(bad, tile, out)
return out.astype(np.float32)
# ── T2 / T5 — log-target regression ───────────────────────────────────
def _fit_t2_t5(self, X: pd.DataFrame, y: np.ndarray) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected DataFrame X; got {type(X).__name__}"
)
# T2 carries stmt_* + derived_* + macro snapshot (fred_*/eia_*);
# T5 is price-stripped (no derived_*) but keeps the macro snapshot.
# Prefix-picking collapses both into one code path.
if self.task == "T2":
prefixes: tuple[str, ...] = ("stmt_", "derived_", "fred_", "eia_")
else:
prefixes = ("stmt_", "fred_", "eia_")
df = X.copy()
feat_cols = [
c for c in _numeric_feature_cols(df, prefixes)
if c not in {"derived_market_cap", "actual_market_cap"}
]
# Sector / industry one-hot — same construction as the legacy code.
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df["sector"], prefix="sector", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), sec_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(sec_dummies.columns)
if "industry" in df.columns:
ind_dummies = pd.get_dummies(
df["industry"], prefix="industry", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), ind_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(ind_dummies.columns)
# Cast numeric features to float32 WITHOUT zero-filling NaN —
# LightGBM handles NaN natively; zero-filling 28% of T2/T5 cells
# corrupted the learned missing-direction splits.
X_feat = df[feat_cols].astype(np.float32)
y_arr = pd.to_numeric(pd.Series(np.asarray(y).ravel()), errors="coerce").astype(
np.float64
)
valid = y_arr.notna() & (y_arr > 0)
X_feat = X_feat.loc[valid.values]
y_arr = y_arr.loc[valid.values]
if X_feat.empty:
raise RuntimeError(
f"{self.task} fit: no rows with positive market_cap after drop."
)
# Scrub only +/-inf; LightGBM rejects non-finite-non-NaN values
# but tolerates NaN.
X_arr = X_feat.values.astype(np.float32)
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
model = self._make_log_pipeline()
model.fit(X_arr, y_arr.values)
self._state = {
"model": model,
"feat_cols": feat_cols,
"prefixes": prefixes,
}
def _predict_t2_t5(self, X: pd.DataFrame) -> np.ndarray:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} predict: expected DataFrame; got {type(X).__name__}"
)
df = X.copy()
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df["sector"], prefix="sector", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), sec_dummies.reset_index(drop=True)],
axis=1,
)
if "industry" in df.columns:
ind_dummies = pd.get_dummies(
df["industry"], prefix="industry", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), ind_dummies.reset_index(drop=True)],
axis=1,
)
X_feat = _align_columns(
df, st["feat_cols"], fillna=False,
).astype(np.float32)
# Preserve NaN for LightGBM (matches the fit-time distribution);
# scrub only +/-inf.
X_arr = X_feat.values.astype(np.float32)
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
# TransformedTargetRegressor inverts log1p → expm1 internally.
preds = st["model"].predict(X_arr)
# Floor at zero to keep the (positive) market-cap interpretation.
preds = np.clip(preds, 0.0, None)
return preds.astype(np.float32)
# ── T3 / T6 — per-field booster ensemble ──────────────────────────────
def _t3_t6_build_ticker_features(
self, X: pd.DataFrame,
) -> tuple[pd.DataFrame, list[str]]:
"""Return ``(per-ticker numeric+sector features DataFrame, feat_cols)``.
Mirrors the legacy ``run_task_3_classical`` recipe:
* Pick numeric columns excluding ``fiscal_year`` (the join key)
and ``value_num`` (an internal scratch column).
* For T6 with ``t6_text_handling="sector_industry_only"``, the NL
``company_description`` column is dropped here implicitly because
string columns are non-numeric (and the explicit drop below is a
belt-and-braces guard).
* One-hot-encode ``sector`` (prefix=``sec``) deduped per ticker.
"""
df = X.copy()
# Defensive: explicitly drop free-text columns (T6) so they cannot
# accidentally leak into a future dtype check.
for text_col in ("company_description",):
if text_col in df.columns:
df = df.drop(columns=[text_col])
ticker_feat_cols = [
c for c in _numeric_feature_cols(df)
if c not in {"fiscal_year"} and c != "value_num"
]
ticker_feats = df[["ticker"] + ticker_feat_cols].copy()
ticker_feats[ticker_feat_cols] = (
ticker_feats[ticker_feat_cols].astype(np.float32).fillna(0.0)
)
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df.set_index("ticker")["sector"], prefix="sec", dtype=np.float32,
)
sec_dummies = sec_dummies.reset_index().drop_duplicates("ticker")
ticker_feats = (
ticker_feats.drop_duplicates("ticker")
.merge(sec_dummies, on="ticker", how="left")
.fillna(0.0)
)
else:
ticker_feats = ticker_feats.drop_duplicates("ticker")
feat_cols = [c for c in ticker_feats.columns if c != "ticker"]
return ticker_feats, feat_cols
def _fit_t3_t6(self, X: pd.DataFrame, y: pd.DataFrame) -> None:
"""Fit a SINGLE LightGBM that takes per-(ticker, fiscal_year)
numeric features concatenated with a sparse one-hot of ``field``,
predicting the scalar ``value``.
Output panel: one row per (ticker, fiscal_year, fitted_field) at
predict time. Per-field median fallback is kept for fields whose
training pool is too small (``<5`` rows) to fit.
"""
from scipy.sparse import csr_matrix, hstack as sparse_hstack
from sklearn.preprocessing import OneHotEncoder
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected DataFrame X; got {type(X).__name__}"
)
if not isinstance(y, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected long-form DataFrame y; got "
f"{type(y).__name__}"
)
for col in ("ticker", "field", "value"):
if col not in y.columns:
raise ValueError(
f"{self.task} fit: y missing required column {col!r}"
)
ticker_feats, feat_cols = self._t3_t6_build_ticker_features(X)
# Lock the field set to ``sorted(y["field"].unique())`` (per plan §1).
fitted_fields: list[str] = sorted(
str(f) for f in y["field"].astype(str).unique()
)
# Long-form labels joined with per-ticker features (broadcast across
# fiscal years). Drop rows with no parseable target.
gt = y.copy()
gt["value_num"] = pd.to_numeric(gt["value"], errors="coerce")
gt["field"] = gt["field"].astype(str)
gt = gt.merge(ticker_feats, on="ticker", how="left").fillna(0.0)
gt = gt.dropna(subset=["value_num"])
# Per-field median fallback for fields with too few rows (the
# legacy small-pool guard, preserved field-by-field).
per_field_count = gt.groupby("field").size().to_dict()
median_fields: dict[str, float] = {}
small_field_set: set[str] = set()
for field in fitted_fields:
cnt = int(per_field_count.get(field, 0))
if cnt < 5:
sub = gt[gt["field"] == field]
med = float(sub["value_num"].median()) if not sub.empty else 0.0
median_fields[field] = med
small_field_set.add(field)
train_mask = ~gt["field"].isin(small_field_set)
gt_train = gt[train_mask]
# Decide a global log-transform heuristic (preserves legacy magnitude
# gate) using the pooled non-zero target distribution.
global_model = None
global_scaler = None
use_log = False
y_min = 0.0
y_max = 0.0
y_range = 1.0
ohe: OneHotEncoder | None = None
if not gt_train.empty:
y_tr = gt_train["value_num"].values.astype(np.float64)
nz = y_tr[y_tr != 0]
if nz.size > 0:
use_log = float(np.median(np.abs(nz))) > 1000
y_tr_t = (
np.sign(y_tr) * np.log1p(np.abs(y_tr)) if use_log else y_tr
)
# Per-ticker numerics already pass through ``.fillna(0.0)`` in
# ``_t3_t6_build_ticker_features``, so the row-side has no NaN.
# We still scrub +/-inf defensively before LightGBM.
X_num_tr = gt_train[feat_cols].values.astype(np.float32)
X_num_tr = np.where(
np.isposinf(X_num_tr) | np.isneginf(X_num_tr),
np.nan, X_num_tr,
)
# Sparse one-hot of field id. Use the LOCKED fitted_fields set
# as categories so the predict path can encode every field
# (even those whose training pool was too small to fit; for
# those we override with the median anyway).
ohe = OneHotEncoder(
categories=[fitted_fields],
handle_unknown="ignore",
sparse_output=True,
dtype=np.float32,
)
field_arr_tr = gt_train["field"].values.reshape(-1, 1)
X_field_tr = ohe.fit_transform(field_arr_tr)
X_full_tr = sparse_hstack(
[csr_matrix(X_num_tr), X_field_tr], format="csr",
)
# LightGBM accepts sparse CSR. Use a single booster.
global_model = self._make_lgbm()
global_model.fit(X_full_tr, y_tr_t)
y_min = float(y_tr.min())
y_max = float(y_tr.max())
y_range = max(abs(y_max - y_min), abs(y_max) * 0.1, 1.0)
self._state = {
"ticker_feats": ticker_feats,
"feat_cols": feat_cols,
"fitted_fields": fitted_fields,
"median_fields": median_fields,
"model": global_model,
"scaler": global_scaler, # kept for compat (always None now)
"ohe": ohe,
"use_log": use_log,
"y_min": y_min,
"y_max": y_max,
"y_range": y_range,
}
self.fitted_fields = fitted_fields # public, per plan §1
def _predict_t3_t6(self, X: pd.DataFrame) -> pd.DataFrame:
"""Predict every (ticker, fiscal_year, fitted_field) cell with the
single shared LightGBM (numeric features + sparse field one-hot),
falling back to per-field medians for small-pool fields tagged at
fit time.
"""
from scipy.sparse import csr_matrix, hstack as sparse_hstack
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} predict: expected DataFrame; got {type(X).__name__}"
)
if "ticker" not in X.columns or "fiscal_year" not in X.columns:
raise ValueError(
f"{self.task} predict: X must include 'ticker' and "
f"'fiscal_year'."
)
fitted_fields: list[str] = st["fitted_fields"]
median_fields: dict[str, float] = st["median_fields"]
feat_cols: list[str] = st["feat_cols"]
# Build test-side per-ticker features using the SAME recipe as fit,
# then align columns to the train feature schema.
test_feats, _ = self._t3_t6_build_ticker_features(X)
test_feats = test_feats.set_index("ticker")
for c in feat_cols:
if c not in test_feats.columns:
test_feats[c] = 0.0
test_feats = test_feats[feat_cols].fillna(0.0)
# One row per (test row × every fitted field) — long-form predict.
# We assemble the predict matrix as the cross-product of test rows
# and fitted fields, run a single batched .predict, then map back.
n_rows = len(X)
n_fields = len(fitted_fields)
rows: list[dict[str, Any]] = []
if n_rows == 0 or n_fields == 0:
return pd.DataFrame(
rows, columns=["ticker", "fiscal_year", "field", "pred"],
)
# Pre-fetch numeric features per test row.
ticker_arr = X["ticker"].astype(str).values
fy_arr = X["fiscal_year"].values
# For tickers absent from training-side ticker_feats the feature
# vector is zero (matches the legacy behaviour for unseen tickers).
zero_vec = np.zeros(len(feat_cols), dtype=np.float32)
feats_by_ticker: dict[str, np.ndarray] = {}
for t in set(ticker_arr.tolist()):
try:
v = test_feats.loc[t]
if isinstance(v, pd.DataFrame):
v = v.iloc[0]
feats_by_ticker[t] = np.asarray(
v.values, dtype=np.float32,
)
except KeyError:
feats_by_ticker[t] = zero_vec
# Decide which (row, field) cells get the model vs. a median fallback.
model = st["model"]
# Note: ``scaler`` slot exists in state for save/load compat but is
# always None now — LightGBM is scale-invariant so we dropped it.
ohe = st["ohe"]
use_log = bool(st["use_log"])
y_min = float(st["y_min"])
y_max = float(st["y_max"])
y_range = float(st["y_range"])
# Cache one prediction per unique (ticker, field) cell to avoid
# duplicating the model call across the same ticker repeated for
# multiple fiscal years.
unique_tickers = list(dict.fromkeys(ticker_arr.tolist()))
# Build the model batch only for fields with a fitted booster.
model_fields = (
[f for f in fitted_fields if f not in median_fields]
if model is not None else []
)
cell_pred: dict[tuple[str, str], float] = {}
if model is not None and model_fields and unique_tickers:
# Cross-product matrix: rows = (ticker × model_field) pairs.
# Per-ticker numerics are already imputed to 0 in
# ``_t3_t6_build_ticker_features`` (predict-side mirrors fit);
# we only scrub +/-inf defensively for LightGBM.
X_num = np.stack(
[feats_by_ticker[t] for t in unique_tickers], axis=0,
).astype(np.float32)
X_num = np.where(
np.isposinf(X_num) | np.isneginf(X_num),
np.nan, X_num,
)
# Repeat per model-field so the one-hot lookup aligns 1-to-1.
n_t = len(unique_tickers)
n_mf = len(model_fields)
X_num_rep = np.repeat(X_num, n_mf, axis=0)
field_arr = np.tile(
np.asarray(model_fields, dtype=object), n_t,
).reshape(-1, 1)
assert ohe is not None # set whenever model is set
X_field = ohe.transform(field_arr)
X_full = sparse_hstack(
[csr_matrix(X_num_rep), X_field], format="csr",
)
y_pred_t = np.asarray(model.predict(X_full))
if use_log:
y_pred = np.sign(y_pred_t) * np.expm1(np.abs(y_pred_t))
else:
y_pred = y_pred_t
y_pred = np.clip(y_pred, y_min - y_range, y_max + y_range)
# Re-shape into (n_t, n_mf) for cell-key indexing.
y_pred = y_pred.reshape(n_t, n_mf)
for ti, t in enumerate(unique_tickers):
for fi, f in enumerate(model_fields):
cell_pred[(t, f)] = float(y_pred[ti, fi])
for i in range(n_rows):
t = ticker_arr[i]
fy = fy_arr[i]
for field in fitted_fields:
if field in median_fields:
val = median_fields[field]
else:
val = cell_pred.get((t, field), 0.0)
rows.append({
"ticker": t,
"fiscal_year": fy,
"field": field,
"pred": float(val),
})
return pd.DataFrame(
rows, columns=["ticker", "fiscal_year", "field", "pred"],
)
# ── T4 — flat-lookback + event-type one-hot ───────────────────────────
@staticmethod
def _t4_flatten_lookback(lb_col: pd.Series) -> tuple[np.ndarray, int]:
"""Stack object-dtype ``lookback`` cells into ``(N, L*F)`` float32.
Each cell is a ``(L, F)`` ndarray. Empty / malformed cells are
replaced with zeros sized to the modal panel shape.
"""
arrays: list[np.ndarray] = []
for cell in lb_col.values:
if isinstance(cell, np.ndarray) and cell.ndim == 2:
arrays.append(cell.astype(np.float32))
if not arrays:
raise RuntimeError(
"T4: no usable lookback ndarrays in X['lookback']."
)
L = arrays[0].shape[0]
F = arrays[0].shape[1]
flat_rows: list[np.ndarray] = []
for cell in lb_col.values:
if isinstance(cell, np.ndarray) and cell.shape == (L, F):
flat_rows.append(cell.reshape(-1).astype(np.float32))
else:
flat_rows.append(np.zeros(L * F, dtype=np.float32))
flat = np.stack(flat_rows, axis=0)
return flat, L * F
def _fit_t4(self, X: pd.DataFrame, y: np.ndarray) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T4 fit: expected DataFrame X; got {type(X).__name__}"
)
if "lookback" not in X.columns or "event_type" not in X.columns:
raise ValueError(
"T4 fit: X must include 'lookback' and 'event_type' columns."
)
flat, n_lb_flat = self._t4_flatten_lookback(X["lookback"])
et_arr = X["event_type"].astype(str).values
et_dummies = pd.get_dummies(
pd.Series(et_arr), prefix="evt", dtype=np.float32,
)
X_arr = np.concatenate(
[flat, et_dummies.values.astype(np.float32)], axis=1,
)
# Preserve NaN for LightGBM; scrub only +/-inf.
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
y_arr = np.asarray(y, dtype=np.float32).ravel()
if y_arr.shape[0] != X_arr.shape[0]:
raise ValueError(
f"T4 fit: y/X length mismatch ({y_arr.shape[0]} vs "
f"{X_arr.shape[0]})."
)
model = self._make_lgbm()
model.fit(X_arr, y_arr)
self._state = {
"model": model,
"evt_columns": list(et_dummies.columns),
"n_lb_flat": int(n_lb_flat),
}
def _predict_t4(self, X: pd.DataFrame) -> np.ndarray:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T4 predict: expected DataFrame; got {type(X).__name__}"
)
if "lookback" not in X.columns or "event_type" not in X.columns:
raise ValueError(
"T4 predict: X must include 'lookback' and 'event_type'."
)
flat, _ = self._t4_flatten_lookback(X["lookback"])
# Align lookback flat-width to train (defensive — tolerate small
# column drift coming from a slightly-different feature panel).
if flat.shape[1] > st["n_lb_flat"]:
flat = flat[:, : st["n_lb_flat"]]
elif flat.shape[1] < st["n_lb_flat"]:
pad = np.zeros(
(flat.shape[0], st["n_lb_flat"] - flat.shape[1]),
dtype=np.float32,
)
flat = np.concatenate([flat, pad], axis=1)
et_arr = X["event_type"].astype(str).values
et_dummies = pd.get_dummies(
pd.Series(et_arr), prefix="evt", dtype=np.float32,
)
for c in st["evt_columns"]:
if c not in et_dummies.columns:
et_dummies[c] = 0.0
et_dummies = et_dummies[st["evt_columns"]].fillna(0.0)
X_arr = np.concatenate(
[flat, et_dummies.values.astype(np.float32)], axis=1,
)
# Preserve NaN for LightGBM; scrub only +/-inf.
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
return st["model"].predict(X_arr).astype(np.float32)
# ── T7 — dual-output (rent, price) ────────────────────────────────────
@staticmethod
def _t7_first_col(
df: pd.DataFrame, candidates: tuple[str, ...],
) -> str | None:
"""Return the first column whose name (lowercased) contains any of
``candidates`` (substring match), else ``None``.
"""
for c in df.columns:
cl = c.lower()
if any(cand in cl for cand in candidates):
return c
return None
def _t7_build_features(
self, X: pd.DataFrame, *, fit: bool,
) -> tuple[pd.DataFrame, list[str], str | None]:
"""Build the property-feature frame; returns ``(X_feat, feat_cols,
prop_type_col)``.
Same numeric feature recipe as the legacy T7 baseline.
"""
df = X.copy()
feat_cols: list[str] = []
for col in (
"sqft", "squareFootage", "square_footage",
"beds", "bedrooms", "baths", "bathrooms",
"year_built", "yearBuilt",
"years_since_last_sale",
):
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
feat_cols.append(col)
prop_type_col = next(
(c for c in ("property_type", "propertyType", "type")
if c in df.columns),
None,
)
if prop_type_col:
prop_dummies = pd.get_dummies(
df[prop_type_col], prefix="ptype", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), prop_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(prop_dummies.columns)
if not feat_cols:
raise RuntimeError(
f"T7 {'fit' if fit else 'predict'}: no usable property features."
)
return df, feat_cols, prop_type_col
def _fit_t7(self, X: pd.DataFrame, y: pd.DataFrame) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T7 fit: expected DataFrame X; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("T7 fit: X must include 'address'.")
df, feat_cols, prop_type_col = self._t7_build_features(X, fit=True)
# Targets: prefer rent / price columns already on X (canonical T7
# train carries them); fall back to a per-address merge with y.
rent_col = self._t7_first_col(df, ("rent",))
price_col = self._t7_first_col(df, ("price", "lastsaleprice"))
if isinstance(y, pd.DataFrame) and "address" in y.columns:
if rent_col is None and "rent" in y.columns:
df = df.merge(
y[["address", "rent"]], on="address", how="left",
)
rent_col = "rent"
if price_col is None and "price" in y.columns:
df = df.merge(
y[["address", "price"]], on="address", how="left",
)
price_col = "price"
if rent_col is None and price_col is None:
raise RuntimeError("T7 fit: no rent or price target found.")
# Preserve NaN for LightGBM's native missing-value handling;
# scrub only +/-inf (LightGBM rejects them but tolerates NaN).
X_feat = df[feat_cols].astype(np.float32)
X_arr = X_feat.values.astype(np.float32)
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
models: dict[str, Any] = {}
for target_name, target_col in (("rent", rent_col), ("price", price_col)):
if target_col is None:
continue
y_all = pd.to_numeric(df[target_col], errors="coerce")
valid = y_all.notna() & (y_all > 0)
n_valid = int(valid.sum())
if n_valid < 1:
continue
X_tr = X_arr[valid.values]
y_tr = y_all.loc[valid].values.astype(np.float64)
if n_valid < 2:
# LightGBM rejects n<2; emit a constant-predictor (the single
# training value) so eval is well-defined. Real T7 trains
# have ~10k rows; this branch only triggers in micro-scale
# smoke runs where dedup-by-address leaves 1 row.
models[target_name] = ("constant", float(y_tr.mean()))
continue
m = self._make_log_pipeline()
m.fit(X_tr, y_tr)
models[target_name] = m
if not models:
raise RuntimeError(
f"T7 fit: insufficient training data "
f"(rent_col={rent_col!r}, price_col={price_col!r}, "
f"n_rows={len(df)}); need >=1 row with a positive target."
)
self._state = {
"feat_cols": feat_cols,
"prop_type_col": prop_type_col,
"models": models,
}
def _predict_t7(self, X: pd.DataFrame) -> pd.DataFrame:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T7 predict: expected DataFrame; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("T7 predict: X must include 'address'.")
df = X.copy()
for col in (
"sqft", "squareFootage", "square_footage",
"beds", "bedrooms", "baths", "bathrooms",
"year_built", "yearBuilt",
"years_since_last_sale",
):
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
prop_type_col = st["prop_type_col"]
if prop_type_col and prop_type_col in df.columns:
prop_dummies = pd.get_dummies(
df[prop_type_col], prefix="ptype", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), prop_dummies.reset_index(drop=True)],
axis=1,
)
X_feat = _align_columns(
df, st["feat_cols"], fillna=False,
).astype(np.float32)
X_arr = X_feat.values.astype(np.float32)
X_arr = np.where(np.isposinf(X_arr) | np.isneginf(X_arr),
np.nan, X_arr)
out = pd.DataFrame({"address": X["address"].astype(str).values})
for target_name in ("rent", "price"):
model = st["models"].get(target_name)
if model is None:
out[f"pred_{target_name}"] = np.full(
len(X), np.nan, dtype=np.float32,
)
continue
if isinstance(model, tuple) and model[0] == "constant":
out[f"pred_{target_name}"] = np.full(
len(X), float(model[1]), dtype=np.float32,
)
continue
preds = model.predict(X_arr)
preds = np.clip(preds, 0.0, None)
out[f"pred_{target_name}"] = preds.astype(np.float32)
return out
# ── RandomForest variant ──────────────────────────────────────────────────
def _make_rf_estimator(
cfg: RandomForestConfig, *, seed: int,
) -> Any:
"""Build a fresh sklearn ``RandomForestRegressor`` from ``cfg``.
Lazy-imports sklearn so the import-time cost is only paid when the
classical/random_forest method is actually instantiated.
"""
from sklearn.ensemble import RandomForestRegressor
return RandomForestRegressor(
n_estimators=int(cfg.n_estimators),
max_depth=cfg.max_depth,
min_samples_leaf=int(cfg.min_samples_leaf),
n_jobs=int(cfg.n_jobs),
random_state=int(seed),
)
def _make_rf_log_pipeline(
cfg: RandomForestConfig, *, seed: int,
) -> Any:
"""RandomForest wrapped in a log1p/expm1 target transform.
Used by T2 / T5 / T7 (positive-target regression). Mirrors
:meth:`LightGBMRegressor._make_log_pipeline` but with sklearn's RF
as the regressor. RF is scale-invariant; no StandardScaler step.
"""
from sklearn.compose import TransformedTargetRegressor
return TransformedTargetRegressor(
regressor=_make_rf_estimator(cfg, seed=seed),
func=np.log1p,
inverse_func=np.expm1,
)
@register(
name="random_forest",
family="classical",
tasks=frozenset({"T1", "T2", "T3", "T4", "T5", "T6", "T7"}),
config_class=RandomForestConfig,
)
class RandomForestMethod(_JoblibSaveMixin, Method):
"""sklearn RandomForestRegressor with per-task private dispatch.
Mirrors :class:`LightGBMRegressor` per-task adapter shape (T1..T7) but
swaps the base estimator for ``sklearn.ensemble.RandomForestRegressor``.
Reuses the module-level helpers (``_flatten_panel``, ``_align_columns``,
``_numeric_feature_cols``, plus the ``_t3_t6_build_ticker_features`` /
``_t7_build_features`` helpers from :class:`LightGBMRegressor`).
Key behaviour differences from LightGBM:
* sklearn RandomForest does NOT handle NaN inputs natively; every fit /
predict path zero-fills NaN before calling the estimator.
* sklearn RandomForest does NOT accept sparse CSR matrices on the T3/T6
ensemble path; we densify with ``.toarray()`` before fit/predict
(acceptable for the small-pool T3/T6 train sets).
* The class is named ``RandomForestMethod`` (not
``RandomForestRegressor``) to avoid the name collision with
``sklearn.ensemble.RandomForestRegressor``.
"""
name: ClassVar[str] = "random_forest"
family: ClassVar[str] = "classical"
tasks: ClassVar[frozenset[str]] = frozenset(
{"T1", "T2", "T3", "T4", "T5", "T6", "T7"}
)
schema_version: ClassVar[int] = 1
def __init__(
self,
*,
task: str,
config: RandomForestConfig | None = None,
**kwargs: Any,
) -> None:
if task not in self.tasks:
raise ValueError(
f"RandomForestMethod: unsupported task {task!r}; "
f"supported = {sorted(self.tasks)}"
)
self.task = task
if config is None:
config = (
RandomForestConfig(**kwargs) if kwargs else RandomForestConfig()
)
elif kwargs:
raise ValueError(
"RandomForestMethod: pass either ``config=`` or kwargs, not both"
)
self.config = config
self._state: dict[str, Any] = {}
# ── public API ────────────────────────────────────────────────────────
def fit(self, X: Any, y: Any, *, seed: int = 42) -> "RandomForestMethod":
self._seed = int(seed)
if self.task == "T1":
self._fit_t1(X, y)
elif self.task in ("T2", "T5"):
self._fit_t2_t5(X, y)
elif self.task in ("T3", "T6"):
self._fit_t3_t6(X, y)
elif self.task == "T4":
self._fit_t4(X, y)
elif self.task == "T7":
self._fit_t7(X, y)
else: # pragma: no cover -- gated by __init__
raise ValueError(self.task)
return self
def predict(self, X: Any) -> np.ndarray | pd.DataFrame:
if not self._state:
raise RuntimeError(
"RandomForestMethod: call .fit(X, y) before .predict()."
)
if self.task == "T1":
return self._predict_t1(X)
if self.task in ("T2", "T5"):
return self._predict_t2_t5(X)
if self.task in ("T3", "T6"):
return self._predict_t3_t6(X)
if self.task == "T4":
return self._predict_t4(X)
if self.task == "T7":
return self._predict_t7(X)
raise ValueError(self.task) # pragma: no cover
def lib_versions(self) -> dict[str, str]:
return _classical_lib_versions()
@classmethod
def default_config(cls) -> RandomForestConfig:
return RandomForestConfig()
# ── helpers (re-use LightGBM's T3/T6 + T7 feature builders) ───────────
def _t3_t6_build_ticker_features(
self, X: pd.DataFrame,
) -> tuple[pd.DataFrame, list[str]]:
return LightGBMRegressor._t3_t6_build_ticker_features(self, X)
def _t7_build_features(
self, X: pd.DataFrame, *, fit: bool,
) -> tuple[pd.DataFrame, list[str], str | None]:
return LightGBMRegressor._t7_build_features(self, X, fit=fit)
@staticmethod
def _t4_flatten_lookback(lb_col: pd.Series) -> tuple[np.ndarray, int]:
return LightGBMRegressor._t4_flatten_lookback(lb_col)
@staticmethod
def _t7_first_col(
df: pd.DataFrame, candidates: tuple[str, ...],
) -> str | None:
return LightGBMRegressor._t7_first_col(df, candidates)
# ── T1 — multi-output regression on per-window log-returns ────────────
def _fit_t1(self, X: np.ndarray, y: np.ndarray) -> None:
"""Multi-output log-return regression; mirrors LightGBM T1.
sklearn RandomForest natively supports multi-output targets — fit
ONE forest with ``y.shape == (N, horizon)`` rather than wrapping in
``MultiOutputRegressor`` (which trains horizon-many forests
sequentially). The ONE-forest path is ~horizon× faster and matches
what sklearn's reference docs recommend for vector-valued targets.
sklearn RandomForest does NOT handle NaN natively, so we zero-fill
any NaN cells before fitting (in addition to scrubbing +/-inf).
"""
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 fit: expected ndarray X (N, L, F); got "
f"{type(X).__name__} {getattr(X, 'shape', '?')}"
)
if not isinstance(y, np.ndarray) or y.ndim != 2:
raise ValueError(
f"T1 fit: expected ndarray y (N, horizon); got "
f"{type(y).__name__} {getattr(y, 'shape', '?')}"
)
if y.shape[0] != X.shape[0]:
raise ValueError(
f"T1 fit: y/X length mismatch ({y.shape[0]} vs {X.shape[0]})."
)
horizon = int(y.shape[1])
close_idx = 0
c = X[:, -1, close_idx].astype(np.float64)
y_f = y.astype(np.float64)
keep = (
np.isfinite(c) & (c > 0.0) &
np.isfinite(y_f).all(axis=1) & (y_f > 0.0).all(axis=1)
)
n_total = int(X.shape[0])
n_keep = int(keep.sum())
if n_keep < 1:
raise RuntimeError(
f"T1 fit: only {n_keep}/{n_total} training windows have "
"positive finite close + horizon prices; cannot fit "
"log-return target."
)
X_kept = X[keep]
c_kept = c[keep]
y_log = np.log(y_f[keep] / c_kept[:, None]).astype(np.float32)
X_flat = _flatten_panel(
X_kept, add_rolling_close=True, close_idx=close_idx,
)
# Scrub +/-inf AND zero-fill NaN — sklearn RF rejects all non-finite.
X_flat = np.nan_to_num(
X_flat, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
# NATIVE multi-output: one RF tree set predicts all horizon steps.
model = _make_rf_estimator(self.config, seed=self._seed)
model.fit(X_flat, y_log)
self._state = {
"model": model,
"close_idx": close_idx,
"horizon": horizon,
"n_features_flat": X_flat.shape[1],
"n_train_total": n_total,
"n_train_kept": n_keep,
"log_clip": 2.0,
}
self._horizon = horizon
def _predict_t1(self, X: np.ndarray) -> np.ndarray:
st = self._state
if not isinstance(X, np.ndarray) or X.ndim != 3:
raise ValueError(
f"T1 predict: expected ndarray (N, L, F); got "
f"{type(X).__name__} {getattr(X, 'shape', '?')}"
)
close_idx = int(st["close_idx"])
c_test = X[:, -1, close_idx].astype(np.float64)
c_safe = np.where(np.isfinite(c_test) & (c_test > 0.0), c_test, np.nan)
X_flat = _flatten_panel(
X, add_rolling_close=True, close_idx=close_idx,
)
# Zero-fill NaN and scrub +/-inf — sklearn RF cannot handle them.
X_flat = np.nan_to_num(
X_flat, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
n_train_cols = st["n_features_flat"]
if X_flat.shape[1] > n_train_cols:
X_flat = X_flat[:, :n_train_cols]
elif X_flat.shape[1] < n_train_cols:
pad = np.zeros(
(X_flat.shape[0], n_train_cols - X_flat.shape[1]),
dtype=np.float32,
)
X_flat = np.concatenate([X_flat, pad], axis=1)
log_pred = st["model"].predict(X_flat).astype(np.float64)
if log_pred.ndim == 1:
log_pred = log_pred.reshape(-1, st["horizon"])
clip = float(st.get("log_clip", 2.0))
log_pred = np.clip(log_pred, -clip, clip)
out = c_safe[:, None] * np.exp(log_pred)
bad = ~np.isfinite(out)
if bad.any():
tile = np.broadcast_to(c_test[:, None], out.shape).astype(np.float64)
out = np.where(bad, tile, out)
return out.astype(np.float32)
# ── T2 / T5 — log-target regression ───────────────────────────────────
def _fit_t2_t5(self, X: pd.DataFrame, y: np.ndarray) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected DataFrame X; got {type(X).__name__}"
)
if self.task == "T2":
prefixes: tuple[str, ...] = ("stmt_", "derived_", "fred_", "eia_")
else:
prefixes = ("stmt_", "fred_", "eia_")
df = X.copy()
feat_cols = [
c for c in _numeric_feature_cols(df, prefixes)
if c not in {"derived_market_cap", "actual_market_cap"}
]
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df["sector"], prefix="sector", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), sec_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(sec_dummies.columns)
if "industry" in df.columns:
ind_dummies = pd.get_dummies(
df["industry"], prefix="industry", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), ind_dummies.reset_index(drop=True)],
axis=1,
)
feat_cols += list(ind_dummies.columns)
X_feat = df[feat_cols].astype(np.float32)
y_arr = pd.to_numeric(
pd.Series(np.asarray(y).ravel()), errors="coerce",
).astype(np.float64)
valid = y_arr.notna() & (y_arr > 0)
X_feat = X_feat.loc[valid.values]
y_arr = y_arr.loc[valid.values]
if X_feat.empty:
raise RuntimeError(
f"{self.task} fit: no rows with positive market_cap after drop."
)
# sklearn RF rejects NaN/inf — zero-fill before fit.
X_arr = np.nan_to_num(
X_feat.values.astype(np.float32),
nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
model = _make_rf_log_pipeline(self.config, seed=self._seed)
model.fit(X_arr, y_arr.values)
self._state = {
"model": model,
"feat_cols": feat_cols,
"prefixes": prefixes,
}
def _predict_t2_t5(self, X: pd.DataFrame) -> np.ndarray:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} predict: expected DataFrame; got {type(X).__name__}"
)
df = X.copy()
if "sector" in df.columns:
sec_dummies = pd.get_dummies(
df["sector"], prefix="sector", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), sec_dummies.reset_index(drop=True)],
axis=1,
)
if "industry" in df.columns:
ind_dummies = pd.get_dummies(
df["industry"], prefix="industry", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), ind_dummies.reset_index(drop=True)],
axis=1,
)
# Zero-fill NaN at align time (RF can't handle them); also scrub
# any straggler +/-inf below.
X_feat = _align_columns(
df, st["feat_cols"], fillna=True,
).astype(np.float32)
X_arr = np.nan_to_num(
X_feat.values.astype(np.float32),
nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
preds = st["model"].predict(X_arr)
preds = np.clip(preds, 0.0, None)
return preds.astype(np.float32)
# ── T3 / T6 — per-field booster ensemble (sparse field one-hot) ───────
def _fit_t3_t6(self, X: pd.DataFrame, y: pd.DataFrame) -> None:
"""Single RandomForest with per-(ticker, fiscal_year) numeric
features + one-hot of ``field``. sklearn RF does NOT accept sparse
CSR — we densify with ``.toarray()`` before fit (acceptable for
the small-pool T3/T6 train sets).
"""
from sklearn.preprocessing import OneHotEncoder
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected DataFrame X; got {type(X).__name__}"
)
if not isinstance(y, pd.DataFrame):
raise TypeError(
f"{self.task} fit: expected long-form DataFrame y; got "
f"{type(y).__name__}"
)
for col in ("ticker", "field", "value"):
if col not in y.columns:
raise ValueError(
f"{self.task} fit: y missing required column {col!r}"
)
ticker_feats, feat_cols = self._t3_t6_build_ticker_features(X)
fitted_fields: list[str] = sorted(
str(f) for f in y["field"].astype(str).unique()
)
gt = y.copy()
gt["value_num"] = pd.to_numeric(gt["value"], errors="coerce")
gt["field"] = gt["field"].astype(str)
gt = gt.merge(ticker_feats, on="ticker", how="left").fillna(0.0)
gt = gt.dropna(subset=["value_num"])
per_field_count = gt.groupby("field").size().to_dict()
median_fields: dict[str, float] = {}
small_field_set: set[str] = set()
for field in fitted_fields:
cnt = int(per_field_count.get(field, 0))
if cnt < 5:
sub = gt[gt["field"] == field]
med = float(sub["value_num"].median()) if not sub.empty else 0.0
median_fields[field] = med
small_field_set.add(field)
train_mask = ~gt["field"].isin(small_field_set)
gt_train = gt[train_mask]
global_model = None
global_scaler = None
use_log = False
y_min = 0.0
y_max = 0.0
y_range = 1.0
ohe: OneHotEncoder | None = None
if not gt_train.empty:
y_tr = gt_train["value_num"].values.astype(np.float64)
nz = y_tr[y_tr != 0]
if nz.size > 0:
use_log = float(np.median(np.abs(nz))) > 1000
y_tr_t = (
np.sign(y_tr) * np.log1p(np.abs(y_tr)) if use_log else y_tr
)
X_num_tr = gt_train[feat_cols].values.astype(np.float32)
# sklearn RF rejects NaN/inf — zero-fill.
X_num_tr = np.nan_to_num(
X_num_tr, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
ohe = OneHotEncoder(
categories=[fitted_fields],
handle_unknown="ignore",
sparse_output=True,
dtype=np.float32,
)
field_arr_tr = gt_train["field"].values.reshape(-1, 1)
X_field_tr = ohe.fit_transform(field_arr_tr).toarray().astype(np.float32)
X_full_tr = np.concatenate([X_num_tr, X_field_tr], axis=1)
global_model = _make_rf_estimator(self.config, seed=self._seed)
global_model.fit(X_full_tr, y_tr_t)
y_min = float(y_tr.min())
y_max = float(y_tr.max())
y_range = max(abs(y_max - y_min), abs(y_max) * 0.1, 1.0)
self._state = {
"ticker_feats": ticker_feats,
"feat_cols": feat_cols,
"fitted_fields": fitted_fields,
"median_fields": median_fields,
"model": global_model,
"scaler": global_scaler,
"ohe": ohe,
"use_log": use_log,
"y_min": y_min,
"y_max": y_max,
"y_range": y_range,
}
self.fitted_fields = fitted_fields
def _predict_t3_t6(self, X: pd.DataFrame) -> pd.DataFrame:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"{self.task} predict: expected DataFrame; got {type(X).__name__}"
)
if "ticker" not in X.columns or "fiscal_year" not in X.columns:
raise ValueError(
f"{self.task} predict: X must include 'ticker' and "
f"'fiscal_year'."
)
fitted_fields: list[str] = st["fitted_fields"]
median_fields: dict[str, float] = st["median_fields"]
feat_cols: list[str] = st["feat_cols"]
test_feats, _ = self._t3_t6_build_ticker_features(X)
test_feats = test_feats.set_index("ticker")
for c in feat_cols:
if c not in test_feats.columns:
test_feats[c] = 0.0
test_feats = test_feats[feat_cols].fillna(0.0)
n_rows = len(X)
n_fields = len(fitted_fields)
rows: list[dict[str, Any]] = []
if n_rows == 0 or n_fields == 0:
return pd.DataFrame(
rows, columns=["ticker", "fiscal_year", "field", "pred"],
)
ticker_arr = X["ticker"].astype(str).values
fy_arr = X["fiscal_year"].values
zero_vec = np.zeros(len(feat_cols), dtype=np.float32)
feats_by_ticker: dict[str, np.ndarray] = {}
for t in set(ticker_arr.tolist()):
try:
v = test_feats.loc[t]
if isinstance(v, pd.DataFrame):
v = v.iloc[0]
feats_by_ticker[t] = np.asarray(
v.values, dtype=np.float32,
)
except KeyError:
feats_by_ticker[t] = zero_vec
model = st["model"]
ohe = st["ohe"]
use_log = bool(st["use_log"])
y_min = float(st["y_min"])
y_max = float(st["y_max"])
y_range = float(st["y_range"])
unique_tickers = list(dict.fromkeys(ticker_arr.tolist()))
model_fields = (
[f for f in fitted_fields if f not in median_fields]
if model is not None else []
)
cell_pred: dict[tuple[str, str], float] = {}
if model is not None and model_fields and unique_tickers:
X_num = np.stack(
[feats_by_ticker[t] for t in unique_tickers], axis=0,
).astype(np.float32)
X_num = np.nan_to_num(
X_num, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
n_t = len(unique_tickers)
n_mf = len(model_fields)
X_num_rep = np.repeat(X_num, n_mf, axis=0)
field_arr = np.tile(
np.asarray(model_fields, dtype=object), n_t,
).reshape(-1, 1)
assert ohe is not None
X_field = ohe.transform(field_arr).toarray().astype(np.float32)
X_full = np.concatenate([X_num_rep, X_field], axis=1)
y_pred_t = np.asarray(model.predict(X_full))
if use_log:
y_pred = np.sign(y_pred_t) * np.expm1(np.abs(y_pred_t))
else:
y_pred = y_pred_t
y_pred = np.clip(y_pred, y_min - y_range, y_max + y_range)
y_pred = y_pred.reshape(n_t, n_mf)
for ti, t in enumerate(unique_tickers):
for fi, f in enumerate(model_fields):
cell_pred[(t, f)] = float(y_pred[ti, fi])
for i in range(n_rows):
t = ticker_arr[i]
fy = fy_arr[i]
for field in fitted_fields:
if field in median_fields:
val = median_fields[field]
else:
val = cell_pred.get((t, field), 0.0)
rows.append({
"ticker": t,
"fiscal_year": fy,
"field": field,
"pred": float(val),
})
return pd.DataFrame(
rows, columns=["ticker", "fiscal_year", "field", "pred"],
)
# ── T4 — flat-lookback + event-type one-hot ───────────────────────────
def _fit_t4(self, X: pd.DataFrame, y: np.ndarray) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T4 fit: expected DataFrame X; got {type(X).__name__}"
)
if "lookback" not in X.columns or "event_type" not in X.columns:
raise ValueError(
"T4 fit: X must include 'lookback' and 'event_type' columns."
)
flat, n_lb_flat = self._t4_flatten_lookback(X["lookback"])
et_arr = X["event_type"].astype(str).values
et_dummies = pd.get_dummies(
pd.Series(et_arr), prefix="evt", dtype=np.float32,
)
X_arr = np.concatenate(
[flat, et_dummies.values.astype(np.float32)], axis=1,
)
# sklearn RF rejects NaN/inf — zero-fill.
X_arr = np.nan_to_num(
X_arr, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
y_arr = np.asarray(y, dtype=np.float32).ravel()
if y_arr.shape[0] != X_arr.shape[0]:
raise ValueError(
f"T4 fit: y/X length mismatch ({y_arr.shape[0]} vs "
f"{X_arr.shape[0]})."
)
model = _make_rf_estimator(self.config, seed=self._seed)
model.fit(X_arr, y_arr)
self._state = {
"model": model,
"evt_columns": list(et_dummies.columns),
"n_lb_flat": int(n_lb_flat),
}
def _predict_t4(self, X: pd.DataFrame) -> np.ndarray:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T4 predict: expected DataFrame; got {type(X).__name__}"
)
if "lookback" not in X.columns or "event_type" not in X.columns:
raise ValueError(
"T4 predict: X must include 'lookback' and 'event_type'."
)
flat, _ = self._t4_flatten_lookback(X["lookback"])
if flat.shape[1] > st["n_lb_flat"]:
flat = flat[:, : st["n_lb_flat"]]
elif flat.shape[1] < st["n_lb_flat"]:
pad = np.zeros(
(flat.shape[0], st["n_lb_flat"] - flat.shape[1]),
dtype=np.float32,
)
flat = np.concatenate([flat, pad], axis=1)
et_arr = X["event_type"].astype(str).values
et_dummies = pd.get_dummies(
pd.Series(et_arr), prefix="evt", dtype=np.float32,
)
for c in st["evt_columns"]:
if c not in et_dummies.columns:
et_dummies[c] = 0.0
et_dummies = et_dummies[st["evt_columns"]].fillna(0.0)
X_arr = np.concatenate(
[flat, et_dummies.values.astype(np.float32)], axis=1,
)
X_arr = np.nan_to_num(
X_arr, nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
return st["model"].predict(X_arr).astype(np.float32)
# ── T7 — dual-output (rent, price) ────────────────────────────────────
def _fit_t7(self, X: pd.DataFrame, y: pd.DataFrame) -> None:
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T7 fit: expected DataFrame X; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("T7 fit: X must include 'address'.")
df, feat_cols, prop_type_col = self._t7_build_features(X, fit=True)
rent_col = self._t7_first_col(df, ("rent",))
price_col = self._t7_first_col(df, ("price", "lastsaleprice"))
if isinstance(y, pd.DataFrame) and "address" in y.columns:
if rent_col is None and "rent" in y.columns:
df = df.merge(
y[["address", "rent"]], on="address", how="left",
)
rent_col = "rent"
if price_col is None and "price" in y.columns:
df = df.merge(
y[["address", "price"]], on="address", how="left",
)
price_col = "price"
if rent_col is None and price_col is None:
raise RuntimeError("T7 fit: no rent or price target found.")
# sklearn RF rejects NaN/inf — zero-fill.
X_feat = df[feat_cols].astype(np.float32)
X_arr = np.nan_to_num(
X_feat.values.astype(np.float32),
nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
models: dict[str, Any] = {}
for target_name, target_col in (("rent", rent_col), ("price", price_col)):
if target_col is None:
continue
y_all = pd.to_numeric(df[target_col], errors="coerce")
valid = y_all.notna() & (y_all > 0)
n_valid = int(valid.sum())
if n_valid < 1:
continue
X_tr = X_arr[valid.values]
y_tr = y_all.loc[valid].values.astype(np.float64)
if n_valid < 2:
# RandomForest tolerates n=1 but eval is degenerate; emit a
# constant predictor to match LightGBM's degenerate-case
# behaviour exactly (smoke-run path only).
models[target_name] = ("constant", float(y_tr.mean()))
continue
m = _make_rf_log_pipeline(self.config, seed=self._seed)
m.fit(X_tr, y_tr)
models[target_name] = m
if not models:
raise RuntimeError(
f"T7 fit: insufficient training data "
f"(rent_col={rent_col!r}, price_col={price_col!r}, "
f"n_rows={len(df)}); need >=1 row with a positive target."
)
self._state = {
"feat_cols": feat_cols,
"prop_type_col": prop_type_col,
"models": models,
}
def _predict_t7(self, X: pd.DataFrame) -> pd.DataFrame:
st = self._state
if not isinstance(X, pd.DataFrame):
raise TypeError(
f"T7 predict: expected DataFrame; got {type(X).__name__}"
)
if "address" not in X.columns:
raise ValueError("T7 predict: X must include 'address'.")
df = X.copy()
for col in (
"sqft", "squareFootage", "square_footage",
"beds", "bedrooms", "baths", "bathrooms",
"year_built", "yearBuilt",
"years_since_last_sale",
):
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors="coerce")
prop_type_col = st["prop_type_col"]
if prop_type_col and prop_type_col in df.columns:
prop_dummies = pd.get_dummies(
df[prop_type_col], prefix="ptype", dtype=np.float32,
)
df = pd.concat(
[df.reset_index(drop=True), prop_dummies.reset_index(drop=True)],
axis=1,
)
# Zero-fill NaN at align time and scrub stragglers — RF rejects them.
X_feat = _align_columns(
df, st["feat_cols"], fillna=True,
).astype(np.float32)
X_arr = np.nan_to_num(
X_feat.values.astype(np.float32),
nan=0.0, posinf=0.0, neginf=0.0,
).astype(np.float32)
out = pd.DataFrame({"address": X["address"].astype(str).values})
for target_name in ("rent", "price"):
model = st["models"].get(target_name)
if model is None:
out[f"pred_{target_name}"] = np.full(
len(X), np.nan, dtype=np.float32,
)
continue
if isinstance(model, tuple) and model[0] == "constant":
out[f"pred_{target_name}"] = np.full(
len(X), float(model[1]), dtype=np.float32,
)
continue
preds = model.predict(X_arr)
preds = np.clip(preds, 0.0, None)
out[f"pred_{target_name}"] = preds.astype(np.float32)
return out