multi-ets 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.
- multi_ets-0.1.0/LICENSE +16 -0
- multi_ets-0.1.0/MANIFEST.in +3 -0
- multi_ets-0.1.0/PKG-INFO +224 -0
- multi_ets-0.1.0/README.md +196 -0
- multi_ets-0.1.0/pyproject.toml +111 -0
- multi_ets-0.1.0/setup.cfg +4 -0
- multi_ets-0.1.0/setup.py +70 -0
- multi_ets-0.1.0/src/multi_ets/__init__.py +10 -0
- multi_ets-0.1.0/src/multi_ets/_holt_hot.pyx +475 -0
- multi_ets-0.1.0/src/multi_ets/holt.py +1204 -0
- multi_ets-0.1.0/src/multi_ets/py.typed +0 -0
- multi_ets-0.1.0/src/multi_ets/selection.py +136 -0
- multi_ets-0.1.0/src/multi_ets.egg-info/PKG-INFO +224 -0
- multi_ets-0.1.0/src/multi_ets.egg-info/SOURCES.txt +19 -0
- multi_ets-0.1.0/src/multi_ets.egg-info/dependency_links.txt +1 -0
- multi_ets-0.1.0/src/multi_ets.egg-info/requires.txt +2 -0
- multi_ets-0.1.0/src/multi_ets.egg-info/top_level.txt +1 -0
- multi_ets-0.1.0/tests/test_holt.py +1297 -0
- multi_ets-0.1.0/tests/test_holt_hot.py +198 -0
- multi_ets-0.1.0/tests/test_seasonal_hot.py +287 -0
- multi_ets-0.1.0/tests/test_selection.py +112 -0
multi_ets-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
MIT No Attribution
|
|
2
|
+
|
|
3
|
+
Copyright 2026 Robert Kübler
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this
|
|
6
|
+
software and associated documentation files (the "Software"), to deal in the Software
|
|
7
|
+
without restriction, including without limitation the rights to use, copy, modify,
|
|
8
|
+
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
|
9
|
+
permit persons to whom the Software is furnished to do so.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
12
|
+
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
|
13
|
+
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
14
|
+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
15
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
16
|
+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
multi_ets-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: multi-ets
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Exponential smoothing (SES, Holt, Holt-Winters) fit by joint multi-step-ahead loss instead of one-step-ahead residuals.
|
|
5
|
+
Author-email: Robert Kübler <xgarve@gmail.com>
|
|
6
|
+
License-Expression: MIT-0
|
|
7
|
+
Project-URL: Repository, https://github.com/RobKuebler/multi-ets
|
|
8
|
+
Project-URL: Issues, https://github.com/RobKuebler/multi-ets/issues
|
|
9
|
+
Keywords: forecasting,time-series,exponential-smoothing,holt-winters,ets
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Cython
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: scipy>=1.11
|
|
26
|
+
Requires-Dist: numpy>=1.26
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# multi-ets
|
|
30
|
+
|
|
31
|
+
Exponential smoothing (Holt, Holt-Winters) fit by minimizing a **joint multi-step-ahead loss**, instead of the classical one-step-ahead loss statsmodels and most other implementations use.
|
|
32
|
+
|
|
33
|
+
Most ETS implementations fit `alpha`/`beta`/`gamma`/... to minimize one-step-ahead residuals, then hope the recursion also forecasts well `h` steps out. Here, the loss is computed jointly across every valid forecast origin and every horizon step `1..h`, so the fitted parameters are the ones that actually minimize the error you care about: the multi-step forecast.
|
|
34
|
+
|
|
35
|
+
Fit with hand-derived gradients and multi-start [L-BFGS-B](https://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html) (via `scipy.optimize.minimize`) to deal with the resulting loss surface's local optima.
|
|
36
|
+
|
|
37
|
+
## Why multi-ets?
|
|
38
|
+
|
|
39
|
+
statsmodels and statsforecast are solid classical/innovations ETS implementations, but their fitting is rigid: one fixed loss (SSE or Gaussian MLE), and no real answer for missing data. `multi_ets` differs on exactly those two points, and is at least competitive on plain forecast accuracy.
|
|
40
|
+
|
|
41
|
+
**Missing values.** `multi_ets` skips NaN steps in the state recursion and zero-weights them out of the loss, instead of failing or silently propagating garbage:
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
=== Missing values (2 NaNs in a 20-point series) ===
|
|
45
|
+
multi_ets: [145.00701916 146.36080822 147.71459728]
|
|
46
|
+
statsmodels: [nan nan nan] (fits without error, but forecast is all-NaN)
|
|
47
|
+
statsforecast: raises Exception: no model able to be fitted
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
statsmodels *looks* like it succeeded -- `.fit()` raises nothing -- but the forecast is silently all-NaN. statsforecast fails outright. Neither offers a way to just handle the gap. (`uv run python -m benchmarks.capability_demo`)
|
|
51
|
+
|
|
52
|
+
**Loss functions.** All 9 built-in losses (`mse`, `mae`, `huber`, `pinball`, `expectile`, `logcosh`, `poisson`, `negbinom`, `tweedie`), or any custom callable, apply to every model. statsmodels and statsforecast don't expose a loss choice at all -- you get SSE (classical) or Gaussian MLE (innovations), period. That matters whenever the default isn't the right objective, e.g. an outlier-robust fit:
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
=== Loss choice on a series with one outlier ===
|
|
56
|
+
(ground truth for the first forecast step is ~130.0)
|
|
57
|
+
multi_ets (mse ): [135.01093768 135.62232229 136.2337069 136.84509151 137.45647612]
|
|
58
|
+
multi_ets (huber delta=5): [131.34230083 131.87624212 132.41018341 132.9441247 133.47806599]
|
|
59
|
+
statsmodels/statsforecast: no loss parameter -- always fit by SSE/MLE.
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The `huber` fit lands closer to the true continuation because the outlier no longer dominates the loss the way it does under plain `mse`.
|
|
63
|
+
|
|
64
|
+
**Forecast accuracy and fit time.** On a matched-structure rolling-origin backtest (4 real + 10 synthetic series, `h` in `{1, 6, 12}`, see `docs/adr/0003-batch-vs-one-step-ahead-fitting.md` and `benchmarks/run_model_comparison.py`), the joint multi-step loss beats statsmodels' classical one-step fit on MSE in 70% of h=6/h=12 cases (median MSE ratio 0.989), and comes out ahead by MASE more often than any single alternative (multi_ets 12/27, statsforecast 9/27, statsmodels 5/27). Median fit time is 0.077s vs. statsmodels' 0.120s; statsforecast is fastest at 0.017s (numba-jitted) but that speed comes with no loss choice and no missing-value support. None of this is a landslide in either direction -- `multi_ets` loses on some structures (e.g. `real_gdp` at longer horizons, documented in the ADR) -- but it's a real edge, not just a different API for the same fit.
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
uv run python -m benchmarks.run_model_comparison # regenerate the numbers above
|
|
68
|
+
uv run python -m benchmarks.capability_demo # regenerate the snippets above
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Install
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
uv add multi-ets # or: pip install multi-ets
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Usage
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from multi_ets import ExponentialSmoothing
|
|
81
|
+
|
|
82
|
+
# Flat forecast, no trend, no seasonality.
|
|
83
|
+
forecasts = ExponentialSmoothing(h=5).fit(y).predict()
|
|
84
|
+
|
|
85
|
+
# Plain linear trend, forecast 5 steps ahead.
|
|
86
|
+
forecasts = ExponentialSmoothing(h=5, trend="add").fit(y).predict()
|
|
87
|
+
|
|
88
|
+
# Damped trend (phi jointly optimized, box-constrained to (0, 1)).
|
|
89
|
+
forecasts = ExponentialSmoothing(h=5, trend="damped").fit(y).predict()
|
|
90
|
+
|
|
91
|
+
# Additive seasonality, period 12 (e.g. monthly data), with a linear trend.
|
|
92
|
+
forecasts = ExponentialSmoothing(h=5, trend="add", seasonal_period=12).fit(y).predict()
|
|
93
|
+
|
|
94
|
+
# Seasonality with no trend term at all.
|
|
95
|
+
forecasts = ExponentialSmoothing(h=5, seasonal_period=12).fit(y).predict()
|
|
96
|
+
|
|
97
|
+
# Multiplicative seasonality, with a damped trend.
|
|
98
|
+
forecasts = (
|
|
99
|
+
ExponentialSmoothing(h=5, trend="damped", seasonal_period=12, seasonal_type="multiplicative")
|
|
100
|
+
.fit(y)
|
|
101
|
+
.predict()
|
|
102
|
+
)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`trend` is `None` (default, no trend), `"add"`, or `"damped"`; `seasonal_period` (default `None`)
|
|
106
|
+
adds an `"additive"` or `"multiplicative"` (`seasonal_type`) seasonal component on top of either
|
|
107
|
+
trend, or on top of no trend at all. Every combination exposes just `.fit(y)` / `.predict()`;
|
|
108
|
+
fitted parameters are in `.params_` after `fit()`.
|
|
109
|
+
|
|
110
|
+
### Prediction intervals
|
|
111
|
+
|
|
112
|
+
Every model exposes `.predict_interval(coverage=0.9)` after fitting, returning an empirical
|
|
113
|
+
per-horizon-step Gaussian interval built from residuals of the fitted joint loss:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
lower, upper = ExponentialSmoothing(h=5, trend="add").fit(y).predict_interval(coverage=0.9)
|
|
117
|
+
|
|
118
|
+
# A list of coverages returns a {coverage: (lower, upper)} dict instead.
|
|
119
|
+
intervals = ExponentialSmoothing(h=5, trend="add").fit(y).predict_interval(coverage=[0.5, 0.9])
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Model selection
|
|
123
|
+
|
|
124
|
+
`select_model` picks the best of several already-configured candidates via rolling-origin
|
|
125
|
+
cross-validation, scoring each with its own `loss`/`h`:
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from multi_ets import ExponentialSmoothing, select_model
|
|
129
|
+
|
|
130
|
+
candidates = [
|
|
131
|
+
ExponentialSmoothing(h=5, loss="mae"),
|
|
132
|
+
ExponentialSmoothing(h=5, trend="add", seasonal_period=12, loss="mae"),
|
|
133
|
+
]
|
|
134
|
+
best, scores = select_model(candidates, y, n_splits=3)
|
|
135
|
+
forecasts = best.predict()
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`best` is refit on the full series; `scores` maps each candidate to its mean CV loss.
|
|
139
|
+
|
|
140
|
+
`AutoExponentialSmoothing` builds that candidate grid for you -- every valid `trend` x
|
|
141
|
+
`seasonal_type` combination at a given `seasonal_period` (or just the three `trend` options with
|
|
142
|
+
no seasonal candidates when `seasonal_period` is omitted) -- and picks the best the same way:
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
from multi_ets import AutoExponentialSmoothing
|
|
146
|
+
|
|
147
|
+
model = AutoExponentialSmoothing(h=5, seasonal_period=12, loss="mae").fit(y)
|
|
148
|
+
forecasts = model.predict()
|
|
149
|
+
model.best_ # the winning fitted ExponentialSmoothing
|
|
150
|
+
model.scores_ # {candidate: mean_cv_loss}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
It's named `AutoExponentialSmoothing` rather than `AutoETS`: `AutoETS` is statsforecast's name for
|
|
154
|
+
an *innovations*-based (MLE) auto-selector -- a structurally different fitting philosophy (see
|
|
155
|
+
CONTEXT.md's "Innovations ETS" glossary entry) -- and this repo's own benchmarks compare against
|
|
156
|
+
it directly.
|
|
157
|
+
|
|
158
|
+
### Loss
|
|
159
|
+
|
|
160
|
+
All models accept a `loss` kwarg: `"mse"` (default), `"mae"`, `"huber"` (+ `delta`), `"pinball"` (+
|
|
161
|
+
`tau`), `"expectile"` (+ `tau`), `"logcosh"`, `"poisson"`, `"negbinom"` (+ `alpha` dispersion), or
|
|
162
|
+
`"tweedie"` (+ `p` power, `1 < p < 2`), or any callable `(y_true, y_pred) -> scalar` written in
|
|
163
|
+
plain NumPy. `poisson`/`negbinom`/`tweedie` require a non-negative `y`.
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
ExponentialSmoothing(h=5, trend="add", loss="huber", delta=2.0).fit(y).predict()
|
|
167
|
+
ExponentialSmoothing(h=5, trend="add", loss="tweedie", p=1.3).fit(y).predict()
|
|
168
|
+
ExponentialSmoothing(h=5, trend="add", loss=lambda yt, yp: (yt - yp).var()).fit(y).predict()
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Multi-start
|
|
172
|
+
|
|
173
|
+
Fitting is non-convex, so each model restarts from `n_starts` (default 10) points spread across the parameter box and keeps the best, via a plain Python loop over `scipy.optimize.minimize`.
|
|
174
|
+
|
|
175
|
+
### Compiled backend
|
|
176
|
+
|
|
177
|
+
The fit objective + hand-derived gradient for every built-in loss (`mse`/`mae`/`huber`/`pinball`/
|
|
178
|
+
`poisson`/`negbinom`/`tweedie`/`expectile`/`logcosh`) runs in a compiled Cython extension. PyPI ships
|
|
179
|
+
prebuilt wheels for Linux, macOS and Windows (x86_64 and ARM), so `pip install multi-ets` gets the
|
|
180
|
+
fast version with no compiler needed. A custom callable `loss` always uses the NumPy path.
|
|
181
|
+
|
|
182
|
+
On a platform without a prebuilt wheel, pip builds from source. If no C compiler is available, the
|
|
183
|
+
install still succeeds with a warning and `multi_ets` falls back to the slower NumPy path -- results
|
|
184
|
+
are the same either way. See `docs/adr/0005-ship-compiled-wheels.md`.
|
|
185
|
+
|
|
186
|
+
For development, `uv sync` (or `pip install -e .`) compiles the extension automatically and
|
|
187
|
+
recompiles it when `_holt_hot.pyx` changes. The `MULTI_ETS_EXTENSION` environment variable
|
|
188
|
+
controls the build: `optional` (default), `required` (fail if compiling fails) or `skip`
|
|
189
|
+
(pure Python).
|
|
190
|
+
|
|
191
|
+
## Model overview
|
|
192
|
+
|
|
193
|
+
A single `ExponentialSmoothing(h, trend, seasonal_period, seasonal_type, ...)` class covers every
|
|
194
|
+
configuration below; the `trend`/`seasonal_period`/`seasonal_type` kwargs pick the configuration
|
|
195
|
+
(see `docs/adr/0004-consolidate-model-classes.md` for why this replaced one class per
|
|
196
|
+
configuration):
|
|
197
|
+
|
|
198
|
+
| `trend` | `seasonal_period` | Configuration |
|
|
199
|
+
|---|---|---|
|
|
200
|
+
| `None` | `None` | flat forecast, no trend, no seasonality (simple exponential smoothing) |
|
|
201
|
+
| `"add"` | `None` | linear trend |
|
|
202
|
+
| `"damped"` | `None` | damped trend, `phi` fit jointly |
|
|
203
|
+
| `None` | set | seasonal only, additive or multiplicative (`seasonal_type`), no trend |
|
|
204
|
+
| `"add"` | set | linear trend + seasonal, additive or multiplicative |
|
|
205
|
+
| `"damped"` | set | damped trend + seasonal, additive or multiplicative |
|
|
206
|
+
|
|
207
|
+
## Development
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
uv run pytest tests/ -q
|
|
211
|
+
uv run python examples/benchmark.py # accuracy/speed vs. statsmodels on real datasets
|
|
212
|
+
uv run python -m benchmarks.capability_demo # missing-value / loss-choice demo (see "Why multi-ets?")
|
|
213
|
+
|
|
214
|
+
uv run pre-commit install # once, to run lint/format/type checks on every commit
|
|
215
|
+
uv run pre-commit run --all-files
|
|
216
|
+
|
|
217
|
+
uv run ruff check . # lint
|
|
218
|
+
uv run ruff format . # format
|
|
219
|
+
uv run ty check src # type check
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## License
|
|
223
|
+
|
|
224
|
+
[MIT No Attribution](LICENSE) (MIT-0): use, modify and redistribute it for any purpose, commercial included, with no attribution required.
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
# multi-ets
|
|
2
|
+
|
|
3
|
+
Exponential smoothing (Holt, Holt-Winters) fit by minimizing a **joint multi-step-ahead loss**, instead of the classical one-step-ahead loss statsmodels and most other implementations use.
|
|
4
|
+
|
|
5
|
+
Most ETS implementations fit `alpha`/`beta`/`gamma`/... to minimize one-step-ahead residuals, then hope the recursion also forecasts well `h` steps out. Here, the loss is computed jointly across every valid forecast origin and every horizon step `1..h`, so the fitted parameters are the ones that actually minimize the error you care about: the multi-step forecast.
|
|
6
|
+
|
|
7
|
+
Fit with hand-derived gradients and multi-start [L-BFGS-B](https://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html) (via `scipy.optimize.minimize`) to deal with the resulting loss surface's local optima.
|
|
8
|
+
|
|
9
|
+
## Why multi-ets?
|
|
10
|
+
|
|
11
|
+
statsmodels and statsforecast are solid classical/innovations ETS implementations, but their fitting is rigid: one fixed loss (SSE or Gaussian MLE), and no real answer for missing data. `multi_ets` differs on exactly those two points, and is at least competitive on plain forecast accuracy.
|
|
12
|
+
|
|
13
|
+
**Missing values.** `multi_ets` skips NaN steps in the state recursion and zero-weights them out of the loss, instead of failing or silently propagating garbage:
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
=== Missing values (2 NaNs in a 20-point series) ===
|
|
17
|
+
multi_ets: [145.00701916 146.36080822 147.71459728]
|
|
18
|
+
statsmodels: [nan nan nan] (fits without error, but forecast is all-NaN)
|
|
19
|
+
statsforecast: raises Exception: no model able to be fitted
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
statsmodels *looks* like it succeeded -- `.fit()` raises nothing -- but the forecast is silently all-NaN. statsforecast fails outright. Neither offers a way to just handle the gap. (`uv run python -m benchmarks.capability_demo`)
|
|
23
|
+
|
|
24
|
+
**Loss functions.** All 9 built-in losses (`mse`, `mae`, `huber`, `pinball`, `expectile`, `logcosh`, `poisson`, `negbinom`, `tweedie`), or any custom callable, apply to every model. statsmodels and statsforecast don't expose a loss choice at all -- you get SSE (classical) or Gaussian MLE (innovations), period. That matters whenever the default isn't the right objective, e.g. an outlier-robust fit:
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
=== Loss choice on a series with one outlier ===
|
|
28
|
+
(ground truth for the first forecast step is ~130.0)
|
|
29
|
+
multi_ets (mse ): [135.01093768 135.62232229 136.2337069 136.84509151 137.45647612]
|
|
30
|
+
multi_ets (huber delta=5): [131.34230083 131.87624212 132.41018341 132.9441247 133.47806599]
|
|
31
|
+
statsmodels/statsforecast: no loss parameter -- always fit by SSE/MLE.
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The `huber` fit lands closer to the true continuation because the outlier no longer dominates the loss the way it does under plain `mse`.
|
|
35
|
+
|
|
36
|
+
**Forecast accuracy and fit time.** On a matched-structure rolling-origin backtest (4 real + 10 synthetic series, `h` in `{1, 6, 12}`, see `docs/adr/0003-batch-vs-one-step-ahead-fitting.md` and `benchmarks/run_model_comparison.py`), the joint multi-step loss beats statsmodels' classical one-step fit on MSE in 70% of h=6/h=12 cases (median MSE ratio 0.989), and comes out ahead by MASE more often than any single alternative (multi_ets 12/27, statsforecast 9/27, statsmodels 5/27). Median fit time is 0.077s vs. statsmodels' 0.120s; statsforecast is fastest at 0.017s (numba-jitted) but that speed comes with no loss choice and no missing-value support. None of this is a landslide in either direction -- `multi_ets` loses on some structures (e.g. `real_gdp` at longer horizons, documented in the ADR) -- but it's a real edge, not just a different API for the same fit.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
uv run python -m benchmarks.run_model_comparison # regenerate the numbers above
|
|
40
|
+
uv run python -m benchmarks.capability_demo # regenerate the snippets above
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
uv add multi-ets # or: pip install multi-ets
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from multi_ets import ExponentialSmoothing
|
|
53
|
+
|
|
54
|
+
# Flat forecast, no trend, no seasonality.
|
|
55
|
+
forecasts = ExponentialSmoothing(h=5).fit(y).predict()
|
|
56
|
+
|
|
57
|
+
# Plain linear trend, forecast 5 steps ahead.
|
|
58
|
+
forecasts = ExponentialSmoothing(h=5, trend="add").fit(y).predict()
|
|
59
|
+
|
|
60
|
+
# Damped trend (phi jointly optimized, box-constrained to (0, 1)).
|
|
61
|
+
forecasts = ExponentialSmoothing(h=5, trend="damped").fit(y).predict()
|
|
62
|
+
|
|
63
|
+
# Additive seasonality, period 12 (e.g. monthly data), with a linear trend.
|
|
64
|
+
forecasts = ExponentialSmoothing(h=5, trend="add", seasonal_period=12).fit(y).predict()
|
|
65
|
+
|
|
66
|
+
# Seasonality with no trend term at all.
|
|
67
|
+
forecasts = ExponentialSmoothing(h=5, seasonal_period=12).fit(y).predict()
|
|
68
|
+
|
|
69
|
+
# Multiplicative seasonality, with a damped trend.
|
|
70
|
+
forecasts = (
|
|
71
|
+
ExponentialSmoothing(h=5, trend="damped", seasonal_period=12, seasonal_type="multiplicative")
|
|
72
|
+
.fit(y)
|
|
73
|
+
.predict()
|
|
74
|
+
)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`trend` is `None` (default, no trend), `"add"`, or `"damped"`; `seasonal_period` (default `None`)
|
|
78
|
+
adds an `"additive"` or `"multiplicative"` (`seasonal_type`) seasonal component on top of either
|
|
79
|
+
trend, or on top of no trend at all. Every combination exposes just `.fit(y)` / `.predict()`;
|
|
80
|
+
fitted parameters are in `.params_` after `fit()`.
|
|
81
|
+
|
|
82
|
+
### Prediction intervals
|
|
83
|
+
|
|
84
|
+
Every model exposes `.predict_interval(coverage=0.9)` after fitting, returning an empirical
|
|
85
|
+
per-horizon-step Gaussian interval built from residuals of the fitted joint loss:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
lower, upper = ExponentialSmoothing(h=5, trend="add").fit(y).predict_interval(coverage=0.9)
|
|
89
|
+
|
|
90
|
+
# A list of coverages returns a {coverage: (lower, upper)} dict instead.
|
|
91
|
+
intervals = ExponentialSmoothing(h=5, trend="add").fit(y).predict_interval(coverage=[0.5, 0.9])
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Model selection
|
|
95
|
+
|
|
96
|
+
`select_model` picks the best of several already-configured candidates via rolling-origin
|
|
97
|
+
cross-validation, scoring each with its own `loss`/`h`:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from multi_ets import ExponentialSmoothing, select_model
|
|
101
|
+
|
|
102
|
+
candidates = [
|
|
103
|
+
ExponentialSmoothing(h=5, loss="mae"),
|
|
104
|
+
ExponentialSmoothing(h=5, trend="add", seasonal_period=12, loss="mae"),
|
|
105
|
+
]
|
|
106
|
+
best, scores = select_model(candidates, y, n_splits=3)
|
|
107
|
+
forecasts = best.predict()
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`best` is refit on the full series; `scores` maps each candidate to its mean CV loss.
|
|
111
|
+
|
|
112
|
+
`AutoExponentialSmoothing` builds that candidate grid for you -- every valid `trend` x
|
|
113
|
+
`seasonal_type` combination at a given `seasonal_period` (or just the three `trend` options with
|
|
114
|
+
no seasonal candidates when `seasonal_period` is omitted) -- and picks the best the same way:
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
from multi_ets import AutoExponentialSmoothing
|
|
118
|
+
|
|
119
|
+
model = AutoExponentialSmoothing(h=5, seasonal_period=12, loss="mae").fit(y)
|
|
120
|
+
forecasts = model.predict()
|
|
121
|
+
model.best_ # the winning fitted ExponentialSmoothing
|
|
122
|
+
model.scores_ # {candidate: mean_cv_loss}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
It's named `AutoExponentialSmoothing` rather than `AutoETS`: `AutoETS` is statsforecast's name for
|
|
126
|
+
an *innovations*-based (MLE) auto-selector -- a structurally different fitting philosophy (see
|
|
127
|
+
CONTEXT.md's "Innovations ETS" glossary entry) -- and this repo's own benchmarks compare against
|
|
128
|
+
it directly.
|
|
129
|
+
|
|
130
|
+
### Loss
|
|
131
|
+
|
|
132
|
+
All models accept a `loss` kwarg: `"mse"` (default), `"mae"`, `"huber"` (+ `delta`), `"pinball"` (+
|
|
133
|
+
`tau`), `"expectile"` (+ `tau`), `"logcosh"`, `"poisson"`, `"negbinom"` (+ `alpha` dispersion), or
|
|
134
|
+
`"tweedie"` (+ `p` power, `1 < p < 2`), or any callable `(y_true, y_pred) -> scalar` written in
|
|
135
|
+
plain NumPy. `poisson`/`negbinom`/`tweedie` require a non-negative `y`.
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
ExponentialSmoothing(h=5, trend="add", loss="huber", delta=2.0).fit(y).predict()
|
|
139
|
+
ExponentialSmoothing(h=5, trend="add", loss="tweedie", p=1.3).fit(y).predict()
|
|
140
|
+
ExponentialSmoothing(h=5, trend="add", loss=lambda yt, yp: (yt - yp).var()).fit(y).predict()
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Multi-start
|
|
144
|
+
|
|
145
|
+
Fitting is non-convex, so each model restarts from `n_starts` (default 10) points spread across the parameter box and keeps the best, via a plain Python loop over `scipy.optimize.minimize`.
|
|
146
|
+
|
|
147
|
+
### Compiled backend
|
|
148
|
+
|
|
149
|
+
The fit objective + hand-derived gradient for every built-in loss (`mse`/`mae`/`huber`/`pinball`/
|
|
150
|
+
`poisson`/`negbinom`/`tweedie`/`expectile`/`logcosh`) runs in a compiled Cython extension. PyPI ships
|
|
151
|
+
prebuilt wheels for Linux, macOS and Windows (x86_64 and ARM), so `pip install multi-ets` gets the
|
|
152
|
+
fast version with no compiler needed. A custom callable `loss` always uses the NumPy path.
|
|
153
|
+
|
|
154
|
+
On a platform without a prebuilt wheel, pip builds from source. If no C compiler is available, the
|
|
155
|
+
install still succeeds with a warning and `multi_ets` falls back to the slower NumPy path -- results
|
|
156
|
+
are the same either way. See `docs/adr/0005-ship-compiled-wheels.md`.
|
|
157
|
+
|
|
158
|
+
For development, `uv sync` (or `pip install -e .`) compiles the extension automatically and
|
|
159
|
+
recompiles it when `_holt_hot.pyx` changes. The `MULTI_ETS_EXTENSION` environment variable
|
|
160
|
+
controls the build: `optional` (default), `required` (fail if compiling fails) or `skip`
|
|
161
|
+
(pure Python).
|
|
162
|
+
|
|
163
|
+
## Model overview
|
|
164
|
+
|
|
165
|
+
A single `ExponentialSmoothing(h, trend, seasonal_period, seasonal_type, ...)` class covers every
|
|
166
|
+
configuration below; the `trend`/`seasonal_period`/`seasonal_type` kwargs pick the configuration
|
|
167
|
+
(see `docs/adr/0004-consolidate-model-classes.md` for why this replaced one class per
|
|
168
|
+
configuration):
|
|
169
|
+
|
|
170
|
+
| `trend` | `seasonal_period` | Configuration |
|
|
171
|
+
|---|---|---|
|
|
172
|
+
| `None` | `None` | flat forecast, no trend, no seasonality (simple exponential smoothing) |
|
|
173
|
+
| `"add"` | `None` | linear trend |
|
|
174
|
+
| `"damped"` | `None` | damped trend, `phi` fit jointly |
|
|
175
|
+
| `None` | set | seasonal only, additive or multiplicative (`seasonal_type`), no trend |
|
|
176
|
+
| `"add"` | set | linear trend + seasonal, additive or multiplicative |
|
|
177
|
+
| `"damped"` | set | damped trend + seasonal, additive or multiplicative |
|
|
178
|
+
|
|
179
|
+
## Development
|
|
180
|
+
|
|
181
|
+
```bash
|
|
182
|
+
uv run pytest tests/ -q
|
|
183
|
+
uv run python examples/benchmark.py # accuracy/speed vs. statsmodels on real datasets
|
|
184
|
+
uv run python -m benchmarks.capability_demo # missing-value / loss-choice demo (see "Why multi-ets?")
|
|
185
|
+
|
|
186
|
+
uv run pre-commit install # once, to run lint/format/type checks on every commit
|
|
187
|
+
uv run pre-commit run --all-files
|
|
188
|
+
|
|
189
|
+
uv run ruff check . # lint
|
|
190
|
+
uv run ruff format . # format
|
|
191
|
+
uv run ty check src # type check
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## License
|
|
195
|
+
|
|
196
|
+
[MIT No Attribution](LICENSE) (MIT-0): use, modify and redistribute it for any purpose, commercial included, with no attribution required.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "multi-ets"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Exponential smoothing (SES, Holt, Holt-Winters) fit by joint multi-step-ahead loss instead of one-step-ahead residuals."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Robert Kübler", email = "xgarve@gmail.com" }
|
|
8
|
+
]
|
|
9
|
+
license = "MIT-0"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
requires-python = ">=3.12"
|
|
12
|
+
keywords = ["forecasting", "time-series", "exponential-smoothing", "holt-winters", "ets"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Intended Audience :: Science/Research",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Programming Language :: Python :: 3.14",
|
|
22
|
+
"Programming Language :: Cython",
|
|
23
|
+
"Operating System :: OS Independent",
|
|
24
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"scipy>=1.11",
|
|
29
|
+
"numpy>=1.26",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Repository = "https://github.com/RobKuebler/multi-ets"
|
|
34
|
+
Issues = "https://github.com/RobKuebler/multi-ets/issues"
|
|
35
|
+
|
|
36
|
+
[dependency-groups]
|
|
37
|
+
dev = [
|
|
38
|
+
"pre-commit>=4.6.2",
|
|
39
|
+
"pytest>=8.0",
|
|
40
|
+
"pytest-cov>=7.1.0",
|
|
41
|
+
"ruff>=0.16.3",
|
|
42
|
+
"statsmodels>=0.14",
|
|
43
|
+
"ty>=0.0.73",
|
|
44
|
+
]
|
|
45
|
+
benchmark = [
|
|
46
|
+
"statsforecast>=2.0",
|
|
47
|
+
"matplotlib>=3.8",
|
|
48
|
+
"pandas>=2.0",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
[build-system]
|
|
52
|
+
# setuptools + Cython compile the `_holt_hot` extension on every install
|
|
53
|
+
# (setup.py). Building against NumPy 2 yields extensions that also run on
|
|
54
|
+
# NumPy 1.x, so the runtime `numpy>=1.26` floor still holds.
|
|
55
|
+
# See docs/adr/0005-ship-compiled-wheels.md.
|
|
56
|
+
requires = ["setuptools>=77", "cython>=3.0", "numpy>=2.0"]
|
|
57
|
+
build-backend = "setuptools.build_meta"
|
|
58
|
+
|
|
59
|
+
[tool.setuptools.packages.find]
|
|
60
|
+
where = ["src"]
|
|
61
|
+
|
|
62
|
+
[tool.setuptools.package-data]
|
|
63
|
+
multi_ets = ["py.typed"]
|
|
64
|
+
|
|
65
|
+
[tool.setuptools.exclude-package-data]
|
|
66
|
+
multi_ets = ["*.pyx", "*.c"]
|
|
67
|
+
|
|
68
|
+
[tool.uv]
|
|
69
|
+
# Rebuild the editable install when the Cython source or build script changes.
|
|
70
|
+
cache-keys = [{ file = "pyproject.toml" }, { file = "setup.py" }, { file = "src/**/*.pyx" }]
|
|
71
|
+
|
|
72
|
+
[tool.cibuildwheel]
|
|
73
|
+
# Builds every CPython that requires-python allows. Free-threaded and 32-bit
|
|
74
|
+
# builds are skipped (scipy ships no wheels for most of them).
|
|
75
|
+
skip = ["cp3??t-*", "*-win32", "*_i686"]
|
|
76
|
+
environment = { MULTI_ETS_EXTENSION = "required" }
|
|
77
|
+
test-requires = ["pytest", "pytest-cov"]
|
|
78
|
+
# Fail if the wheel lacks the extension (the hot-loop tests would only skip).
|
|
79
|
+
test-command = [
|
|
80
|
+
'python -c "import multi_ets._holt_hot"',
|
|
81
|
+
"pytest {project}/tests/test_holt_hot.py {project}/tests/test_seasonal_hot.py -q -p no:cacheprovider",
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
[tool.cibuildwheel.macos]
|
|
85
|
+
archs = ["x86_64", "arm64"]
|
|
86
|
+
|
|
87
|
+
[tool.ruff]
|
|
88
|
+
target-version = "py312"
|
|
89
|
+
line-length = 100
|
|
90
|
+
|
|
91
|
+
[tool.ruff.lint]
|
|
92
|
+
select = ["E", "F", "I", "UP", "B", "SIM", "RUF", "NPY", "D", "ANN"]
|
|
93
|
+
# ANN401: this module deliberately types numpy-duck-typed values as Any
|
|
94
|
+
# rather than chasing precise stubs that don't buy much at this size.
|
|
95
|
+
ignore = ["ANN401"]
|
|
96
|
+
|
|
97
|
+
[tool.ruff.lint.pydocstyle]
|
|
98
|
+
convention = "numpy"
|
|
99
|
+
|
|
100
|
+
[tool.ruff.lint.per-file-ignores]
|
|
101
|
+
"tests/*" = ["D", "ANN"]
|
|
102
|
+
"examples/*" = ["D", "ANN"]
|
|
103
|
+
"benchmarks/*" = ["D", "ANN"]
|
|
104
|
+
"spikes/**" = ["D", "ANN"]
|
|
105
|
+
|
|
106
|
+
[tool.pytest.ini_options]
|
|
107
|
+
testpaths = ["tests"]
|
|
108
|
+
addopts = "--cov=multi_ets --cov-report=term-missing"
|
|
109
|
+
|
|
110
|
+
[tool.coverage.run]
|
|
111
|
+
source = ["src/multi_ets"]
|
multi_ets-0.1.0/setup.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Builds the `multi_ets._holt_hot` Cython extension as part of every install.
|
|
2
|
+
|
|
3
|
+
The package metadata lives in `pyproject.toml`; this file only declares the
|
|
4
|
+
compiled extension (see docs/adr/0005-ship-compiled-wheels.md). The
|
|
5
|
+
`MULTI_ETS_EXTENSION` environment variable controls what happens:
|
|
6
|
+
|
|
7
|
+
- `optional` (default): try to compile; if the C compiler is missing or the
|
|
8
|
+
compile fails, warn and install the pure-Python package, which falls back to
|
|
9
|
+
the NumPy path at import time.
|
|
10
|
+
- `required`: a failed compile fails the build. Used by CI and the
|
|
11
|
+
cibuildwheel release build, so a broken compile can't ship silently.
|
|
12
|
+
- `skip`: don't build the extension at all (tests the pure-Python fallback).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
from Cython.Build import cythonize
|
|
21
|
+
from setuptools import Extension, setup
|
|
22
|
+
from setuptools.command.build_ext import build_ext
|
|
23
|
+
|
|
24
|
+
MODE = os.environ.get("MULTI_ETS_EXTENSION", "optional")
|
|
25
|
+
if MODE not in {"optional", "required", "skip"}:
|
|
26
|
+
raise ValueError(f"MULTI_ETS_EXTENSION must be optional/required/skip, got {MODE!r}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class OptionalBuildExt(build_ext):
|
|
30
|
+
"""`build_ext` that degrades to a warning unless the extension is required."""
|
|
31
|
+
|
|
32
|
+
def run(self) -> None:
|
|
33
|
+
"""Build all extensions, swallowing failures in `optional` mode."""
|
|
34
|
+
try:
|
|
35
|
+
super().run()
|
|
36
|
+
except Exception as exc:
|
|
37
|
+
self._fail(exc)
|
|
38
|
+
|
|
39
|
+
def build_extension(self, ext: Any) -> None:
|
|
40
|
+
"""Build one extension, swallowing failures in `optional` mode."""
|
|
41
|
+
try:
|
|
42
|
+
super().build_extension(ext)
|
|
43
|
+
except Exception as exc:
|
|
44
|
+
self._fail(exc)
|
|
45
|
+
|
|
46
|
+
def _fail(self, exc: Exception) -> None:
|
|
47
|
+
if MODE == "required":
|
|
48
|
+
raise exc
|
|
49
|
+
print(
|
|
50
|
+
f"WARNING: building multi_ets._holt_hot failed ({exc}); installing the "
|
|
51
|
+
"pure-Python version, which uses the slower NumPy fitting path.",
|
|
52
|
+
file=sys.stderr,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
ext_modules = []
|
|
57
|
+
if MODE != "skip":
|
|
58
|
+
ext_modules = cythonize(
|
|
59
|
+
[
|
|
60
|
+
Extension(
|
|
61
|
+
"multi_ets._holt_hot",
|
|
62
|
+
["src/multi_ets/_holt_hot.pyx"],
|
|
63
|
+
include_dirs=[np.get_include()],
|
|
64
|
+
define_macros=[("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")],
|
|
65
|
+
)
|
|
66
|
+
],
|
|
67
|
+
compiler_directives={"language_level": "3"},
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
setup(ext_modules=ext_modules, cmdclass={"build_ext": OptionalBuildExt})
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Holt/Holt-Winters exponential smoothing models fit by a joint multi-step loss."""
|
|
2
|
+
|
|
3
|
+
from multi_ets.holt import ExponentialSmoothing
|
|
4
|
+
from multi_ets.selection import AutoExponentialSmoothing, select_model
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"AutoExponentialSmoothing",
|
|
8
|
+
"ExponentialSmoothing",
|
|
9
|
+
"select_model",
|
|
10
|
+
]
|