BackendPayactiv / forecast.py
JoyZhan's picture
Upload 13 files
04bc9df verified
Raw History Blame Contribute Delete
8.52 kB
"""EWA (Exponential Weighted Average) demand forecast model.
Supports:
* Simple (single) exponential smoothing – level only
* Holt's (double) exponential smoothing – level + trend
"""
from __future__ import annotations
import math
from dataclasses import dataclass, field
from typing import List, Optional, Tuple
import numpy as np
from scipy import optimize
@dataclass
class _SESResult:
"""Fitted simple exponential smoothing state."""
alpha: float
level: float # last fitted level (= one-step-ahead forecast)
residuals: List[float] = field(default_factory=list)
@dataclass
class _DESResult:
"""Fitted double (Holt's) exponential smoothing state."""
alpha: float
beta: float
level: float
trend: float
residuals: List[float] = field(default_factory=list)
class EWAForecastModel:
"""EWA demand forecast model with optional trend component.
Parameters
----------
alpha:
Level smoothing factor. When *None* (default) the value is
optimised automatically by minimising in-sample SSE.
beta:
Trend smoothing factor. When *None* (default) the model decides
automatically: if *alpha* is also *None* it optimises both; if
*alpha* is supplied it defaults to simple exponential smoothing.
"""
def __init__(
self,
alpha: Optional[float] = None,
beta: Optional[float] = None,
) -> None:
self.alpha = alpha
self.beta = beta
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def fit_predict(
self,
history: List[float],
horizon: int,
confidence_level: float = 0.95,
) -> Tuple[List[float], List[Tuple[float, float]], float, Optional[float], str, Optional[float]]:
"""Fit the model on *history* and return a forecast.
Returns
-------
(forecast, intervals, alpha_used, beta_used, model_type, rmse)
"""
data = np.asarray(history, dtype=float)
use_trend = self._should_use_trend(data)
if use_trend:
result = self._fit_double(data)
forecast_vals = self._forecast_double(result, horizon)
model_type = "double"
alpha_used = result.alpha
beta_used: Optional[float] = result.beta
residuals = result.residuals
else:
result_s = self._fit_simple(data)
forecast_vals = self._forecast_simple(result_s, horizon)
model_type = "simple"
alpha_used = result_s.alpha
beta_used = None
residuals = result_s.residuals
rmse = self._rmse(residuals) if residuals else None
intervals = self._prediction_intervals(
forecast_vals, residuals, confidence_level
)
return forecast_vals, intervals, alpha_used, beta_used, model_type, rmse
# ------------------------------------------------------------------
# Model selection
# ------------------------------------------------------------------
def _should_use_trend(self, data: np.ndarray) -> bool:
"""Use double smoothing when beta is provided or when both alpha
and beta are None and there is enough data to detect a trend."""
if self.beta is not None:
return True
if self.alpha is None:
# auto mode: use double smoothing if series is long enough
return len(data) >= 4
return False
# ------------------------------------------------------------------
# Simple exponential smoothing
# ------------------------------------------------------------------
def _fit_simple(self, data: np.ndarray) -> _SESResult:
alpha = self.alpha
if alpha is None:
alpha = self._optimise_alpha(data)
level, residuals = self._ses_smooth(data, alpha)
return _SESResult(alpha=alpha, level=level, residuals=residuals)
@staticmethod
def _ses_smooth(data: np.ndarray, alpha: float) -> Tuple[float, List[float]]:
level = float(data[0])
residuals: List[float] = []
for obs in data[1:]:
fitted = level
residuals.append(float(obs) - fitted)
level = alpha * float(obs) + (1.0 - alpha) * level
return level, residuals
def _optimise_alpha(self, data: np.ndarray) -> float:
def sse(a: float) -> float:
_, res = self._ses_smooth(data, float(a))
return sum(r ** 2 for r in res)
result = optimize.minimize_scalar(sse, bounds=(1e-4, 1.0), method="bounded")
return float(np.clip(result.x, 1e-4, 1.0))
@staticmethod
def _forecast_simple(fitted: _SESResult, horizon: int) -> List[float]:
"""SES forecast: all future values equal the last level."""
return [fitted.level] * horizon
# ------------------------------------------------------------------
# Double (Holt's) exponential smoothing
# ------------------------------------------------------------------
def _fit_double(self, data: np.ndarray) -> _DESResult:
alpha = self.alpha
beta = self.beta
if alpha is None or beta is None:
alpha, beta = self._optimise_alpha_beta(data)
level, trend, residuals = self._des_smooth(data, alpha, beta)
return _DESResult(
alpha=alpha, beta=beta, level=level, trend=trend, residuals=residuals
)
@staticmethod
def _des_smooth(
data: np.ndarray, alpha: float, beta: float
) -> Tuple[float, float, List[float]]:
level = float(data[0])
trend = float(data[1]) - float(data[0])
residuals: List[float] = []
for obs in data[1:]:
fitted = level + trend
residuals.append(float(obs) - fitted)
prev_level = level
level = alpha * float(obs) + (1.0 - alpha) * (level + trend)
trend = beta * (level - prev_level) + (1.0 - beta) * trend
return level, trend, residuals
def _optimise_alpha_beta(self, data: np.ndarray) -> Tuple[float, float]:
def sse(params: np.ndarray) -> float:
a, b = float(params[0]), float(params[1])
_, _, res = self._des_smooth(data, a, b)
return sum(r ** 2 for r in res)
best_sse = math.inf
best_params = (0.3, 0.1)
for a0 in (0.1, 0.3, 0.5, 0.7):
for b0 in (0.05, 0.1, 0.3):
res = optimize.minimize(
sse,
x0=[a0, b0],
bounds=[(1e-4, 1.0), (1e-4, 1.0)],
method="L-BFGS-B",
)
if res.fun < best_sse:
best_sse = res.fun
best_params = (float(res.x[0]), float(res.x[1]))
alpha = float(np.clip(best_params[0], 1e-4, 1.0))
beta = float(np.clip(best_params[1], 1e-4, 1.0))
return alpha, beta
@staticmethod
def _forecast_double(fitted: _DESResult, horizon: int) -> List[float]:
"""Holt's forecast: level + h * trend."""
return [fitted.level + h * fitted.trend for h in range(1, horizon + 1)]
# ------------------------------------------------------------------
# Prediction intervals
# ------------------------------------------------------------------
@staticmethod
def _rmse(residuals: List[float]) -> Optional[float]:
if not residuals:
return None
return float(math.sqrt(sum(r ** 2 for r in residuals) / len(residuals)))
@staticmethod
def _prediction_intervals(
forecast: List[float],
residuals: List[float],
confidence_level: float,
) -> List[Tuple[float, float]]:
"""Compute approximate prediction intervals using residual std dev.
The interval width grows with the square root of the forecast
horizon to account for increasing uncertainty.
"""
from scipy.stats import norm # local import to keep module lean
if residuals:
std = float(np.std(residuals, ddof=1))
else:
std = 0.0
z = float(norm.ppf(0.5 + confidence_level / 2.0))
intervals: List[Tuple[float, float]] = []
for h, point in enumerate(forecast, start=1):
margin = z * std * math.sqrt(h)
intervals.append((point - margin, point + margin))
return intervals