| """Naive / statistical methods for the MacroLens unified API. |
| |
| Five concrete classes, one per (model × subset of tasks): |
| |
| Persistence T1 (N, horizon) -- last-close tile |
| HistoricalAnalogue T4 (N,) -- per-event-type train mean |
| LogSizeOLS T2, T5 (N,) -- log1p OLS on numerics |
| SectorMedian T3, T6 long-form -- per-(sector, field) train median |
| MetroMedian T7 (N, 3) -- per-(state, property_type) median |
| |
| Every class: |
| |
| * Inherits :class:`_JoblibSaveMixin` (state.joblib + manifest.json). |
| * Registers via :func:`register` so `ml.methods.<Name>` finds it. |
| * Receives ``task`` as a constructor arg; a ``ValueError`` is raised if |
| the requested task is not in :attr:`tasks`. |
| |
| 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 |
| import logging |
| from typing import Any, ClassVar |
|
|
| import numpy as np |
| import pandas as pd |
|
|
| from ._config import ( |
| HistoricalAnalogueConfig, |
| LogSizeOLSConfig, |
| MetroMedianConfig, |
| PersistenceConfig, |
| SectorMedianConfig, |
| ) |
| from ._registry import register |
| from .base import Method, _JoblibSaveMixin |
|
|
| logger = logging.getLogger(__name__) |
| _PERSISTENCE_DEFAULT_CLOSE_IDX_LOGGED: bool = False |
|
|
|
|
| |
|
|
|
|
| def _naive_lib_versions() -> dict[str, str]: |
| """Versions of the three libs the naive family actually uses. |
| |
| Overrides the broader default in :class:`Method` (which probes torch / |
| transformers / vllm too) -- those are not imported here and recording |
| them on a naive-method RunRecord would be misleading. |
| """ |
| out: dict[str, str] = {} |
| for pkg in ("numpy", "pandas", "scikit-learn"): |
| try: |
| out[pkg] = importlib.metadata.version(pkg) |
| except importlib.metadata.PackageNotFoundError: |
| pass |
| return out |
|
|
|
|
| |
|
|
|
|
| @register( |
| name="persistence", |
| family="naive", |
| tasks=frozenset({"T1"}), |
| config_class=PersistenceConfig, |
| ) |
| class Persistence(_JoblibSaveMixin, Method): |
| """Forecast the future close trajectory by tiling the last lookback close. |
| |
| Predict shape: ``(N, horizon)``. The class emits a constant trajectory |
| per row equal to ``X[:, -1, close_feature_idx]`` tiled ``horizon`` |
| times. This is the trivial-floor baseline; any real T1 method should |
| beat it. |
| |
| Notes |
| ----- |
| * ``X`` is a numpy ndarray ``(N, lookback, F)`` with no column names, |
| so the runner is responsible for passing the close-feature index |
| via ``PersistenceConfig.close_feature_idx`` (default ``0``). |
| * ``horizon`` is read from ``y.shape[1]`` at fit time and stored as |
| ``self._horizon``; if ``config.horizon`` is set it overrides. |
| """ |
|
|
| name: ClassVar[str] = "persistence" |
| family: ClassVar[str] = "naive" |
| tasks: ClassVar[frozenset[str]] = frozenset({"T1"}) |
| schema_version: ClassVar[int] = 1 |
|
|
| def __init__( |
| self, |
| *, |
| task: str, |
| config: PersistenceConfig | None = None, |
| **kwargs: Any, |
| ) -> None: |
| if task not in self.tasks: |
| raise ValueError( |
| f"Persistence does not support task={task!r}; " |
| f"supported: {sorted(self.tasks)}" |
| ) |
| self.task = task |
| self.config = config or PersistenceConfig(**kwargs) |
| if self.task == "T1" and self.config.close_feature_idx == 0: |
| |
| |
| |
| global _PERSISTENCE_DEFAULT_CLOSE_IDX_LOGGED |
| if not _PERSISTENCE_DEFAULT_CLOSE_IDX_LOGGED: |
| logger.info( |
| "Persistence(task='T1'): close_feature_idx defaults to 0; " |
| "the runner should resolve the actual close column index " |
| "from meta.attrs['feature_names'] and pass it via config." |
| ) |
| _PERSISTENCE_DEFAULT_CLOSE_IDX_LOGGED = True |
| self._horizon: int | None = None |
| self._close_feature_idx: int = int(self.config.close_feature_idx) |
|
|
| @classmethod |
| def default_config(cls) -> PersistenceConfig: |
| return PersistenceConfig() |
|
|
| def fit(self, X: np.ndarray, y: np.ndarray, *, seed: int = 42) -> "Persistence": |
| if not isinstance(X, np.ndarray) or X.ndim != 3: |
| raise ValueError( |
| f"Persistence.fit: expected X shape (N, lookback, F); got " |
| f"type={type(X).__name__} shape={getattr(X, 'shape', '?')}" |
| ) |
| if not isinstance(y, np.ndarray) or y.ndim != 2: |
| raise ValueError( |
| f"Persistence.fit: expected y shape (N, horizon); got " |
| f"type={type(y).__name__} shape={getattr(y, 'shape', '?')}" |
| ) |
| |
| self._horizon = ( |
| int(self.config.horizon) |
| if self.config.horizon is not None |
| else int(y.shape[1]) |
| ) |
| if self._close_feature_idx >= X.shape[2]: |
| raise ValueError( |
| f"Persistence.fit: close_feature_idx={self._close_feature_idx} " |
| f"out of bounds for F={X.shape[2]}" |
| ) |
| return self |
|
|
| def predict(self, X: np.ndarray) -> np.ndarray: |
| if self._horizon is None: |
| raise RuntimeError("Persistence: call .fit(X, y) before .predict().") |
| if not isinstance(X, np.ndarray) or X.ndim != 3: |
| raise ValueError( |
| f"Persistence.predict: expected (N, lookback, F); got " |
| f"type={type(X).__name__} shape={getattr(X, 'shape', '?')}" |
| ) |
| if self._close_feature_idx >= X.shape[2]: |
| raise ValueError( |
| f"Persistence.predict: close_feature_idx={self._close_feature_idx} " |
| f"out of bounds for F={X.shape[2]}" |
| ) |
| last_close = X[:, -1, self._close_feature_idx][:, np.newaxis] |
| return np.tile(last_close, (1, self._horizon)).astype(np.float32) |
|
|
| def lib_versions(self) -> dict[str, str]: |
| return _naive_lib_versions() |
|
|
|
|
| |
|
|
|
|
| @register( |
| name="historical_analogue", |
| family="naive", |
| tasks=frozenset({"T4"}), |
| config_class=HistoricalAnalogueConfig, |
| ) |
| class HistoricalAnalogue(_JoblibSaveMixin, Method): |
| """Predict scenario return as the per-``event_type`` train mean. |
| |
| ``X`` is the T4 DataFrame ``[lookback, event_type, event_description]``; |
| only ``event_type`` is consumed. Unseen event types fall back to the |
| global train mean. |
| |
| Predict shape: ``(N,)`` float32. |
| """ |
|
|
| name: ClassVar[str] = "historical_analogue" |
| family: ClassVar[str] = "naive" |
| tasks: ClassVar[frozenset[str]] = frozenset({"T4"}) |
| schema_version: ClassVar[int] = 1 |
|
|
| def __init__( |
| self, |
| *, |
| task: str, |
| config: HistoricalAnalogueConfig | None = None, |
| **kwargs: Any, |
| ) -> None: |
| if task not in self.tasks: |
| raise ValueError( |
| f"HistoricalAnalogue does not support task={task!r}; " |
| f"supported: {sorted(self.tasks)}" |
| ) |
| self.task = task |
| self.config = config or HistoricalAnalogueConfig(**kwargs) |
| self._type_mean: dict[str, float] = {} |
| self._global_mean: float = 0.0 |
| self._fitted: bool = False |
|
|
| @classmethod |
| def default_config(cls) -> HistoricalAnalogueConfig: |
| return HistoricalAnalogueConfig() |
|
|
| @staticmethod |
| def _event_types(X: pd.DataFrame) -> np.ndarray: |
| if not isinstance(X, pd.DataFrame): |
| raise TypeError( |
| f"HistoricalAnalogue: expected DataFrame X; got " |
| f"{type(X).__name__}" |
| ) |
| if "event_type" not in X.columns: |
| raise ValueError( |
| "HistoricalAnalogue: X is missing 'event_type' column." |
| ) |
| return np.asarray(X["event_type"].values, dtype=object).astype(str) |
|
|
| def fit( |
| self, X: pd.DataFrame, y: np.ndarray, *, seed: int = 42 |
| ) -> "HistoricalAnalogue": |
| et = self._event_types(X) |
| y_arr = np.asarray(y, dtype=np.float64).ravel() |
| if et.shape[0] != y_arr.shape[0]: |
| raise ValueError( |
| f"HistoricalAnalogue.fit: event_type/y length mismatch " |
| f"({et.shape[0]} vs {y_arr.shape[0]})" |
| ) |
| df = pd.DataFrame({"event_type": et, "ret": y_arr}).dropna(subset=["ret"]) |
| if df.empty: |
| raise RuntimeError("HistoricalAnalogue.fit: no usable training rows.") |
| self._type_mean = df.groupby("event_type")["ret"].mean().to_dict() |
| self._global_mean = float(df["ret"].mean()) |
| self._fitted = True |
| return self |
|
|
| def predict(self, X: pd.DataFrame) -> np.ndarray: |
| if not self._fitted: |
| raise RuntimeError( |
| "HistoricalAnalogue: call .fit(X, y) before .predict()." |
| ) |
| et = self._event_types(X) |
| return np.array( |
| [self._type_mean.get(e, self._global_mean) for e in et], |
| dtype=np.float32, |
| ) |
|
|
| def lib_versions(self) -> dict[str, str]: |
| return _naive_lib_versions() |
|
|
|
|
| |
|
|
|
|
| |
| |
| |
| |
| |
| class LogSizeOLS(_JoblibSaveMixin, Method): |
| """OLS regression of ``log1p(market_cap)`` on ``log1p(numeric features)``. |
| |
| Classical-ML baseline (fitted parametric model): for T2 / T5 inputs, |
| fits a ``sklearn.linear_model.LinearRegression`` on |
| ``log1p(numeric_columns)`` plus optional sector dummies, with target |
| ``log1p(actual_market_cap)``. Predicts in log space and returns the |
| dollar-space prediction via ``np.expm1``. |
| |
| Predict shape: ``(N,)`` float32. |
| """ |
|
|
| name: ClassVar[str] = "log_size_ols" |
| family: ClassVar[str] = "classical" |
| tasks: ClassVar[frozenset[str]] = frozenset({"T2", "T5"}) |
| schema_version: ClassVar[int] = 1 |
|
|
| def __init__( |
| self, |
| *, |
| task: str, |
| config: LogSizeOLSConfig | None = None, |
| **kwargs: Any, |
| ) -> None: |
| if task not in self.tasks: |
| raise ValueError( |
| f"LogSizeOLS does not support task={task!r}; " |
| f"supported: {sorted(self.tasks)}" |
| ) |
| self.task = task |
| self.config = config or LogSizeOLSConfig(**kwargs) |
| self._model: Any = None |
| self._numeric_cols: list[str] = [] |
| self._sector_dummy_cols: list[str] = [] |
| self._train_columns: list[str] = [] |
|
|
| @classmethod |
| def default_config(cls) -> LogSizeOLSConfig: |
| return LogSizeOLSConfig() |
|
|
| @staticmethod |
| def _select_numeric(df: pd.DataFrame) -> list[str]: |
| """Return the columns this method treats as size-proxy numerics. |
| |
| Anything numeric that is neither a key (``ticker``/``date``) nor |
| the target itself qualifies. The exact set depends on the inputs |
| file the loader projected onto -- T5 strips price-derived |
| features upstream, so the same selector works for T2 and T5. |
| """ |
| skip = {"ticker", "date", "actual_market_cap", "derived_market_cap"} |
| return [ |
| c |
| for c in df.columns |
| if c not in skip and pd.api.types.is_numeric_dtype(df[c]) |
| ] |
|
|
| def _build_features( |
| self, X: pd.DataFrame, *, train_columns: list[str] | None |
| ) -> pd.DataFrame: |
| """log1p of numerics + (optional) sector dummies, aligned to train. |
| |
| ``train_columns`` is None at fit time; the post-concat order is |
| captured for predict-time alignment. |
| """ |
| numeric_cols = ( |
| self._numeric_cols if train_columns is not None else self._select_numeric(X) |
| ) |
|
|
| num = X.reindex(columns=numeric_cols).apply( |
| lambda s: pd.to_numeric(s, errors="coerce").fillna(0.0) |
| ) |
| |
| num = num.clip(lower=0.0) |
| num = np.log1p(num) |
|
|
| if self.config.sector_dummies and "sector" in X.columns: |
| dum = pd.get_dummies(X["sector"], prefix="sec", dtype=np.float32) |
| else: |
| dum = pd.DataFrame(index=X.index) |
|
|
| feat = pd.concat( |
| [num.reset_index(drop=True), dum.reset_index(drop=True)], axis=1 |
| ).fillna(0.0) |
|
|
| if train_columns is None: |
| |
| self._numeric_cols = list(numeric_cols) |
| self._sector_dummy_cols = list(dum.columns) |
| self._train_columns = list(feat.columns) |
| return feat |
|
|
| |
| for c in train_columns: |
| if c not in feat.columns: |
| feat[c] = 0.0 |
| return feat[train_columns].fillna(0.0) |
|
|
| def fit(self, X: pd.DataFrame, y: np.ndarray, *, seed: int = 42) -> "LogSizeOLS": |
| from sklearn.linear_model import LinearRegression |
|
|
| if not isinstance(X, pd.DataFrame): |
| raise TypeError( |
| f"LogSizeOLS.fit: expected DataFrame X; got {type(X).__name__}" |
| ) |
| y_arr = np.asarray(y, dtype=np.float64).ravel() |
| if y_arr.shape[0] != len(X): |
| raise ValueError( |
| f"LogSizeOLS.fit: y length {y_arr.shape[0]} != " |
| f"X length {len(X)}" |
| ) |
|
|
| |
| mask = np.isfinite(y_arr) & (y_arr > 0) |
| if not mask.any(): |
| raise RuntimeError( |
| "LogSizeOLS.fit: zero rows after dropping non-positive / NaN targets." |
| ) |
| X_fit = X.loc[mask].reset_index(drop=True) |
| y_fit = y_arr[mask] |
|
|
| feat = self._build_features(X_fit, train_columns=None) |
| target = np.log1p(y_fit.astype(np.float64)) |
|
|
| model = LinearRegression() |
| model.fit(feat.values, target) |
| self._model = model |
| return self |
|
|
| def predict(self, X: pd.DataFrame) -> np.ndarray: |
| if self._model is None: |
| raise RuntimeError("LogSizeOLS: call .fit(X, y) before .predict().") |
| if not isinstance(X, pd.DataFrame): |
| raise TypeError( |
| f"LogSizeOLS.predict: expected DataFrame; got {type(X).__name__}" |
| ) |
| feat = self._build_features(X, train_columns=self._train_columns) |
| pred_log = self._model.predict(feat.values) |
| |
| pred_log = np.clip(pred_log, 0.0, 50.0) |
| return np.expm1(pred_log).astype(np.float32) |
|
|
| def lib_versions(self) -> dict[str, str]: |
| return _naive_lib_versions() |
|
|
|
|
| |
|
|
|
|
| @register( |
| name="sector_median", |
| family="naive", |
| tasks=frozenset({"T3", "T6"}), |
| config_class=SectorMedianConfig, |
| ) |
| class SectorMedian(_JoblibSaveMixin, Method): |
| """Predict each XBRL field as the per-(sector, field) train median. |
| |
| At fit time the method: |
| 1. Reads the set of fields to predict from ``y["field"].unique()`` |
| (locked in :attr:`fitted_fields`). |
| 2. Inner-joins ``y`` against ``X[ticker, fiscal_year, sector]`` to |
| attach the train sector per row. |
| 3. Groups by ``(sector, field)`` -> median(value), with a per-field |
| global median fallback for unseen sectors. |
| |
| Predict emits a long-form DataFrame with one row per |
| ``(ticker, fiscal_year)`` × every fitted field, with the looked-up |
| sector median (fallback to per-field global median). |
| |
| Predict columns: ``[ticker, fiscal_year, field, pred]``. |
| """ |
|
|
| name: ClassVar[str] = "sector_median" |
| family: ClassVar[str] = "naive" |
| tasks: ClassVar[frozenset[str]] = frozenset({"T3", "T6"}) |
| schema_version: ClassVar[int] = 1 |
|
|
| def __init__( |
| self, |
| *, |
| task: str, |
| config: SectorMedianConfig | None = None, |
| **kwargs: Any, |
| ) -> None: |
| if task not in self.tasks: |
| raise ValueError( |
| f"SectorMedian does not support task={task!r}; " |
| f"supported: {sorted(self.tasks)}" |
| ) |
| self.task = task |
| self.config = config or SectorMedianConfig(**kwargs) |
| self.fitted_fields: list[str] = [] |
| self._field_sector_median: dict[tuple[str, str], float] = {} |
| self._field_global_median: dict[str, float] = {} |
|
|
| @classmethod |
| def default_config(cls) -> SectorMedianConfig: |
| return SectorMedianConfig() |
|
|
| @staticmethod |
| def _check_xy(X: pd.DataFrame, y: pd.DataFrame) -> None: |
| if not isinstance(X, pd.DataFrame): |
| raise TypeError( |
| f"SectorMedian: expected DataFrame X; got {type(X).__name__}" |
| ) |
| if not isinstance(y, pd.DataFrame): |
| raise TypeError( |
| f"SectorMedian: expected DataFrame y; got {type(y).__name__}" |
| ) |
| for col in ("ticker", "fiscal_year"): |
| if col not in X.columns: |
| raise ValueError(f"SectorMedian: X missing '{col}'") |
| for col in ("ticker", "fiscal_year", "field", "value"): |
| if col not in y.columns: |
| raise ValueError(f"SectorMedian: y missing '{col}'") |
|
|
| def fit( |
| self, X: pd.DataFrame, y: pd.DataFrame, *, seed: int = 42 |
| ) -> "SectorMedian": |
| self._check_xy(X, y) |
|
|
| |
| |
| |
| fitted_fields = sorted(y["field"].astype(str).unique()) |
| if not fitted_fields: |
| raise RuntimeError("SectorMedian.fit: y has zero distinct 'field' values.") |
| self.fitted_fields = fitted_fields |
|
|
| |
| sec_col = "sector" if "sector" in X.columns else None |
| if sec_col is None: |
| |
| x_keys = X[["ticker", "fiscal_year"]].copy() |
| x_keys["sector"] = "Unknown" |
| else: |
| x_keys = X[["ticker", "fiscal_year", "sector"]].copy() |
| x_keys["ticker"] = x_keys["ticker"].astype(str) |
| x_keys["fiscal_year"] = pd.to_numeric( |
| x_keys["fiscal_year"], errors="coerce" |
| ).astype("Int64") |
| x_keys["sector"] = x_keys["sector"].astype(str).fillna("Unknown") |
| x_keys = x_keys.drop_duplicates(subset=["ticker", "fiscal_year"]) |
|
|
| |
| gt = y[["ticker", "fiscal_year", "field", "value"]].copy() |
| gt["ticker"] = gt["ticker"].astype(str) |
| gt["fiscal_year"] = pd.to_numeric(gt["fiscal_year"], errors="coerce").astype( |
| "Int64" |
| ) |
| gt["field"] = gt["field"].astype(str) |
| gt["value_num"] = pd.to_numeric(gt["value"], errors="coerce") |
|
|
| joined = gt.merge(x_keys, on=["ticker", "fiscal_year"], how="left") |
| joined["sector"] = joined["sector"].fillna("Unknown") |
|
|
| valid = joined.dropna(subset=["value_num"]) |
| if valid.empty: |
| raise RuntimeError( |
| "SectorMedian.fit: no rows with finite numeric values after coercion." |
| ) |
|
|
| self._field_sector_median = ( |
| valid.groupby(["field", "sector"])["value_num"].median().to_dict() |
| ) |
| self._field_global_median = ( |
| valid.groupby("field")["value_num"].median().to_dict() |
| ) |
| return self |
|
|
| def predict(self, X: pd.DataFrame) -> pd.DataFrame: |
| if not self.fitted_fields: |
| raise RuntimeError("SectorMedian: call .fit(X, y) before .predict().") |
| if not isinstance(X, pd.DataFrame): |
| raise TypeError( |
| f"SectorMedian.predict: expected DataFrame; got {type(X).__name__}" |
| ) |
| for col in ("ticker", "fiscal_year"): |
| if col not in X.columns: |
| raise ValueError(f"SectorMedian.predict: X missing '{col}'") |
|
|
| keys = X[["ticker", "fiscal_year"]].copy() |
| if "sector" in X.columns: |
| keys["sector"] = X["sector"].astype(str).fillna("Unknown") |
| else: |
| keys["sector"] = "Unknown" |
| keys["ticker"] = keys["ticker"].astype(str) |
| keys["fiscal_year"] = pd.to_numeric( |
| keys["fiscal_year"], errors="coerce" |
| ).astype("Int64") |
|
|
| rows: list[dict[str, Any]] = [] |
| for ticker, fy, sector in zip( |
| keys["ticker"].values, |
| keys["fiscal_year"].values, |
| keys["sector"].values, |
| ): |
| for fld in self.fitted_fields: |
| med = self._field_sector_median.get( |
| (fld, sector), |
| self._field_global_median.get(fld, 0.0), |
| ) |
| rows.append( |
| { |
| "ticker": ticker, |
| "fiscal_year": fy, |
| "field": fld, |
| "pred": float(med) if pd.notna(med) else 0.0, |
| } |
| ) |
| return pd.DataFrame(rows, columns=["ticker", "fiscal_year", "field", "pred"]) |
|
|
| def lib_versions(self) -> dict[str, str]: |
| return _naive_lib_versions() |
|
|
|
|
| |
| |
| |
| |
| LogSizeRegression = LogSizeOLS |
|
|
|
|
| |
|
|
|
|
| @register( |
| name="metro_median", |
| family="naive", |
| tasks=frozenset({"T7"}), |
| config_class=MetroMedianConfig, |
| ) |
| class MetroMedian(_JoblibSaveMixin, Method): |
| """Predict rent / price as per-(state, property_type) train medians. |
| |
| Default metro key is ``state_property_type``; ``state`` and |
| ``city_state`` are also supported via :attr:`MetroMedianConfig.metro_key`. |
| |
| Fit consumes ``y[address, rent, price]`` for the train labels and |
| ``X[state, property_type]`` for the metro key. Unseen metros fall back |
| to the global train median (per output). |
| |
| Predict columns: ``[address, pred_rent, pred_price]``. |
| """ |
|
|
| name: ClassVar[str] = "metro_median" |
| family: ClassVar[str] = "naive" |
| tasks: ClassVar[frozenset[str]] = frozenset({"T7"}) |
| schema_version: ClassVar[int] = 1 |
|
|
| def __init__( |
| self, |
| *, |
| task: str, |
| config: MetroMedianConfig | None = None, |
| **kwargs: Any, |
| ) -> None: |
| if task not in self.tasks: |
| raise ValueError( |
| f"MetroMedian does not support task={task!r}; " |
| f"supported: {sorted(self.tasks)}" |
| ) |
| self.task = task |
| self.config = config or MetroMedianConfig(**kwargs) |
| self._metro_rent_median: dict[str, float] = {} |
| self._metro_price_median: dict[str, float] = {} |
| self._global_rent_median: float = 0.0 |
| self._global_price_median: float = 0.0 |
| self._has_rent: bool = False |
| self._has_price: bool = False |
| self._fitted: bool = False |
|
|
| @classmethod |
| def default_config(cls) -> MetroMedianConfig: |
| return MetroMedianConfig() |
|
|
| def _metro_key(self, df: pd.DataFrame) -> np.ndarray: |
| """Build the per-row metro key from X according to config.metro_key.""" |
| kind = self.config.metro_key |
| if kind == "state": |
| cols = ["state"] |
| elif kind == "city_state": |
| cols = ["city", "state"] |
| elif kind == "state_property_type": |
| cols = ["state", "property_type"] |
| else: |
| raise ValueError(f"Unknown metro_key={kind!r}") |
|
|
| for c in cols: |
| if c not in df.columns: |
| raise ValueError( |
| f"MetroMedian: column '{c}' missing from X " |
| f"(metro_key={kind!r} requires {cols})" |
| ) |
|
|
| parts = [df[c].astype(str).fillna("").str.strip() for c in cols] |
| out = parts[0] |
| for p in parts[1:]: |
| out = out.str.cat(p, sep="|") |
| return np.where(out.values == "", "Unknown", out.values) |
|
|
| def fit( |
| self, X: pd.DataFrame, y: pd.DataFrame, *, seed: int = 42 |
| ) -> "MetroMedian": |
| if not isinstance(X, pd.DataFrame): |
| raise TypeError( |
| f"MetroMedian.fit: expected DataFrame X; got {type(X).__name__}" |
| ) |
| if not isinstance(y, pd.DataFrame): |
| raise TypeError( |
| f"MetroMedian.fit: expected DataFrame y; got {type(y).__name__}" |
| ) |
|
|
| |
| if "address" not in X.columns or "address" not in y.columns: |
| raise ValueError( |
| "MetroMedian.fit: both X and y must contain 'address'." |
| ) |
| df = X.merge( |
| y[["address", *[c for c in ("rent", "price") if c in y.columns]]], |
| on="address", |
| how="inner", |
| ) |
| if df.empty: |
| raise RuntimeError( |
| "MetroMedian.fit: zero rows after joining X with y on address." |
| ) |
|
|
| metro = self._metro_key(df) |
| df = df.assign(_metro=metro) |
|
|
| if "rent" in df.columns: |
| rv = pd.to_numeric(df["rent"], errors="coerce") |
| r = pd.DataFrame({"metro": df["_metro"].values, "rent": rv.values}).dropna() |
| if not r.empty: |
| self._metro_rent_median = r.groupby("metro")["rent"].median().to_dict() |
| self._global_rent_median = float(r["rent"].median()) |
| self._has_rent = True |
| if "price" in df.columns: |
| pv = pd.to_numeric(df["price"], errors="coerce") |
| p = pd.DataFrame({"metro": df["_metro"].values, "price": pv.values}).dropna() |
| if not p.empty: |
| self._metro_price_median = p.groupby("metro")["price"].median().to_dict() |
| self._global_price_median = float(p["price"].median()) |
| self._has_price = True |
| self._fitted = True |
| return self |
|
|
| def predict(self, X: pd.DataFrame) -> pd.DataFrame: |
| if not self._fitted: |
| raise RuntimeError("MetroMedian: call .fit(X, y) before .predict().") |
| if not isinstance(X, pd.DataFrame): |
| raise TypeError( |
| f"MetroMedian.predict: expected DataFrame; got {type(X).__name__}" |
| ) |
| if "address" not in X.columns: |
| raise ValueError("MetroMedian.predict: X missing 'address'.") |
|
|
| metro = self._metro_key(X) |
| out = pd.DataFrame({"address": X["address"].astype(str).values}) |
| if self._has_rent: |
| out["pred_rent"] = [ |
| self._metro_rent_median.get(m, self._global_rent_median) for m in metro |
| ] |
| else: |
| out["pred_rent"] = np.nan |
| if self._has_price: |
| out["pred_price"] = [ |
| self._metro_price_median.get(m, self._global_price_median) for m in metro |
| ] |
| else: |
| out["pred_price"] = np.nan |
| return out |
|
|
| def lib_versions(self) -> dict[str, str]: |
| return _naive_lib_versions() |
|
|