Metadata-Version: 2.4
Name: forecast-hybrid
Version: 0.1.0
Summary: Hybrid forecasting for Python.
Author: forecast_hybrid contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/DwaipayanDutta/forecast_hybrid
Project-URL: Repository, https://github.com/DwaipayanDutta/forecast_hybrid
Project-URL: Issues, https://github.com/DwaipayanDutta/forecast_hybrid/issues
Project-URL: Documentation, https://github.com/DwaipayanDutta/forecast_hybrid#readme
Keywords: forecasting,time series,ensemble,hybrid
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.23
Requires-Dist: pandas>=1.5
Requires-Dist: scipy>=1.9
Requires-Dist: statsmodels>=0.13.5
Provides-Extra: tbats
Requires-Dist: tbats>=1.1.0; extra == "tbats"
Provides-Extra: autoarima
Requires-Dist: pmdarima>=2.0.4; extra == "autoarima"
Provides-Extra: plot
Requires-Dist: matplotlib>=3.6; extra == "plot"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5; extra == "docs"
Provides-Extra: dev
Requires-Dist: pytest>=7.4; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Dynamic: license-file

<p align="center">
  <img src="assets/forecast-hybrid-banner.png" alt="forecast_hybrid banner" width="100%" />
</p>

<p align="center">
  <a href="https://pypi.org/project/forecast-hybrid/"><img src="https://img.shields.io/pypi/v/forecast-hybrid.svg?color=blue&logo=pypi&logoColor=white" alt="PyPI version" /></a>
  <a href="https://pypi.org/project/forecast-hybrid/"><img src="https://img.shields.io/pypi/pyversions/forecast-hybrid.svg" alt="Python versions" /></a>
  <a href="https://github.com/DwaipayanDutta/forecast_hybrid/actions/workflows/ci.yml"><img src="https://github.com/DwaipayanDutta/forecast_hybrid/actions/workflows/ci.yml/badge.svg" alt="CI Status" /></a>
  <a href="https://github.com/DwaipayanDutta/forecast_hybrid/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License: MIT" /></a>
  <a href="https://github.com/astral-sh/ruff"><img src="https://img.shields.io/badge/code%20style-ruff-000000.svg" alt="Code Style: Ruff" /></a>
  <a href="https://mypy-lang.org/"><img src="https://img.shields.io/badge/types-Mypy-blue.svg" alt="Type Checked" /></a>
</p>

---

# forecast_hybrid

**Modern, principled hybrid forecasting for Python.**

In practical time-series forecasting, no individual model consistently outperforms across all horizons, seasonalities, and volatility regimes. **`forecast_hybrid`** provides a unified framework to fit complementary time-series models (classical statistical models, exponential smoothing, state space, ARIMA, and custom machine learning algorithms), automatically optimize their combination weights, and produce robust point forecasts alongside calibrated prediction intervals and statistical diagnostics.

---

## 🌟 Key Features

- **Multi-Model Ensembling**: Combine statistical models (`ets`, `arima`, `holt`, `ses`, `drift`, `seasonal_naive`, `mean`, `naive`) and ML models with optimal weights.
- **Principled Weight Optimization**: Choose from `inverse_mse`, `inverse_mae`, `equal`, Information Criterion (`ic`/AICc), Non-Negative Least Squares (`nnls`), or Rolling-Origin Cross-Validation (`cv`).
- **Uncertainty Quantification**: Calibrated 80% and 95% prediction intervals via parametric Gaussian scaling (`sqrt_h`, `linear`, `flat`) or conformal/bootstrap residual resampling.
- **Competition-Grade Metrics**: Native implementation of M5's **RMSSE** (Root Mean Squared Scaled Error), **MASE**, **SMAPE**, **MAPE**, **RMSE**, and **MAE**.
- **Diagnostic Engine**: Residual analysis with Ljung-Box autocorrelation testing (`ljung_box`) and skewness/kurtosis moments (`residual_summary`).
- **Extensible Architecture**: Register custom model backends (LightGBM, CatBoost, Prophet, PyTorch) via `register_model` and `BaseModel`.
- **Zero-Loss Serialization**: Export and load entire forecast states with component breakdown and intervals using JSON.
- **Production Ready**: Fully typed (PEP 561 `py.typed`), strictly linted with Ruff, 100% passing tests with high coverage, and compatible with Python 3.9 through 3.13+.

---

## 🏆 Kaggle M5 Competition Benchmark (+7.16% Improvement)

In the famous [Kaggle M5 Forecasting Challenge](https://www.kaggle.com/c/m5-forecasting-accuracy), the benchmark notebook [*M5 First Public Notebook Under 0.50*](https://www.kaggle.com/code/kneroma/m5-first-public-notebook-under-0-50) by **kneroma** broke the 0.50 WRMSSE barrier using LightGBM.

However, pure gradient boosted trees suffer from recursive multi-step forecast drift and disregard local retail seasonal cycles ($m=7$). By hybridizing LightGBM with `forecast_hybrid`, we evaluated on the official 28-day ground truth (`d_1914` to `d_1941` from `sales_train_evaluation.csv`) using the official competition metric **RMSSE**:

| Model | Mean RMSSE | Median RMSSE | Error Std | Result |
| :--- | :---: | :---: | :---: | :--- |
| **Seasonal Naive Benchmark** | 1.0460 | 0.9676 | 0.4793 | Baseline |
| **Kneroma LightGBM Baseline** | 0.9575 | 0.8261 | 0.5353 | Top Public Benchmark |
| **`forecast-hybrid` Ensemble** | **0.8889** | **0.7655** | **0.4441** | **+7.16% Error Reduction** |

> 📁 Check out the complete, runnable reference notebook at [`m5-first-public-notebook-under-0-50.ipynb`](m5-first-public-notebook-under-0-50.ipynb) and the Python script at [`examples/m5_forecasting.py`](examples/m5_forecasting.py).

---

## 📦 Installation

Install the core package from PyPI:

```bash
pip install forecast-hybrid
```

### Optional Extras

| Extra | Command | Description |
| :--- | :--- | :--- |
| **`plot`** | `pip install "forecast-hybrid[plot]"` | Enables `HybridResult.plot()` using `matplotlib` |
| **`tbats`** | `pip install "forecast-hybrid[tbats]"` | Enables the `tbats` model (installs `tbats>=1.1.0`) |
| **`autoarima`** | `pip install "forecast-hybrid[autoarima]"` | Enables `auto_arima` model search via `pmdarima` |
| **`all`** | `pip install "forecast-hybrid[tbats,autoarima,plot]"` | All optional modeling and plotting dependencies |
| **`dev`** | `pip install -e ".[dev,docs]"` | Development dependencies (`pytest`, `ruff`, `mypy`, `mkdocs`, `twine`) |

---

## 🚀 Quickstart

Generate a hybrid forecast in just 3 lines of code:

```python
import numpy as np
import pandas as pd
from forecast_hybrid import hybrid_forecast

# 1. Create a sample monthly time-series
dates = pd.date_range("2020-01-01", periods=48, freq="MS")
y = pd.Series(
    20 + 0.5 * np.arange(48) + 3 * np.sin(2 * np.pi * np.arange(48) / 12),
    index=dates,
    name="MonthlySales",
)

# 2. Fit hybrid ensemble of ETS, ARIMA, and Drift with weekly/monthly seasonality
result = hybrid_forecast(
    y,
    h=12,
    m=12,
    models=["ets", "arima", "drift"],
    weights="inverse_mse",
    level=(80, 95),
)

# 3. Inspect combined forecasts, component weights, and confidence bands
print(result.summary())
print(result.weights)       # e.g., {'ets': 0.45, 'arima': 0.38, 'drift': 0.17}
print(result.to_frame())    # DataFrame with columns: mean, lower_80, upper_80, lower_95, upper_95
```

---

## 🧠 Supported Component Models

Check available models at runtime with `forecast_hybrid.available_models()`:

| Model ID | Class Name | Description | Key Options / Hyperparameters |
| :--- | :--- | :--- | :--- |
| `naive` | `NaiveModel` | Random walk benchmark | None |
| `seasonal_naive` | `SeasonalNaiveModel` | Seasonal random walk | `m` (seasonal period, e.g. 7, 12, 365) |
| `mean` | `MeanModel` | Historical cumulative mean | None |
| `drift` | `DriftModel` | Random walk with linear drift | None |
| `ses` | `SESModel` | Simple Exponential Smoothing | `initialization_method="estimated"` |
| `holt` | `HoltModel` | Holt Linear Trend | `damped_trend=True` / `False` |
| `ets` | `ETSModel` | Automated Exponential Smoothing | `trend`, `seasonal`, `damped_trend` |
| `arima` | `ARIMAModel` | ARIMA with AICc grid search | `order=(p,d,q)`, `seasonal_order=(P,D,Q,m)`, `max_p`, `max_q` |
| `auto_arima` | `AutoARIMAModel` | Automated Box-Jenkins search | Requires `pmdarima` (`[autoarima]` extra) |
| `tbats` | `TBATSModel` | Trigonometric Box-Cox ARMA Trend Seasonality | Requires `tbats` (`[tbats]` extra) |

---

## ⚖️ Ensembling & Weighting Schemes

`forecast_hybrid` supports 6 built-in weighting strategies:

```python
from forecast_hybrid import HybridForecaster

# Example: Non-negative least squares ensembling
forecaster = HybridForecaster(
    models=["seasonal_naive", "ets", "arima", "drift"],
    weights="nnls",
    m=7,
)
forecaster.fit(y)
```

| Scheme | Description | Mathematical Formulation |
| :--- | :--- | :--- |
| **`inverse_mse`** *(default)* | Proportional to inverse in-sample Mean Squared Error | $w_i \propto \left(\frac{1}{\text{MSE}_i}\right)^p$ |
| **`inverse_mae`** | Proportional to inverse in-sample Mean Absolute Error | $w_i \propto \left(\frac{1}{\text{MAE}_i}\right)^p$ |
| **`equal`** | Simple arithmetic mean across all components | $w_i = \frac{1}{K}$ |
| **`ic`** | Akaike Information Criterion (AICc) weights | $w_i \propto \exp\left(-\frac{\Delta_i}{2}\right)$ |
| **`nnls`** | Non-Negative Least Squares constrained regression | $\min_{w \ge 0} \|y - \sum w_i \hat{y}_i\|_2^2$ |
| **`cv`** | Rolling-origin cross-validation RMSE weights | Uses out-of-fold rolling errors |
| **Callable** | Custom user-defined weighting function | `lambda fitted_matrix: [w1, w2, ...]` |

---

## 📈 Prediction Intervals

Compute calibrated uncertainty bands via parametric Gaussian distributions or non-parametric bootstrap resampling:

```python
# Conformal bootstrap prediction intervals
f = HybridForecaster(
    models=["naive", "drift", "ses"],
    interval_method="bootstrap",  # 'normal' or 'bootstrap'
    n_bootstrap=500,
    random_state=42,
    level=(80, 95),
).fit(y)

res = f.forecast(h=6)
# res.lower[95.0], res.upper[95.0]
```

- **`"normal"`**: $\hat{y}_h \pm z_{1-\alpha/2} \cdot \hat{\sigma} \cdot g(h)$, where horizon scaling $g(h)$ is `"sqrt_h"`, `"linear"`, or `"flat"`.
- **`"bootstrap"`**: Resamples centered residual paths, generating empirical percentile boundaries.

---

## 🧪 Metrics & Diagnostics

### Competition & Accuracy Metrics

```python
from forecast_hybrid import accuracy, mae, mape, mase, rmse, rmsse, smape

# Single metrics
err_rmsse = rmsse(actual, forecast, y_train, m=7)
err_mase = mase(actual, forecast, y_train, m=7)
err_smape = smape(actual, forecast)

# Full accuracy summary table
summary = accuracy(actual, forecast, yt=y_train, m=7)
# Returns pd.Series with: me, rmse, mae, mpe, mape, smape, mase, rmsse, acf1
```

### Statistical Residual Diagnostics

```python
from forecast_hybrid import ljung_box, residual_summary

# 1. Summary moments of residuals
stats = residual_summary(forecaster.residuals)
# {'n': 48, 'mean': 0.002, 'std': 1.14, 'min': -2.1, 'max': 2.4, 'skew': 0.08, 'kurtosis': 0.12, 'acf1': 0.05}

# 2. Ljung-Box test for residual white noise (absence of serial autocorrelation)
lb_test = ljung_box(forecaster.residuals, lags=5)
print(lb_test)  # lb_stat, lb_pvalue
```

---

## 💾 Serialization & Production Serving

Serialize and deserialize fitted forecasts to and from JSON without precision loss:

```python
from forecast_hybrid import load_result, result_from_json, save_result

# Export to JSON string or file
json_str = result.to_json(indent=2)
save_result(result, "forecast_2026.json")

# Restore full object
restored_result = load_result("forecast_2026.json")
assert np.allclose(restored_result.mean, result.mean)
```

---

## 🔌 Custom Model Registration

Extend `forecast_hybrid` with your own machine learning or deep learning forecaster:

```python
from forecast_hybrid import HybridForecaster, register_model
from forecast_hybrid.models import BaseModel
import numpy as np

class CustomDecayModel(BaseModel):
    name = "decay"

    def _fit(self, y):
        self._fitted_values = np.full(y.size, y.mean())
        self._last_val = y[-1]

    def _predict(self, h):
        decay = np.exp(-0.1 * np.arange(1, h + 1))
        return self._last_val * decay

# Register into the hybrid catalog
register_model("decay", CustomDecayModel, description="Exponential decay forecaster")

# Use directly in any HybridForecaster
f = HybridForecaster(models=["decay", "seasonal_naive", "ets"]).fit(y)
```

---

## 👩‍💻 Development & Testing

Run the full automated test suite and lint checks:

```bash
# Clone the repository
git clone https://github.com/DwaipayanDutta/forecast_hybrid.git
cd forecast_hybrid

# Install in editable mode with development tools
pip install -e ".[dev,docs]"

# Run tests with coverage
pytest --cov=forecast_hybrid --cov-report=term-missing

# Run code style & formatting checks
ruff check .
ruff format --check .

# Run static type checking
mypy forecast_hybrid

# Build local documentation
mkdocs build --strict
```

---

## 🚀 Publishing to PyPI

To build and publish release distributions to PyPI:

```bash
# 1. Build source distribution and wheel
python -m build

# 2. Verify archive integrity
twine check dist/*

# 3. (Recommended) Test publish to TestPyPI
twine upload --repository testpypi dist/*

# 4. Publish to production PyPI
twine upload dist/*
```

---

## 📄 License

This project is licensed under the **MIT License** — see the [LICENSE](LICENSE) file for details.
