Download src/forecasting.py from Hamza4100/sales-forecasting-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 6.66 kB
-
https://huggingface.co/spaces/Hamza4100/sales-forecasting-dashboard/resolve/main/src/forecasting.py
- Command line
-
hf download hf://spaces/Hamza4100/sales-forecasting-dashboard/src/forecasting.py
-
curl -L -o forecasting.py https://huggingface.co/spaces/Hamza4100/sales-forecasting-dashboard/resolve/main/src/forecasting.py
6.66 kB
| """ | |
| forecasting.py | |
| -------------- | |
| Recursive future forecasting using trained ML models. | |
| """ | |
| from __future__ import annotations | |
| from typing import List | |
| import numpy as np | |
| import pandas as pd | |
| from src.feature_engineering import create_future_features | |
| from src.utils import generate_future_dates, get_frequency_alias | |
| class Forecaster: | |
| """Wrap a fitted model and produce multi-step ahead sales forecasts. | |
| Parameters | |
| ---------- | |
| model : fitted scikit-learn estimator | |
| A model already trained on the feature set produced by | |
| :func:`~feature_engineering.create_features`. | |
| feature_names : list[str] | |
| Ordered feature column names the model was trained on. | |
| freq : str | |
| One of ``"Daily"``, ``"Weekly"``, ``"Monthly"``. | |
| date_col : str | |
| Name of the date column / DatetimeIndex name in the cleaned dataframe. | |
| sales_col : str | |
| Name of the sales column in the cleaned dataframe. | |
| """ | |
| def __init__( | |
| self, | |
| model: object, | |
| feature_names: List[str], | |
| freq: str, | |
| date_col: str, | |
| sales_col: str, | |
| ) -> None: | |
| self.model = model | |
| self.feature_names = feature_names | |
| self.freq = freq | |
| self.date_col = date_col | |
| self.sales_col = sales_col | |
| # ------------------------------------------------------------------ | |
| # Public API | |
| # ------------------------------------------------------------------ | |
| def forecast( | |
| self, | |
| cleaned_df: pd.DataFrame, | |
| horizon_periods: int, | |
| ) -> pd.DataFrame: | |
| """Generate a *horizon_periods*-step ahead forecast using recursive prediction. | |
| Each future step builds its feature row using all previously predicted | |
| values as proxies for future lag values. Predictions are clipped to | |
| a minimum of 0 (sales cannot be negative). | |
| Parameters | |
| ---------- | |
| cleaned_df : pd.DataFrame | |
| The cleaned historical dataframe (output of | |
| DataPreprocessor.fit_transform). Must have a DatetimeIndex or a | |
| column named *date_col*. | |
| horizon_periods : int | |
| Number of future periods to forecast. | |
| Returns | |
| ------- | |
| pd.DataFrame | |
| Columns: ``date`` (datetime), ``forecast`` (float). | |
| """ | |
| sales_series = self._get_sales_series(cleaned_df) | |
| last_date = sales_series.index[-1] | |
| freq_alias = get_frequency_alias(self.freq) | |
| future_dates = generate_future_dates(last_date, horizon_periods, freq_alias) | |
| # Build a dataframe with just the sales column for context look-ups | |
| context_df = sales_series.to_frame(name=self.sales_col) | |
| predictions: List[float] = [] | |
| for step in range(horizon_periods): | |
| # We re-call create_future_features with the growing predictions list. | |
| # Only the final row (index -1) corresponds to the current step. | |
| current_dates = future_dates[: step + 1] | |
| feat_df = create_future_features( | |
| last_known_df=context_df, | |
| future_dates=current_dates, | |
| freq=self.freq, | |
| trained_feature_names=self.feature_names, | |
| previous_preds=list(predictions), # pass a copy | |
| ) | |
| # Predict for the current future step (last row) | |
| X_step = feat_df.iloc[[-1]] | |
| pred = float(self.model.predict(X_step)[0]) | |
| pred = max(0.0, pred) # clip: sales cannot be negative | |
| predictions.append(pred) | |
| forecast_df = pd.DataFrame( | |
| { | |
| "date": future_dates, | |
| "forecast": predictions, | |
| } | |
| ) | |
| return forecast_df | |
| def generate_forecast_df( | |
| self, | |
| cleaned_df: pd.DataFrame, | |
| horizon_periods: int, | |
| ) -> pd.DataFrame: | |
| """Combine historical actuals and future forecast into a single dataframe. | |
| Parameters | |
| ---------- | |
| cleaned_df : pd.DataFrame | |
| The cleaned historical dataframe. | |
| horizon_periods : int | |
| Number of future periods to forecast. | |
| Returns | |
| ------- | |
| pd.DataFrame | |
| Columns: | |
| * ``date`` - datetime for every historical and future period | |
| * ``actual`` - historical sales (NaN for future rows) | |
| * ``forecast`` - NaN for historical rows, predicted value for future rows | |
| """ | |
| sales_series = self._get_sales_series(cleaned_df) | |
| # Build the future forecast | |
| future_df = self.forecast(cleaned_df, horizon_periods) | |
| # Historical part | |
| historical = pd.DataFrame( | |
| { | |
| "date": sales_series.index, | |
| "actual": sales_series.values, | |
| "forecast": np.nan, | |
| } | |
| ) | |
| # Future part | |
| future = pd.DataFrame( | |
| { | |
| "date": future_df["date"].values, | |
| "actual": np.nan, | |
| "forecast": future_df["forecast"].values, | |
| } | |
| ) | |
| combined = pd.concat([historical, future], ignore_index=True) | |
| combined["date"] = pd.to_datetime(combined["date"]) | |
| return combined | |
| # ------------------------------------------------------------------ | |
| # Private helpers | |
| # ------------------------------------------------------------------ | |
| def _get_sales_series(self, cleaned_df: pd.DataFrame) -> pd.Series: | |
| """Extract the sales series from *cleaned_df* as a DatetimeIndex series. | |
| Parameters | |
| ---------- | |
| cleaned_df : pd.DataFrame | |
| Cleaned dataframe from DataPreprocessor. | |
| Returns | |
| ------- | |
| pd.Series | |
| Sales values indexed by datetime. | |
| """ | |
| df = cleaned_df.copy() | |
| if isinstance(df.index, pd.DatetimeIndex): | |
| if self.sales_col in df.columns: | |
| return df[self.sales_col] | |
| # Fallback: first numeric column | |
| for col in df.columns: | |
| if pd.api.types.is_numeric_dtype(df[col]): | |
| return df[col] | |
| raise ValueError("Cannot locate the sales column in the cleaned dataframe.") | |
| # Non-DatetimeIndex: try to set date_col as index | |
| if self.date_col in df.columns: | |
| df[self.date_col] = pd.to_datetime(df[self.date_col]) | |
| df = df.set_index(self.date_col) | |
| if self.sales_col in df.columns: | |
| return df[self.sales_col] | |
| raise ValueError( | |
| f"Sales column '{self.sales_col}' not found in cleaned dataframe." | |
| ) | |