Skip to main content

forecast_hybrid banner

PyPI version Python versions CI Status License: MIT Code Style: Ruff Type Checked


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, the benchmark notebook 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 and the Python script at examples/m5_forecasting.py.


📦 Installation

Install the core package from PyPI:

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:

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:

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:

# 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

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

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:

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:

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:

# 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:

# 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 file for details.

Metadata

Release files for forecast-hybrid 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for forecast-hybrid 0.1.0
File Size Uploaded Provenance Actions
forecast_hybrid-0.1.0.tar.gz 50.7 kB Without provenance Details for forecast_hybrid-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for forecast-hybrid 0.1.0
File Interpreter ABI Platform Actions
forecast_hybrid-0.1.0-py3-none-any.whl Python 3 none any Details for forecast_hybrid-0.1.0-py3-none-any.whl

Total release size: 81.8 kB

Release files / forecast_hybrid-0.1.0.tar.gz

Download URL forecast_hybrid-0.1.0.tar.gz
Size 50.7 kB
Tags Source
SHA-256 checksum
How to use checksums
6652389c38de38bc162eb0eb567b6c17f47ab78d7ceb2e8d8b64ba65ecdf3159
BLAKE2b-256 checksum
How to use checksums
4d72e3517736ad320a04ff037ac0163e7288482eee6b41200b74162df9702df6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release files / forecast_hybrid-0.1.0-py3-none-any.whl

Download URL forecast_hybrid-0.1.0-py3-none-any.whl
Size 31.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4a30181a5e4911e4a34ed66fc0611d34f89db2f4459a8d31d08a4b4d49306fcd
BLAKE2b-256 checksum
How to use checksums
bd3d434c5820d8f7f1aee2eb7ab59130e65144906a6c63b58b10d1d4bdc3ab1f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Security for forecast-hybrid 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page