""" Simplified feature engineering for planning-bucket classification. Only 5 real features + 384 embedding dims = 389 total. No city, no province, no day_of_month, no per-counterparty stats. The merchant name embedding does the heavy lifting. Usage: from src.data.preprocessor_v2 import build_feature_matrix feat_df = build_feature_matrix(raw_df) """ import re import numpy as np import pandas as pd _STRIP_PATTERN = re.compile(r"[^a-z\s]") def clean_merchant_name(name: str) -> str: if not isinstance(name, str): return "" return " ".join(_STRIP_PATTERN.sub(" ", name.lower()).split()) def build_feature_matrix(df: pd.DataFrame, include_targets: bool = True) -> pd.DataFrame: out = pd.DataFrame(index=df.index) # Amount (log-compressed) amount_cad = df["amount_minor"].abs() / 100.0 out["amount_log1p"] = np.log1p(amount_cad) # Direction out["is_inflow"] = (df["amount_minor"] < 0).astype(int) # Income ratio income = df.get("monthly_income_minor", pd.Series(0, index=df.index)) income = income.replace(0, np.nan).fillna(np.nan) out["income_ratio"] = (df["amount_minor"].abs() / income).fillna(-1.0) # Merchant name (cleaned, for embedding lookup) out["merchant_name_clean"] = df["merchant_name"].apply(clean_merchant_name) # Categorical out["account_type"] = df.get("account_type", pd.Series("unknown", index=df.index)).fillna("unknown").astype(str) out["is_recurring_candidate"] = df.get("is_recurring_candidate", pd.Series("unknown", index=df.index)).fillna("unknown").astype(str) # Target if include_targets and "planning_bucket" in df.columns: out["planning_bucket"] = df["planning_bucket"] return out NUMERIC_FEATURES = ["amount_log1p", "is_inflow", "income_ratio"] CATEGORICAL_FEATURES = ["account_type", "is_recurring_candidate"] TABULAR_FEATURES = NUMERIC_FEATURES + CATEGORICAL_FEATURES