sales-dashboard / src /feature_engineering.py
Hamza4100's picture
Upload 20 files
7f5d85f verified
Raw History Blame Contribute Delete
8.9 kB
"""
feature_engineering.py
-----------------------
Build ML-ready feature matrices from cleaned time-series sales data.
"""
from __future__ import annotations
from typing import List, Optional, Tuple
import numpy as np
import pandas as pd
from src.utils import robust_to_datetime
# ---------------------------------------------------------------------------
# Lag / rolling window configuration per frequency
# ---------------------------------------------------------------------------
_LAG_CONFIG = {
"Daily": [1, 7, 14, 28],
"Weekly": [1, 2, 4, 8],
"Monthly": [1, 2, 3, 6, 12],
}
_ROLLING_CONFIG = {
# (window, stat) pairs
"Daily": [(7, "mean"), (14, "mean"), (7, "std")],
"Weekly": [(4, "mean"), (8, "mean"), (4, "std")],
"Monthly": [(3, "mean"), (6, "mean"), (3, "std")],
}
# ---------------------------------------------------------------------------
# Public functions
# ---------------------------------------------------------------------------
def create_features(
df: pd.DataFrame,
date_col: str,
sales_col: str,
freq: str,
) -> Tuple[pd.DataFrame, pd.Series, List[str]]:
"""Build a supervised ML feature matrix from a cleaned time-series dataframe.
The input *df* must have either a ``DatetimeIndex`` **or** a column named
*date_col*. The function does **not** leak future information: all lag
and rolling features are shift-based.
Date features (always created)
--------------------------------
``year``, ``month``, ``quarter``, ``week_of_year``, ``day_of_month``,
``day_of_week``, ``day_of_year``, ``is_weekend`` (Daily only),
``month_sin``, ``month_cos``
Lag features (frequency-dependent, all shift-based)
-----------------------------------------------------
Daily : lag_1, lag_7, lag_14, lag_28
Weekly : lag_1, lag_2, lag_4, lag_8
Monthly : lag_1, lag_2, lag_3, lag_6, lag_12
Rolling features (frequency-dependent)
----------------------------------------
Daily : rolling_mean_7, rolling_mean_14, rolling_std_7
Weekly : rolling_mean_4, rolling_mean_8, rolling_std_4
Monthly : rolling_mean_3, rolling_mean_6, rolling_std_3
Parameters
----------
df : pd.DataFrame
Cleaned dataframe (output of DataPreprocessor.fit_transform).
date_col : str
Name of the date column (or the index name when DatetimeIndex).
sales_col : str
Name of the target sales column.
freq : str
One of ``"Daily"``, ``"Weekly"``, ``"Monthly"``.
Returns
-------
X : pd.DataFrame
Feature matrix (NaN rows from lag creation are dropped).
y : pd.Series
Target sales values aligned with *X*.
feature_names : list[str]
Ordered list of feature column names in *X*.
"""
data = df.copy()
data.index.name = None
# Ensure we have a column-based view of dates
if date_col not in data.columns:
if isinstance(data.index, pd.DatetimeIndex):
data[date_col] = data.index
data[date_col] = robust_to_datetime(data[date_col])
data = data.sort_values(by=date_col)
sales = data[sales_col].copy()
# --- Date features -----------------------------------------------------
data["year"] = data[date_col].dt.year
data["month"] = data[date_col].dt.month
data["quarter"] = data[date_col].dt.quarter
data["week_of_year"] = data[date_col].dt.isocalendar().week.astype(int)
data["day_of_month"] = data[date_col].dt.day
data["day_of_week"] = data[date_col].dt.dayofweek
data["day_of_year"] = data[date_col].dt.dayofyear
if freq == "Daily":
data["is_weekend"] = (data["day_of_week"] >= 5).astype(int)
# Cyclical month encoding
data["month_sin"] = np.sin(2 * np.pi * data["month"] / 12)
data["month_cos"] = np.cos(2 * np.pi * data["month"] / 12)
# --- Lag features (shift-based, no leakage) ----------------------------
lags = _LAG_CONFIG.get(freq, _LAG_CONFIG["Monthly"])
for lag in lags:
data[f"lag_{lag}"] = sales.shift(lag)
# --- Rolling features (shift(1) ensures no leakage) --------------------
rolling_cfgs = _ROLLING_CONFIG.get(freq, _ROLLING_CONFIG["Monthly"])
for window, stat in rolling_cfgs:
shifted = sales.shift(1)
if stat == "mean":
data[f"rolling_mean_{window}"] = shifted.rolling(window=window).mean()
elif stat == "std":
data[f"rolling_std_{window}"] = shifted.rolling(window=window).std()
# --- Drop NaN rows introduced by lags ----------------------------------
feature_cols = [
c for c in data.columns if c not in (date_col, sales_col)
]
data = data.dropna(subset=feature_cols)
dates_aligned = data[date_col]
sales_aligned = data[sales_col]
X = data[feature_cols].copy()
X.index = pd.DatetimeIndex(dates_aligned)
y = sales_aligned.copy()
y.index = pd.DatetimeIndex(dates_aligned)
feature_names = list(X.columns)
return X, y, feature_names
def create_future_features(
last_known_df: pd.DataFrame,
future_dates: pd.DatetimeIndex,
freq: str,
trained_feature_names: List[str],
previous_preds: Optional[List[float]] = None,
) -> pd.DataFrame:
"""Build feature rows for future dates using recursive forecasting logic.
For each future date, lag features are sourced from *previous_preds*
(earlier future predictions) and from the tail of *last_known_df* (the
historical sales values).
Parameters
----------
last_known_df : pd.DataFrame
The cleaned historical dataframe before adding features. Must
contain the sales column as the sole non-index column.
future_dates : pd.DatetimeIndex
The future date range to build features for.
freq : str
One of ``"Daily"``, ``"Weekly"``, ``"Monthly"``.
trained_feature_names : list[str]
The exact feature columns produced by create_features; the returned
dataframe will have exactly these columns in this order.
previous_preds : list[float], optional
Accumulating list of predictions already made for earlier future dates
in this same forecast run. Updated externally by the caller.
Returns
-------
pd.DataFrame
One row per future date, columns matching *trained_feature_names*.
Missing values are filled with 0 as a safe fallback.
"""
if previous_preds is None:
previous_preds = []
# Build a combined historical + already-predicted series for lag look-ups
sales_col = last_known_df.columns[0] # single sales column
hist_values = list(last_known_df[sales_col].values)
combined_values = hist_values + list(previous_preds)
lags = _LAG_CONFIG.get(freq, _LAG_CONFIG["Monthly"])
rolling_cfgs = _ROLLING_CONFIG.get(freq, _ROLLING_CONFIG["Monthly"])
rows = []
for step, fdate in enumerate(future_dates):
# Total index into combined_values for this future step
idx = len(hist_values) + step
row: dict = {}
# --- Date features -----------------------------------------------
row["year"] = fdate.year
row["month"] = fdate.month
row["quarter"] = fdate.quarter
row["week_of_year"] = int(fdate.isocalendar()[1])
row["day_of_month"] = fdate.day
row["day_of_week"] = fdate.dayofweek
row["day_of_year"] = fdate.dayofyear
if freq == "Daily":
row["is_weekend"] = int(fdate.dayofweek >= 5)
row["month_sin"] = float(np.sin(2 * np.pi * fdate.month / 12))
row["month_cos"] = float(np.cos(2 * np.pi * fdate.month / 12))
# --- Lag features ------------------------------------------------
for lag in lags:
look_back = idx - lag
if 0 <= look_back < len(combined_values):
row[f"lag_{lag}"] = float(combined_values[look_back])
else:
row[f"lag_{lag}"] = 0.0
# --- Rolling features (window over values before this step) ------
for window, stat in rolling_cfgs:
window_vals = [
float(combined_values[i])
for i in range(max(0, idx - window), idx)
if i < len(combined_values)
]
if stat == "mean":
row[f"rolling_mean_{window}"] = float(np.mean(window_vals)) if window_vals else 0.0
elif stat == "std":
row[f"rolling_std_{window}"] = float(np.std(window_vals, ddof=1)) if len(window_vals) > 1 else 0.0
rows.append(row)
future_df = pd.DataFrame(rows)
# Align columns to trained_feature_names exactly
for col in trained_feature_names:
if col not in future_df.columns:
future_df[col] = 0.0
future_df = future_df[trained_feature_names].fillna(0.0)
return future_df