forecast-hybrid 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forecast_hybrid-0.1.0/CHANGELOG.md +39 -0
- forecast_hybrid-0.1.0/CONTRIBUTING.md +41 -0
- forecast_hybrid-0.1.0/LICENSE +21 -0
- forecast_hybrid-0.1.0/MANIFEST.in +25 -0
- forecast_hybrid-0.1.0/PKG-INFO +354 -0
- forecast_hybrid-0.1.0/README.md +308 -0
- forecast_hybrid-0.1.0/docs/cross_validation.md +17 -0
- forecast_hybrid-0.1.0/docs/diagnostics.md +15 -0
- forecast_hybrid-0.1.0/docs/index.md +23 -0
- forecast_hybrid-0.1.0/docs/intervals.md +20 -0
- forecast_hybrid-0.1.0/docs/limitations.md +9 -0
- forecast_hybrid-0.1.0/docs/models.md +55 -0
- forecast_hybrid-0.1.0/docs/quickstart.md +42 -0
- forecast_hybrid-0.1.0/docs/serialization.md +15 -0
- forecast_hybrid-0.1.0/docs/weights.md +23 -0
- forecast_hybrid-0.1.0/examples/basic_usage.py +40 -0
- forecast_hybrid-0.1.0/examples/cross_validation_example.py +28 -0
- forecast_hybrid-0.1.0/examples/m5_forecasting.py +118 -0
- forecast_hybrid-0.1.0/examples/model_comparison.py +37 -0
- forecast_hybrid-0.1.0/forecast_hybrid/__init__.py +48 -0
- forecast_hybrid-0.1.0/forecast_hybrid/_version.py +1 -0
- forecast_hybrid-0.1.0/forecast_hybrid/api.py +46 -0
- forecast_hybrid-0.1.0/forecast_hybrid/cross_validation.py +61 -0
- forecast_hybrid-0.1.0/forecast_hybrid/diagnostics.py +47 -0
- forecast_hybrid-0.1.0/forecast_hybrid/exceptions.py +18 -0
- forecast_hybrid-0.1.0/forecast_hybrid/hybrid.py +289 -0
- forecast_hybrid-0.1.0/forecast_hybrid/indexing.py +55 -0
- forecast_hybrid-0.1.0/forecast_hybrid/intervals.py +94 -0
- forecast_hybrid-0.1.0/forecast_hybrid/metrics.py +101 -0
- forecast_hybrid-0.1.0/forecast_hybrid/models/__init__.py +19 -0
- forecast_hybrid-0.1.0/forecast_hybrid/models/_util.py +14 -0
- forecast_hybrid-0.1.0/forecast_hybrid/models/arima.py +105 -0
- forecast_hybrid-0.1.0/forecast_hybrid/models/base.py +107 -0
- forecast_hybrid-0.1.0/forecast_hybrid/models/exponential.py +151 -0
- forecast_hybrid-0.1.0/forecast_hybrid/models/naive.py +72 -0
- forecast_hybrid-0.1.0/forecast_hybrid/models/optional.py +75 -0
- forecast_hybrid-0.1.0/forecast_hybrid/plotting.py +91 -0
- forecast_hybrid-0.1.0/forecast_hybrid/py.typed +0 -0
- forecast_hybrid-0.1.0/forecast_hybrid/registry.py +96 -0
- forecast_hybrid-0.1.0/forecast_hybrid/result.py +72 -0
- forecast_hybrid-0.1.0/forecast_hybrid/serialization.py +115 -0
- forecast_hybrid-0.1.0/forecast_hybrid/utils.py +72 -0
- forecast_hybrid-0.1.0/forecast_hybrid/validation.py +60 -0
- forecast_hybrid-0.1.0/forecast_hybrid/weights.py +62 -0
- forecast_hybrid-0.1.0/forecast_hybrid.egg-info/PKG-INFO +354 -0
- forecast_hybrid-0.1.0/forecast_hybrid.egg-info/SOURCES.txt +67 -0
- forecast_hybrid-0.1.0/forecast_hybrid.egg-info/dependency_links.txt +1 -0
- forecast_hybrid-0.1.0/forecast_hybrid.egg-info/requires.txt +24 -0
- forecast_hybrid-0.1.0/forecast_hybrid.egg-info/top_level.txt +1 -0
- forecast_hybrid-0.1.0/mkdocs.yml +13 -0
- forecast_hybrid-0.1.0/pyproject.toml +75 -0
- forecast_hybrid-0.1.0/setup.cfg +4 -0
- forecast_hybrid-0.1.0/tests/conftest.py +37 -0
- forecast_hybrid-0.1.0/tests/test_cross_validation.py +98 -0
- forecast_hybrid-0.1.0/tests/test_diagnostics.py +72 -0
- forecast_hybrid-0.1.0/tests/test_hybrid.py +211 -0
- forecast_hybrid-0.1.0/tests/test_indexing.py +58 -0
- forecast_hybrid-0.1.0/tests/test_intervals.py +117 -0
- forecast_hybrid-0.1.0/tests/test_metrics.py +89 -0
- forecast_hybrid-0.1.0/tests/test_models.py +142 -0
- forecast_hybrid-0.1.0/tests/test_optional_models.py +64 -0
- forecast_hybrid-0.1.0/tests/test_registry.py +110 -0
- forecast_hybrid-0.1.0/tests/test_serialization.py +123 -0
- forecast_hybrid-0.1.0/tests/test_smoke.py +56 -0
- forecast_hybrid-0.1.0/tests/test_validation.py +64 -0
- forecast_hybrid-0.1.0/tests/test_version.py +22 -0
- forecast_hybrid-0.1.0/tests/test_weights.py +86 -0
- forecast_hybrid-0.1.0/tools/make_zip.py +147 -0
- forecast_hybrid-0.1.0/tools/smoke_test.py +61 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [0.1.0]
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- `HybridForecaster` and the `hybrid_forecast` convenience function: fit several component
|
|
11
|
+
models to a univariate series and combine their forecasts with a weighted average.
|
|
12
|
+
- Built-in models: `naive`, `seasonal_naive`, `mean`, `drift`, `ses`, `holt`, `ets`, `arima`.
|
|
13
|
+
- Optional models: `auto_arima` (needs `pmdarima`, extra `autoarima`) and `tbats`
|
|
14
|
+
(needs `tbats`, extra `tbats`), imported lazily with a `ModelNotAvailableError` install hint.
|
|
15
|
+
- Model registry: `available_models`, `models_table`, `register_model`.
|
|
16
|
+
- Weight schemes: `equal`, `inverse_mse` (default), `inverse_mae`, `ic`, `nnls`, `cv`, and
|
|
17
|
+
user-supplied callables.
|
|
18
|
+
- Prediction intervals: `normal` (with `sqrt_h`, `flat`, `linear` horizon scaling) and
|
|
19
|
+
`bootstrap` methods at configurable levels.
|
|
20
|
+
- Rolling-origin cross-validation: `rolling_origin_splits`, `cross_validate`, `model_cv_errors`.
|
|
21
|
+
- Metrics: `mae`, `mse`, `rmse`, `bias`, `mpe`, `mape`, `smape`, `mase`, `rmsse`, `accuracy`.
|
|
22
|
+
- Diagnostics: `residual_summary`, `ljung_box`, `accuracy_table`.
|
|
23
|
+
- `HybridResult` with `to_frame`, `summary`, `to_dict`, `to_json` and `plot`.
|
|
24
|
+
- JSON serialization: `result_to_json`, `result_from_json`, `save_result`, `load_result`
|
|
25
|
+
(schema version 1).
|
|
26
|
+
- Plotting helpers (require the optional `plot` extra).
|
|
27
|
+
- `forecast_hybrid.utils` helper module.
|
|
28
|
+
- Test suite, documentation (MkDocs), examples, and packaging/CI tooling.
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
- `cross_validate` passed an unsupported keyword to `accuracy` and always failed.
|
|
32
|
+
- Optional-dependency errors raised inside a model were re-wrapped as `FitError`; they now
|
|
33
|
+
propagate as `ModelNotAvailableError`.
|
|
34
|
+
- Serializing a result whose prediction intervals were `NaN` raised; non-finite interval values
|
|
35
|
+
are now stored as `null`.
|
|
36
|
+
- Deserialized `lower`/`upper` frames now have numeric (float) level columns so `to_frame`
|
|
37
|
+
works after a round trip.
|
|
38
|
+
- `future_index` computed the wrong step for irregular `DatetimeIndex` values with pandas 3
|
|
39
|
+
(non-nanosecond resolution).
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
## Development setup
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
python -m venv .venv
|
|
7
|
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
|
8
|
+
pip install -e ".[dev,docs]"
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Optional model dependencies are separate extras (`.[tbats]`, `.[autoarima]`, `.[plot]`).
|
|
12
|
+
|
|
13
|
+
## Validation commands
|
|
14
|
+
|
|
15
|
+
Run these before opening a pull request:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
ruff check .
|
|
19
|
+
ruff format --check .
|
|
20
|
+
mypy forecast_hybrid
|
|
21
|
+
pytest --cov=forecast_hybrid --cov-report=term-missing
|
|
22
|
+
mkdocs build --strict
|
|
23
|
+
python -m build
|
|
24
|
+
python -m twine check dist/*
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`ruff check --fix . && ruff format .` applies automatic fixes.
|
|
28
|
+
|
|
29
|
+
## Guidelines
|
|
30
|
+
|
|
31
|
+
- Keep optional dependencies optional. Never import `tbats`, `pmdarima` or `matplotlib` at
|
|
32
|
+
module import time; import inside the function that needs them and raise
|
|
33
|
+
`ModelNotAvailableError` with an install hint.
|
|
34
|
+
- Add tests for every behavior change. Tests for optional models must skip when the package is
|
|
35
|
+
not installed.
|
|
36
|
+
- Use an explicit `order=` for `ARIMAModel` in tests so they are fast and deterministic.
|
|
37
|
+
- Seed random number generators in tests and examples.
|
|
38
|
+
- Keep `forecast_hybrid.__all__` backwards compatible: only add names.
|
|
39
|
+
- Update `CHANGELOG.md` and the relevant page in `docs/` for user-visible changes.
|
|
40
|
+
- The URLs in `pyproject.toml` are placeholders (`example.invalid`); do not replace them with
|
|
41
|
+
guesses.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dwaipayan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
include LICENSE
|
|
2
|
+
include README.md
|
|
3
|
+
include CHANGELOG.md
|
|
4
|
+
include CONTRIBUTING.md
|
|
5
|
+
include pyproject.toml
|
|
6
|
+
include mkdocs.yml
|
|
7
|
+
recursive-include forecast_hybrid *.py py.typed
|
|
8
|
+
recursive-include tests *.py
|
|
9
|
+
recursive-include examples *.py
|
|
10
|
+
recursive-include docs *.md
|
|
11
|
+
recursive-include tools *.py
|
|
12
|
+
recursive-exclude * __pycache__
|
|
13
|
+
recursive-exclude * *.py[cod]
|
|
14
|
+
recursive-exclude * .DS_Store
|
|
15
|
+
prune build
|
|
16
|
+
prune dist
|
|
17
|
+
prune .venv
|
|
18
|
+
prune .venv-dev
|
|
19
|
+
prune .pytest_cache
|
|
20
|
+
prune .mypy_cache
|
|
21
|
+
prune .ruff_cache
|
|
22
|
+
prune site
|
|
23
|
+
prune .github
|
|
24
|
+
prune Data
|
|
25
|
+
prune data
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: forecast-hybrid
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hybrid forecasting for Python.
|
|
5
|
+
Author: forecast_hybrid contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/DwaipayanDutta/forecast_hybrid
|
|
8
|
+
Project-URL: Repository, https://github.com/DwaipayanDutta/forecast_hybrid
|
|
9
|
+
Project-URL: Issues, https://github.com/DwaipayanDutta/forecast_hybrid/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/DwaipayanDutta/forecast_hybrid#readme
|
|
11
|
+
Keywords: forecasting,time series,ensemble,hybrid
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: numpy>=1.23
|
|
27
|
+
Requires-Dist: pandas>=1.5
|
|
28
|
+
Requires-Dist: scipy>=1.9
|
|
29
|
+
Requires-Dist: statsmodels>=0.13.5
|
|
30
|
+
Provides-Extra: tbats
|
|
31
|
+
Requires-Dist: tbats>=1.1.0; extra == "tbats"
|
|
32
|
+
Provides-Extra: autoarima
|
|
33
|
+
Requires-Dist: pmdarima>=2.0.4; extra == "autoarima"
|
|
34
|
+
Provides-Extra: plot
|
|
35
|
+
Requires-Dist: matplotlib>=3.6; extra == "plot"
|
|
36
|
+
Provides-Extra: docs
|
|
37
|
+
Requires-Dist: mkdocs>=1.5; extra == "docs"
|
|
38
|
+
Provides-Extra: dev
|
|
39
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
40
|
+
Requires-Dist: pytest-cov>=4.1; extra == "dev"
|
|
41
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
42
|
+
Requires-Dist: mypy>=1.8; extra == "dev"
|
|
43
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
44
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
45
|
+
Dynamic: license-file
|
|
46
|
+
|
|
47
|
+
<p align="center">
|
|
48
|
+
<img src="assets/forecast-hybrid-banner.png" alt="forecast_hybrid banner" width="100%" />
|
|
49
|
+
</p>
|
|
50
|
+
|
|
51
|
+
<p align="center">
|
|
52
|
+
<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>
|
|
53
|
+
<a href="https://pypi.org/project/forecast-hybrid/"><img src="https://img.shields.io/pypi/pyversions/forecast-hybrid.svg" alt="Python versions" /></a>
|
|
54
|
+
<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>
|
|
55
|
+
<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>
|
|
56
|
+
<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>
|
|
57
|
+
<a href="https://mypy-lang.org/"><img src="https://img.shields.io/badge/types-Mypy-blue.svg" alt="Type Checked" /></a>
|
|
58
|
+
</p>
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
# forecast_hybrid
|
|
63
|
+
|
|
64
|
+
**Modern, principled hybrid forecasting for Python.**
|
|
65
|
+
|
|
66
|
+
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.
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## ๐ Key Features
|
|
71
|
+
|
|
72
|
+
- **Multi-Model Ensembling**: Combine statistical models (`ets`, `arima`, `holt`, `ses`, `drift`, `seasonal_naive`, `mean`, `naive`) and ML models with optimal weights.
|
|
73
|
+
- **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`).
|
|
74
|
+
- **Uncertainty Quantification**: Calibrated 80% and 95% prediction intervals via parametric Gaussian scaling (`sqrt_h`, `linear`, `flat`) or conformal/bootstrap residual resampling.
|
|
75
|
+
- **Competition-Grade Metrics**: Native implementation of M5's **RMSSE** (Root Mean Squared Scaled Error), **MASE**, **SMAPE**, **MAPE**, **RMSE**, and **MAE**.
|
|
76
|
+
- **Diagnostic Engine**: Residual analysis with Ljung-Box autocorrelation testing (`ljung_box`) and skewness/kurtosis moments (`residual_summary`).
|
|
77
|
+
- **Extensible Architecture**: Register custom model backends (LightGBM, CatBoost, Prophet, PyTorch) via `register_model` and `BaseModel`.
|
|
78
|
+
- **Zero-Loss Serialization**: Export and load entire forecast states with component breakdown and intervals using JSON.
|
|
79
|
+
- **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+.
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## ๐ Kaggle M5 Competition Benchmark (+7.16% Improvement)
|
|
84
|
+
|
|
85
|
+
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.
|
|
86
|
+
|
|
87
|
+
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**:
|
|
88
|
+
|
|
89
|
+
| Model | Mean RMSSE | Median RMSSE | Error Std | Result |
|
|
90
|
+
| :--- | :---: | :---: | :---: | :--- |
|
|
91
|
+
| **Seasonal Naive Benchmark** | 1.0460 | 0.9676 | 0.4793 | Baseline |
|
|
92
|
+
| **Kneroma LightGBM Baseline** | 0.9575 | 0.8261 | 0.5353 | Top Public Benchmark |
|
|
93
|
+
| **`forecast-hybrid` Ensemble** | **0.8889** | **0.7655** | **0.4441** | **+7.16% Error Reduction** |
|
|
94
|
+
|
|
95
|
+
> ๐ 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).
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## ๐ฆ Installation
|
|
100
|
+
|
|
101
|
+
Install the core package from PyPI:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
pip install forecast-hybrid
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Optional Extras
|
|
108
|
+
|
|
109
|
+
| Extra | Command | Description |
|
|
110
|
+
| :--- | :--- | :--- |
|
|
111
|
+
| **`plot`** | `pip install "forecast-hybrid[plot]"` | Enables `HybridResult.plot()` using `matplotlib` |
|
|
112
|
+
| **`tbats`** | `pip install "forecast-hybrid[tbats]"` | Enables the `tbats` model (installs `tbats>=1.1.0`) |
|
|
113
|
+
| **`autoarima`** | `pip install "forecast-hybrid[autoarima]"` | Enables `auto_arima` model search via `pmdarima` |
|
|
114
|
+
| **`all`** | `pip install "forecast-hybrid[tbats,autoarima,plot]"` | All optional modeling and plotting dependencies |
|
|
115
|
+
| **`dev`** | `pip install -e ".[dev,docs]"` | Development dependencies (`pytest`, `ruff`, `mypy`, `mkdocs`, `twine`) |
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## ๐ Quickstart
|
|
120
|
+
|
|
121
|
+
Generate a hybrid forecast in just 3 lines of code:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
import numpy as np
|
|
125
|
+
import pandas as pd
|
|
126
|
+
from forecast_hybrid import hybrid_forecast
|
|
127
|
+
|
|
128
|
+
# 1. Create a sample monthly time-series
|
|
129
|
+
dates = pd.date_range("2020-01-01", periods=48, freq="MS")
|
|
130
|
+
y = pd.Series(
|
|
131
|
+
20 + 0.5 * np.arange(48) + 3 * np.sin(2 * np.pi * np.arange(48) / 12),
|
|
132
|
+
index=dates,
|
|
133
|
+
name="MonthlySales",
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
# 2. Fit hybrid ensemble of ETS, ARIMA, and Drift with weekly/monthly seasonality
|
|
137
|
+
result = hybrid_forecast(
|
|
138
|
+
y,
|
|
139
|
+
h=12,
|
|
140
|
+
m=12,
|
|
141
|
+
models=["ets", "arima", "drift"],
|
|
142
|
+
weights="inverse_mse",
|
|
143
|
+
level=(80, 95),
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
# 3. Inspect combined forecasts, component weights, and confidence bands
|
|
147
|
+
print(result.summary())
|
|
148
|
+
print(result.weights) # e.g., {'ets': 0.45, 'arima': 0.38, 'drift': 0.17}
|
|
149
|
+
print(result.to_frame()) # DataFrame with columns: mean, lower_80, upper_80, lower_95, upper_95
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## ๐ง Supported Component Models
|
|
155
|
+
|
|
156
|
+
Check available models at runtime with `forecast_hybrid.available_models()`:
|
|
157
|
+
|
|
158
|
+
| Model ID | Class Name | Description | Key Options / Hyperparameters |
|
|
159
|
+
| :--- | :--- | :--- | :--- |
|
|
160
|
+
| `naive` | `NaiveModel` | Random walk benchmark | None |
|
|
161
|
+
| `seasonal_naive` | `SeasonalNaiveModel` | Seasonal random walk | `m` (seasonal period, e.g. 7, 12, 365) |
|
|
162
|
+
| `mean` | `MeanModel` | Historical cumulative mean | None |
|
|
163
|
+
| `drift` | `DriftModel` | Random walk with linear drift | None |
|
|
164
|
+
| `ses` | `SESModel` | Simple Exponential Smoothing | `initialization_method="estimated"` |
|
|
165
|
+
| `holt` | `HoltModel` | Holt Linear Trend | `damped_trend=True` / `False` |
|
|
166
|
+
| `ets` | `ETSModel` | Automated Exponential Smoothing | `trend`, `seasonal`, `damped_trend` |
|
|
167
|
+
| `arima` | `ARIMAModel` | ARIMA with AICc grid search | `order=(p,d,q)`, `seasonal_order=(P,D,Q,m)`, `max_p`, `max_q` |
|
|
168
|
+
| `auto_arima` | `AutoARIMAModel` | Automated Box-Jenkins search | Requires `pmdarima` (`[autoarima]` extra) |
|
|
169
|
+
| `tbats` | `TBATSModel` | Trigonometric Box-Cox ARMA Trend Seasonality | Requires `tbats` (`[tbats]` extra) |
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
## โ๏ธ Ensembling & Weighting Schemes
|
|
174
|
+
|
|
175
|
+
`forecast_hybrid` supports 6 built-in weighting strategies:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from forecast_hybrid import HybridForecaster
|
|
179
|
+
|
|
180
|
+
# Example: Non-negative least squares ensembling
|
|
181
|
+
forecaster = HybridForecaster(
|
|
182
|
+
models=["seasonal_naive", "ets", "arima", "drift"],
|
|
183
|
+
weights="nnls",
|
|
184
|
+
m=7,
|
|
185
|
+
)
|
|
186
|
+
forecaster.fit(y)
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
| Scheme | Description | Mathematical Formulation |
|
|
190
|
+
| :--- | :--- | :--- |
|
|
191
|
+
| **`inverse_mse`** *(default)* | Proportional to inverse in-sample Mean Squared Error | $w_i \propto \left(\frac{1}{\text{MSE}_i}\right)^p$ |
|
|
192
|
+
| **`inverse_mae`** | Proportional to inverse in-sample Mean Absolute Error | $w_i \propto \left(\frac{1}{\text{MAE}_i}\right)^p$ |
|
|
193
|
+
| **`equal`** | Simple arithmetic mean across all components | $w_i = \frac{1}{K}$ |
|
|
194
|
+
| **`ic`** | Akaike Information Criterion (AICc) weights | $w_i \propto \exp\left(-\frac{\Delta_i}{2}\right)$ |
|
|
195
|
+
| **`nnls`** | Non-Negative Least Squares constrained regression | $\min_{w \ge 0} \|y - \sum w_i \hat{y}_i\|_2^2$ |
|
|
196
|
+
| **`cv`** | Rolling-origin cross-validation RMSE weights | Uses out-of-fold rolling errors |
|
|
197
|
+
| **Callable** | Custom user-defined weighting function | `lambda fitted_matrix: [w1, w2, ...]` |
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## ๐ Prediction Intervals
|
|
202
|
+
|
|
203
|
+
Compute calibrated uncertainty bands via parametric Gaussian distributions or non-parametric bootstrap resampling:
|
|
204
|
+
|
|
205
|
+
```python
|
|
206
|
+
# Conformal bootstrap prediction intervals
|
|
207
|
+
f = HybridForecaster(
|
|
208
|
+
models=["naive", "drift", "ses"],
|
|
209
|
+
interval_method="bootstrap", # 'normal' or 'bootstrap'
|
|
210
|
+
n_bootstrap=500,
|
|
211
|
+
random_state=42,
|
|
212
|
+
level=(80, 95),
|
|
213
|
+
).fit(y)
|
|
214
|
+
|
|
215
|
+
res = f.forecast(h=6)
|
|
216
|
+
# res.lower[95.0], res.upper[95.0]
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
- **`"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"`.
|
|
220
|
+
- **`"bootstrap"`**: Resamples centered residual paths, generating empirical percentile boundaries.
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## ๐งช Metrics & Diagnostics
|
|
225
|
+
|
|
226
|
+
### Competition & Accuracy Metrics
|
|
227
|
+
|
|
228
|
+
```python
|
|
229
|
+
from forecast_hybrid import accuracy, mae, mape, mase, rmse, rmsse, smape
|
|
230
|
+
|
|
231
|
+
# Single metrics
|
|
232
|
+
err_rmsse = rmsse(actual, forecast, y_train, m=7)
|
|
233
|
+
err_mase = mase(actual, forecast, y_train, m=7)
|
|
234
|
+
err_smape = smape(actual, forecast)
|
|
235
|
+
|
|
236
|
+
# Full accuracy summary table
|
|
237
|
+
summary = accuracy(actual, forecast, yt=y_train, m=7)
|
|
238
|
+
# Returns pd.Series with: me, rmse, mae, mpe, mape, smape, mase, rmsse, acf1
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
### Statistical Residual Diagnostics
|
|
242
|
+
|
|
243
|
+
```python
|
|
244
|
+
from forecast_hybrid import ljung_box, residual_summary
|
|
245
|
+
|
|
246
|
+
# 1. Summary moments of residuals
|
|
247
|
+
stats = residual_summary(forecaster.residuals)
|
|
248
|
+
# {'n': 48, 'mean': 0.002, 'std': 1.14, 'min': -2.1, 'max': 2.4, 'skew': 0.08, 'kurtosis': 0.12, 'acf1': 0.05}
|
|
249
|
+
|
|
250
|
+
# 2. Ljung-Box test for residual white noise (absence of serial autocorrelation)
|
|
251
|
+
lb_test = ljung_box(forecaster.residuals, lags=5)
|
|
252
|
+
print(lb_test) # lb_stat, lb_pvalue
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## ๐พ Serialization & Production Serving
|
|
258
|
+
|
|
259
|
+
Serialize and deserialize fitted forecasts to and from JSON without precision loss:
|
|
260
|
+
|
|
261
|
+
```python
|
|
262
|
+
from forecast_hybrid import load_result, result_from_json, save_result
|
|
263
|
+
|
|
264
|
+
# Export to JSON string or file
|
|
265
|
+
json_str = result.to_json(indent=2)
|
|
266
|
+
save_result(result, "forecast_2026.json")
|
|
267
|
+
|
|
268
|
+
# Restore full object
|
|
269
|
+
restored_result = load_result("forecast_2026.json")
|
|
270
|
+
assert np.allclose(restored_result.mean, result.mean)
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
## ๐ Custom Model Registration
|
|
276
|
+
|
|
277
|
+
Extend `forecast_hybrid` with your own machine learning or deep learning forecaster:
|
|
278
|
+
|
|
279
|
+
```python
|
|
280
|
+
from forecast_hybrid import HybridForecaster, register_model
|
|
281
|
+
from forecast_hybrid.models import BaseModel
|
|
282
|
+
import numpy as np
|
|
283
|
+
|
|
284
|
+
class CustomDecayModel(BaseModel):
|
|
285
|
+
name = "decay"
|
|
286
|
+
|
|
287
|
+
def _fit(self, y):
|
|
288
|
+
self._fitted_values = np.full(y.size, y.mean())
|
|
289
|
+
self._last_val = y[-1]
|
|
290
|
+
|
|
291
|
+
def _predict(self, h):
|
|
292
|
+
decay = np.exp(-0.1 * np.arange(1, h + 1))
|
|
293
|
+
return self._last_val * decay
|
|
294
|
+
|
|
295
|
+
# Register into the hybrid catalog
|
|
296
|
+
register_model("decay", CustomDecayModel, description="Exponential decay forecaster")
|
|
297
|
+
|
|
298
|
+
# Use directly in any HybridForecaster
|
|
299
|
+
f = HybridForecaster(models=["decay", "seasonal_naive", "ets"]).fit(y)
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
304
|
+
## ๐ฉโ๐ป Development & Testing
|
|
305
|
+
|
|
306
|
+
Run the full automated test suite and lint checks:
|
|
307
|
+
|
|
308
|
+
```bash
|
|
309
|
+
# Clone the repository
|
|
310
|
+
git clone https://github.com/DwaipayanDutta/forecast_hybrid.git
|
|
311
|
+
cd forecast_hybrid
|
|
312
|
+
|
|
313
|
+
# Install in editable mode with development tools
|
|
314
|
+
pip install -e ".[dev,docs]"
|
|
315
|
+
|
|
316
|
+
# Run tests with coverage
|
|
317
|
+
pytest --cov=forecast_hybrid --cov-report=term-missing
|
|
318
|
+
|
|
319
|
+
# Run code style & formatting checks
|
|
320
|
+
ruff check .
|
|
321
|
+
ruff format --check .
|
|
322
|
+
|
|
323
|
+
# Run static type checking
|
|
324
|
+
mypy forecast_hybrid
|
|
325
|
+
|
|
326
|
+
# Build local documentation
|
|
327
|
+
mkdocs build --strict
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
## ๐ Publishing to PyPI
|
|
333
|
+
|
|
334
|
+
To build and publish release distributions to PyPI:
|
|
335
|
+
|
|
336
|
+
```bash
|
|
337
|
+
# 1. Build source distribution and wheel
|
|
338
|
+
python -m build
|
|
339
|
+
|
|
340
|
+
# 2. Verify archive integrity
|
|
341
|
+
twine check dist/*
|
|
342
|
+
|
|
343
|
+
# 3. (Recommended) Test publish to TestPyPI
|
|
344
|
+
twine upload --repository testpypi dist/*
|
|
345
|
+
|
|
346
|
+
# 4. Publish to production PyPI
|
|
347
|
+
twine upload dist/*
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
---
|
|
351
|
+
|
|
352
|
+
## ๐ License
|
|
353
|
+
|
|
354
|
+
This project is licensed under the **MIT License** โ see the [LICENSE](LICENSE) file for details.
|