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_modelandBaseModel. - 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+.
📦 Installation
Clone the repository and install the package from its source:
git clone https://github.com/DwaipayanDutta/forecast_hybrid.git
cd forecast_hybrid
pip install .
Optional Extras
| Extra | Command | Description |
|---|---|---|
plot |
pip install ".[plot]" |
Enables HybridResult.plot() using matplotlib |
tbats |
pip install ".[tbats]" |
Enables the tbats model (installs tbats>=1.1.0) |
autoarima |
pip install ".[autoarima]" |
Enables auto_arima model search via pmdarima |
all |
pip install ".[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
📄 License
This project is licensed under the MIT License — see the LICENSE file for details.
Metadata
Release files for forecast-hybrid 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| forecast_hybrid-0.1.1.tar.gz | 49.2 kB | Without provenance | Details for forecast_hybrid-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| forecast_hybrid-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for forecast_hybrid-0.1.1-py3-none-any.whl |
Total release size: 79.4 kB
Release files / forecast_hybrid-0.1.1.tar.gz
| Download URL | forecast_hybrid-0.1.1.tar.gz |
|---|---|
| Size | 49.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6bc24b7b786632a37bd5f510970c8f456948bf27f2cc5b1052ef0fb42ae9ed37
|
|
BLAKE2b-256 checksum How to use checksums |
2390f7e9b77da238a225eb9890f1c8aea5984c6e3011a444d08d77ed58a19a3d
|
| 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.1-py3-none-any.whl
| Download URL | forecast_hybrid-0.1.1-py3-none-any.whl |
|---|---|
| Size | 30.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6e213bb2894314f9dfb8b2290c2d2e66ab149c38423cd8cf244178fffad05932
|
|
BLAKE2b-256 checksum How to use checksums |
2cd1297d9727dc51c7d4406992b50f8aab67da89c5a4f055012e97c8c6f9702a
|
| 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.1
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.