-
Notifications
You must be signed in to change notification settings - Fork 255
/
models.py
6421 lines (5700 loc) · 215 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/src/core/models.ipynb.
# %% auto 0
__all__ = ['AutoARIMA', 'AutoETS', 'ETS', 'AutoCES', 'AutoTheta', 'ARIMA', 'AutoRegressive', 'SimpleExponentialSmoothing',
'SimpleExponentialSmoothingOptimized', 'SeasonalExponentialSmoothing',
'SeasonalExponentialSmoothingOptimized', 'Holt', 'HoltWinters', 'HistoricAverage', 'Naive',
'RandomWalkWithDrift', 'SeasonalNaive', 'WindowAverage', 'SeasonalWindowAverage', 'ADIDA', 'CrostonClassic',
'CrostonOptimized', 'CrostonSBA', 'IMAPA', 'TSB', 'MSTL', 'TBATS', 'AutoTBATS', 'Theta', 'OptimizedTheta',
'DynamicTheta', 'DynamicOptimizedTheta', 'GARCH', 'ARCH', 'SklearnModel', 'ConstantModel', 'ZeroModel',
'NaNModel']
# %% ../nbs/src/core/models.ipynb 5
import warnings
from math import trunc
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
from numba import njit
from scipy.optimize import minimize
from scipy.special import inv_boxcox
from statsforecast.arima import (
Arima,
auto_arima_f,
fitted_arima,
forecast_arima,
forward_arima,
is_constant,
)
from .ces import auto_ces, forecast_ces, forward_ces
from statsforecast.ets import (
_PHI_LOWER,
_PHI_UPPER,
ets_f,
forecast_ets,
forward_ets,
)
from .mstl import mstl
from .theta import auto_theta, forecast_theta, forward_theta
from .garch import garch_model, garch_forecast
from .tbats import tbats_selection, tbats_forecast, _compute_sigmah
from statsforecast.utils import (
_calculate_sigma,
_calculate_intervals,
_ensure_float,
_naive,
_old_kw_to_pos,
_quantiles,
_repeat_val,
_repeat_val_seas,
_seasonal_naive,
CACHE,
ConformalIntervals,
NOGIL,
)
# %% ../nbs/src/core/models.ipynb 9
def _add_fitted_pi(res, se, level):
level = sorted(level)
level = np.asarray(level)
quantiles = _quantiles(level=level)
lo = res["fitted"].reshape(-1, 1) - quantiles * se.reshape(-1, 1)
hi = res["fitted"].reshape(-1, 1) + quantiles * se.reshape(-1, 1)
lo = lo[:, ::-1]
lo = {f"fitted-lo-{l}": lo[:, i] for i, l in enumerate(reversed(level))}
hi = {f"fitted-hi-{l}": hi[:, i] for i, l in enumerate(level)}
res = {**res, **lo, **hi}
return res
# %% ../nbs/src/core/models.ipynb 10
def _add_conformal_distribution_intervals(
fcst: Dict,
cs: np.ndarray,
level: List[Union[int, float]],
) -> Dict:
"""
Adds conformal intervals to the `fcst` dict based on conformal scores `cs`.
`level` should be already sorted. This strategy creates forecasts paths
based on errors and calculate quantiles using those paths.
"""
alphas = [100 - lv for lv in level]
cuts = [alpha / 200 for alpha in reversed(alphas)]
cuts.extend(1 - alpha / 200 for alpha in alphas)
mean = fcst["mean"].reshape(1, -1)
scores = np.vstack([mean - cs, mean + cs])
quantiles = np.quantile(
scores,
cuts,
axis=0,
)
quantiles = quantiles.reshape(len(cuts), -1)
lo_cols = [f"lo-{lv}" for lv in reversed(level)]
hi_cols = [f"hi-{lv}" for lv in level]
out_cols = lo_cols + hi_cols
for i, col in enumerate(out_cols):
fcst[col] = quantiles[i]
return fcst
# %% ../nbs/src/core/models.ipynb 11
def _get_conformal_method(method: str):
available_methods = {
"conformal_distribution": _add_conformal_distribution_intervals,
# "conformal_error": _add_conformal_error_intervals,
}
if method not in available_methods.keys():
raise ValueError(
f"prediction intervals method {method} not supported "
f'please choose one of {", ".join(available_methods.keys())}'
)
return available_methods[method]
# %% ../nbs/src/core/models.ipynb 12
class _TS:
uses_exog = False
def new(self):
b = type(self).__new__(type(self))
b.__dict__.update(self.__dict__)
return b
def _conformity_scores(
self,
y: np.ndarray,
X: Optional[np.ndarray] = None,
) -> np.ndarray:
n_windows = self.prediction_intervals.n_windows # type: ignore[attr-defined]
h = self.prediction_intervals.h # type: ignore[attr-defined]
n_samples = y.size
# use as many windows as possible for short series
# subtract 1 for the training set
n_windows = min(n_windows, (n_samples - 1) // h)
if n_windows < 2:
raise ValueError(
f"Prediction intervals settings require at least {2 * h + 1:,} samples, serie has {n_samples:,}."
)
test_size = n_windows * h
cs = np.empty((n_windows, h), dtype=np.float32)
for i_window in range(n_windows):
train_end = n_samples - test_size + i_window * h
y_train = y[:train_end]
y_test = y[train_end : train_end + h]
if X is not None:
X_train = X[:train_end]
X_test = X[train_end : train_end + h]
else:
X_train = None
X_test = None
fcst_window = self.forecast(h=h, y=y_train, X=X_train, X_future=X_test) # type: ignore[attr-defined]
cs[i_window] = np.abs(fcst_window["mean"] - y_test)
return cs
@property
def _conformal_method(self):
return _get_conformal_method(self.prediction_intervals.method)
def _store_cs(self, y, X):
if self.prediction_intervals is not None:
self._cs = self._conformity_scores(y, X)
def _add_conformal_intervals(self, fcst, y, X, level):
if self.prediction_intervals is not None and level is not None:
cs = self._conformity_scores(y, X) if y is not None else self._cs
res = self._conformal_method(fcst=fcst, cs=cs, level=level)
return res
return fcst
def _add_predict_conformal_intervals(self, fcst, level):
return self._add_conformal_intervals(fcst=fcst, y=None, X=None, level=level)
# %% ../nbs/src/core/models.ipynb 17
class AutoARIMA(_TS):
"""AutoARIMA model.
Automatically selects the best ARIMA (AutoRegressive Integrated Moving Average)
model using an information criterion. Default is Akaike Information Criterion (AICc).
Notes
-----
This implementation is a mirror of Hyndman's [forecast::auto.arima](https://github.com/robjhyndman/forecast).
References
----------
[Rob J. Hyndman, Yeasmin Khandakar (2008). "Automatic Time Series Forecasting: The forecast package for R"](https://www.jstatsoft.org/article/view/v027i03).
Parameters
----------
d : Optional[int]
Order of first-differencing.
D : Optional[int]
Order of seasonal-differencing.
max_p : int
Max autorregresives p.
max_q : int
Max moving averages q.
max_P : int
Max seasonal autorregresives P.
max_Q : int
Max seasonal moving averages Q.
max_order : int
Max p+q+P+Q value if not stepwise selection.
max_d : int
Max non-seasonal differences.
max_D : int
Max seasonal differences.
start_p : int
Starting value of p in stepwise procedure.
start_q : int
Starting value of q in stepwise procedure.
start_P : int
Starting value of P in stepwise procedure.
start_Q : int
Starting value of Q in stepwise procedure.
stationary : bool
If True, restricts search to stationary models.
seasonal : bool
If False, restricts search to non-seasonal models.
ic : str
Information criterion to be used in model selection.
stepwise : bool
If True, will do stepwise selection (faster).
nmodels : int
Number of models considered in stepwise search.
trace : bool
If True, the searched ARIMA models is reported.
approximation : Optional[bool]
If True, conditional sums-of-squares estimation, final MLE.
method : Optional[str]
Fitting method between maximum likelihood or sums-of-squares.
truncate : Optional[int]
Observations truncated series used in model selection.
test : str
Unit root test to use. See `ndiffs` for details.
test_kwargs : Optional[str]
Unit root test additional arguments.
seasonal_test : str
Selection method for seasonal differences.
seasonal_test_kwargs : Optional[dict]
Seasonal unit root test arguments.
allowdrift : bool (default True)
If True, drift models terms considered.
allowmean : bool (default True)
If True, non-zero mean models considered.
blambda : Optional[float]
Box-Cox transformation parameter.
biasadj : bool
Use adjusted back-transformed mean Box-Cox.
season_length : int
Number of observations per unit of time. Ex: 24 Hourly data.
alias : str
Custom name of the model.
prediction_intervals : Optional[ConformalIntervals]
Information to compute conformal prediction intervals.
By default, the model will compute the native prediction
intervals.
"""
uses_exog = True
def __init__(
self,
d: Optional[int] = None,
D: Optional[int] = None,
max_p: int = 5,
max_q: int = 5,
max_P: int = 2,
max_Q: int = 2,
max_order: int = 5,
max_d: int = 2,
max_D: int = 1,
start_p: int = 2,
start_q: int = 2,
start_P: int = 1,
start_Q: int = 1,
stationary: bool = False,
seasonal: bool = True,
ic: str = "aicc",
stepwise: bool = True,
nmodels: int = 94,
trace: bool = False,
approximation: Optional[bool] = False,
method: Optional[str] = None,
truncate: Optional[bool] = None,
test: str = "kpss",
test_kwargs: Optional[str] = None,
seasonal_test: str = "seas",
seasonal_test_kwargs: Optional[Dict] = None,
allowdrift: bool = False,
allowmean: bool = False,
blambda: Optional[float] = None,
biasadj: bool = False,
season_length: int = 1,
alias: str = "AutoARIMA",
prediction_intervals: Optional[ConformalIntervals] = None,
):
self.d = d
self.D = D
self.max_p = max_p
self.max_q = max_q
self.max_P = max_P
self.max_Q = max_Q
self.max_order = max_order
self.max_d = max_d
self.max_D = max_D
self.start_p = start_p
self.start_q = start_q
self.start_P = start_P
self.start_Q = start_Q
self.stationary = stationary
self.seasonal = seasonal
self.ic = ic
self.stepwise = stepwise
self.nmodels = nmodels
self.trace = trace
self.approximation = approximation
self.method = method
self.truncate = truncate
self.test = test
self.test_kwargs = test_kwargs
self.seasonal_test = seasonal_test
self.seasonal_test_kwargs = seasonal_test_kwargs
self.allowdrift = allowdrift
self.allowmean = allowmean
self.blambda = blambda
self.biasadj = biasadj
self.season_length = season_length
self.alias = alias
self.prediction_intervals = prediction_intervals
def __repr__(self):
return self.alias
def fit(
self,
y: np.ndarray,
X: Optional[np.ndarray] = None,
):
"""Fit the AutoARIMA model.
Fit an AutoARIMA to a time series (numpy array) `y`
and optionally exogenous variables (numpy array) `X`.
Parameters
----------
y : numpy.array
Clean time series of shape (t, ).
X : array-like
Optional exogenous of shape (t, n_x).
Returns
-------
self :
AutoARIMA fitted model.
"""
with np.errstate(invalid="ignore"):
self.model_ = auto_arima_f(
x=y,
d=self.d,
D=self.D,
max_p=self.max_p,
max_q=self.max_q,
max_P=self.max_P,
max_Q=self.max_Q,
max_order=self.max_order,
max_d=self.max_d,
max_D=self.max_D,
start_p=self.start_p,
start_q=self.start_q,
start_P=self.start_P,
start_Q=self.start_Q,
stationary=self.stationary,
seasonal=self.seasonal,
ic=self.ic,
stepwise=self.stepwise,
nmodels=self.nmodels,
trace=self.trace,
approximation=self.approximation,
method=self.method,
truncate=self.truncate,
xreg=X,
test=self.test,
test_kwargs=self.test_kwargs,
seasonal_test=self.seasonal_test,
seasonal_test_kwargs=self.seasonal_test_kwargs,
allowdrift=self.allowdrift,
allowmean=self.allowmean,
blambda=self.blambda,
biasadj=self.biasadj,
period=self.season_length,
)
self._store_cs(y=y, X=X)
return self
def predict(
self,
h: int,
X: Optional[np.ndarray] = None,
level: Optional[List[int]] = None,
):
"""Predict with fitted AutoArima.
Parameters
----------
h : int
Forecast horizon.
X : array-like
Optional exogenous of shape (h, n_x).
level : List[float]
Confidence levels (0-100) for prediction intervals.
Returns
-------
forecasts : dict
Dictionary with entries `mean` for point predictions and `level_*` for probabilistic predictions.
"""
fcst = forecast_arima(self.model_, h=h, xreg=X, level=level)
mean = fcst["mean"]
res = {"mean": mean}
if level is None:
return res
level = sorted(level)
if self.prediction_intervals is not None:
res = self._add_predict_conformal_intervals(res, level)
else:
res = {
"mean": mean,
**{f"lo-{l}": fcst["lower"][f"{l}%"] for l in reversed(level)},
**{f"hi-{l}": fcst["upper"][f"{l}%"] for l in level},
}
return res
def predict_in_sample(self, level: Optional[List[int]] = None):
"""Access fitted AutoArima insample predictions.
Parameters
----------
level : List[float]
Confidence levels (0-100) for prediction intervals.
Returns
-------
forecasts : dict
Dictionary with entries `fitted` for point predictions and `level_*` for probabilistic predictions.
"""
mean = fitted_arima(self.model_)
res = {"fitted": mean}
if level is not None:
se = np.sqrt(self.model_["sigma2"])
res = _add_fitted_pi(res=res, se=se, level=level)
return res
def forecast(
self,
y: np.ndarray,
h: int,
X: Optional[np.ndarray] = None,
X_future: Optional[np.ndarray] = None,
level: Optional[List[int]] = None,
fitted: bool = False,
):
"""Memory Efficient AutoARIMA predictions.
This method avoids memory burden due from object storage.
It is analogous to `fit_predict` without storing information.
It assumes you know the forecast horizon in advance.
Parameters
----------
y : numpy.array
Clean time series of shape (n, ).
h : int
Forecast horizon.
X : array-like
Optional insample exogenpus of shape (t, n_x).
X_future : array-like
Optional exogenous of shape (h, n_x) optional exogenous.
level : List[float]
Confidence levels (0-100) for prediction intervals.
fitted : bool
Whether or not returns insample predictions.
Returns
-------
forecasts : dict
Dictionary with entries `mean` for point predictions and `level_*` for probabilistic predictions.
"""
with np.errstate(invalid="ignore"):
mod = auto_arima_f(
x=y,
d=self.d,
D=self.D,
max_p=self.max_p,
max_q=self.max_q,
max_P=self.max_P,
max_Q=self.max_Q,
max_order=self.max_order,
max_d=self.max_d,
max_D=self.max_D,
start_p=self.start_p,
start_q=self.start_q,
start_P=self.start_P,
start_Q=self.start_Q,
stationary=self.stationary,
seasonal=self.seasonal,
ic=self.ic,
stepwise=self.stepwise,
nmodels=self.nmodels,
trace=self.trace,
approximation=self.approximation,
method=self.method,
truncate=self.truncate,
xreg=X,
test=self.test,
test_kwargs=self.test_kwargs,
seasonal_test=self.seasonal_test,
seasonal_test_kwargs=self.seasonal_test_kwargs,
allowdrift=self.allowdrift,
allowmean=self.allowmean,
blambda=self.blambda,
biasadj=self.biasadj,
period=self.season_length,
)
fcst = forecast_arima(mod, h, xreg=X_future, level=level)
res = {"mean": fcst["mean"]}
if fitted:
res["fitted"] = fitted_arima(mod)
if level is not None:
level = sorted(level)
if self.prediction_intervals is not None:
res = self._add_conformal_intervals(fcst=res, y=y, X=X, level=level)
else:
res = {
**res,
**{f"lo-{l}": fcst["lower"][f"{l}%"] for l in reversed(level)},
**{f"hi-{l}": fcst["upper"][f"{l}%"] for l in level},
}
if fitted:
# add prediction intervals for fitted values
se = np.sqrt(mod["sigma2"])
res = _add_fitted_pi(res=res, se=se, level=level)
return res
def forward(
self,
y: np.ndarray,
h: int,
X: Optional[np.ndarray] = None,
X_future: Optional[np.ndarray] = None,
level: Optional[List[int]] = None,
fitted: bool = False,
):
"""Apply fitted ARIMA model to a new time series.
Parameters
----------
y : numpy.array
Clean time series of shape (n, ).
h : int
Forecast horizon.
X : array-like
Optional insample exogenous of shape (t, n_x).
X_future : array-like
Optional exogenous of shape (h, n_x).
level : List[float]
Confidence levels for prediction intervals.
fitted : bool
Whether or not returns insample predictions.
Returns
-------
forecasts : dict
Dictionary with entries `mean` for point predictions and `level_*` for probabilistic predictions.
"""
if not hasattr(self, "model_"):
raise Exception("You have to use the `fit` method first")
with np.errstate(invalid="ignore"):
mod = forward_arima(self.model_, y=y, xreg=X, method=self.method)
fcst = forecast_arima(mod, h, xreg=X_future, level=level)
res = {"mean": fcst["mean"]}
if fitted:
res["fitted"] = fitted_arima(mod)
if level is not None:
level = sorted(level)
if self.prediction_intervals is not None:
res = self._add_conformal_intervals(fcst=res, y=y, X=X, level=level)
else:
res = {
**res,
**{f"lo-{l}": fcst["lower"][f"{l}%"] for l in reversed(level)},
**{f"hi-{l}": fcst["upper"][f"{l}%"] for l in level},
}
if fitted:
# add prediction intervals for fitted values
se = np.sqrt(mod["sigma2"])
res = _add_fitted_pi(res=res, se=se, level=level)
return res
# %% ../nbs/src/core/models.ipynb 33
class AutoETS(_TS):
"""Automatic Exponential Smoothing model.
Automatically selects the best ETS (Error, Trend, Seasonality)
model using an information criterion. Default is Akaike Information Criterion (AICc), while particular models are estimated using maximum likelihood.
The state-space equations can be determined based on their $M$ multiplicative, $A$ additive,
$Z$ optimized or $N$ ommited components. The `model` string parameter defines the ETS equations:
E in [$M, A, Z$], T in [$N, A, M, Z$], and S in [$N, A, M, Z$].
For example when model='ANN' (additive error, no trend, and no seasonality), ETS will
explore only a simple exponential smoothing.
If the component is selected as 'Z', it operates as a placeholder to ask the AutoETS model
to figure out the best parameter.
Notes
-----
This implementation is a mirror of Hyndman's [forecast::ets](https://github.com/robjhyndman/forecast).
References
----------
[Rob J. Hyndman, Yeasmin Khandakar (2008). "Automatic Time Series Forecasting: The forecast package for R"](https://www.jstatsoft.org/article/view/v027i03).
[Hyndman, Rob, et al (2008). "Forecasting with exponential smoothing: the state space approach"](https://robjhyndman.com/expsmooth/).
Parameters
----------
model : str
Controlling state-space-equations.
season_length : int
Number of observations per unit of time. Ex: 24 Hourly data.
damped : bool
A parameter that 'dampens' the trend.
phi : float, optional (default=None)
Smoothing parameter for trend damping. Only used when `damped=True`.
alias : str
Custom name of the model.
prediction_intervals : Optional[ConformalIntervals],
Information to compute conformal prediction intervals.
By default, the model will compute the native prediction
intervals.
"""
def __init__(
self,
season_length: int = 1,
model: str = "ZZZ",
damped: Optional[bool] = None,
phi: Optional[float] = None,
alias: str = "AutoETS",
prediction_intervals: Optional[ConformalIntervals] = None,
):
self.season_length = season_length
self.model = model
self.damped = damped
if phi is not None:
if not isinstance(phi, float):
raise ValueError("phi must be `None` or float.")
if not _PHI_LOWER <= phi <= _PHI_UPPER:
raise ValueError(f"Valid range for phi is [{_PHI_LOWER}, {_PHI_UPPER}]")
self.phi = phi
self.alias = alias
self.prediction_intervals = prediction_intervals
def __repr__(self):
return self.alias
def fit(
self,
y: np.ndarray,
X: Optional[np.ndarray] = None,
):
"""Fit the Exponential Smoothing model.
Fit an Exponential Smoothing model to a time series (numpy array) `y`
and optionally exogenous variables (numpy array) `X`.
Parameters
----------
y : numpy.array
Clean time series of shape (t, ).
X : array-like
Optional exogenous of shape (t, n_x).
Returns
-------
self :
Exponential Smoothing fitted model.
"""
self.model_ = ets_f(
y, m=self.season_length, model=self.model, damped=self.damped, phi=self.phi
)
self.model_["actual_residuals"] = y - self.model_["fitted"]
self._store_cs(y=y, X=X)
return self
def predict(
self, h: int, X: Optional[np.ndarray] = None, level: Optional[List[int]] = None
):
"""Predict with fitted Exponential Smoothing.
Parameters
----------
h : int
Forecast horizon.
X : array-like
Optional exogenpus of shape (h, n_x).
level : List[float]
Confidence levels (0-100) for prediction intervals.
Returns
-------
forecasts : dict
Dictionary with entries `mean` for point predictions and `level_*` for probabilistic predictions.
"""
fcst = forecast_ets(self.model_, h=h, level=level)
res = {"mean": fcst["mean"]}
if level is None:
return res
level = sorted(level)
if self.prediction_intervals is not None:
res = self._add_predict_conformal_intervals(res, level)
else:
res = {
**res,
**{f"lo-{l}": fcst[f"lo-{l}"] for l in reversed(level)},
**{f"hi-{l}": fcst[f"hi-{l}"] for l in level},
}
return res
def predict_in_sample(self, level: Optional[List[int]] = None):
"""Access fitted Exponential Smoothing insample predictions.
Parameters
----------
level : List[float]
Confidence levels (0-100) for prediction intervals.
Returns
-------
forecasts : dict
Dictionary with entries `fitted` for point predictions and `level_*` for probabilistic predictions.
"""
res = {"fitted": self.model_["fitted"]}
if level is not None:
residuals = self.model_["actual_residuals"]
se = _calculate_sigma(residuals, len(residuals) - self.model_["n_params"])
res = _add_fitted_pi(res=res, se=se, level=level)
return res
def forecast(
self,
y: np.ndarray,
h: int,
X: Optional[np.ndarray] = None,
X_future: Optional[np.ndarray] = None,
level: Optional[List[int]] = None,
fitted: bool = False,
):
"""Memory Efficient Exponential Smoothing predictions.
This method avoids memory burden due from object storage.
It is analogous to `fit_predict` without storing information.
It assumes you know the forecast horizon in advance.
Parameters
----------
y : numpy.array
Clean time series of shape (n, ).
h : int
Forecast horizon.
X : array-like
Optional insample exogenpus of shape (t, n_x).
X_future : array-like
Optional exogenous of shape (h, n_x).
level : List[float]
Confidence levels (0-100) for prediction intervals.
fitted : bool
Whether or not returns insample predictions.
Returns
-------
forecasts : dict
Dictionary with entries `mean` for point predictions and `level_*` for probabilistic predictions.
"""
mod = ets_f(
y, m=self.season_length, model=self.model, damped=self.damped, phi=self.phi
)
fcst = forecast_ets(mod, h=h, level=level)
keys = ["mean"]
if fitted:
keys.append("fitted")
res = {key: fcst[key] for key in keys}
if level is not None:
level = sorted(level)
if self.prediction_intervals is not None:
res = self._add_conformal_intervals(fcst=res, y=y, X=X, level=level)
else:
res = {
**res,
**{f"lo-{l}": fcst[f"lo-{l}"] for l in reversed(level)},
**{f"hi-{l}": fcst[f"hi-{l}"] for l in level},
}
if fitted:
# add prediction intervals for fitted values
se = _calculate_sigma(y - mod["fitted"], len(y) - mod["n_params"])
res = _add_fitted_pi(res=res, se=se, level=level)
return res
def forward(
self,
y: np.ndarray,
h: int,
X: Optional[np.ndarray] = None,
X_future: Optional[np.ndarray] = None,
level: Optional[List[int]] = None,
fitted: bool = False,
):
"""Apply fitted Exponential Smoothing model to a new time series.
Parameters
----------
y : numpy.array
Clean time series of shape (n, ).
h : int
Forecast horizon.
X : array-like
Optional insample exogenpus of shape (t, n_x).
X_future : array-like
Optional exogenous of shape (h, n_x).
level : List[float]
Confidence levels for prediction intervals.
fitted : bool
Whether or not to return insample predictions.
Returns
-------
forecasts : dict
Dictionary with entries `mean` for point predictions and `level_*` for probabilistic predictions.
"""
if not hasattr(self, "model_"):
raise Exception("You have to use the `fit` method first")
mod = forward_ets(self.model_, y=y)
fcst = forecast_ets(mod, h=h, level=level)
keys = ["mean"]
if fitted:
keys.append("fitted")
res = {key: fcst[key] for key in keys}
if level is not None:
level = sorted(level)
if self.prediction_intervals is not None:
res = self._add_conformal_intervals(fcst=res, y=y, X=X, level=level)
else:
res = {
**res,
**{f"lo-{l}": fcst[f"lo-{l}"] for l in reversed(level)},
**{f"hi-{l}": fcst[f"hi-{l}"] for l in level},
}
if fitted:
# add prediction intervals for fitted values
se = _calculate_sigma(y - mod["fitted"], len(y) - mod["n_params"])
res = _add_fitted_pi(res=res, se=se, level=level)
return res
# %% ../nbs/src/core/models.ipynb 48
class ETS(AutoETS):
@classmethod
def _warn(cls):
warnings.warn(
"`ETS` will be deprecated in future versions of `StatsForecast`. Please use `AutoETS` instead.",
category=FutureWarning,
stacklevel=2,
)
def __init__(
self,
season_length: int = 1,
model: str = "ZZZ",
damped: Optional[bool] = None,
phi: Optional[float] = None,
alias: str = "ETS",
prediction_intervals: Optional[ConformalIntervals] = None,
):
ETS._warn()
super().__init__(
season_length=season_length,
model=model,
damped=damped,
phi=phi,
alias=alias,
prediction_intervals=prediction_intervals,
)
def __repr__(self):
return self.alias
# %% ../nbs/src/core/models.ipynb 53
class AutoCES(_TS):
"""Complex Exponential Smoothing model.
Automatically selects the best Complex Exponential Smoothing
model using an information criterion. Default is Akaike Information Criterion (AICc), while particular
models are estimated using maximum likelihood.
The state-space equations can be determined based on their $S$ simple, $P$ parial,
$Z$ optimized or $N$ ommited components. The `model` string parameter defines the
kind of CES model: $N$ for simple CES (withous seasonality), $S$ for simple seasonality (lagged CES),
$P$ for partial seasonality (without complex part), $F$ for full seasonality (lagged CES
with real and complex seasonal parts).
If the component is selected as 'Z', it operates as a placeholder to ask the AutoCES model
to figure out the best parameter.
References
----------
[Svetunkov, Ivan & Kourentzes, Nikolaos. (2015). "Complex Exponential Smoothing". 10.13140/RG.2.1.3757.2562. ](https://onlinelibrary.wiley.com/doi/full/10.1002/nav.22074).
Parameters
----------
model : str
Controlling state-space-equations.
season_length : int
Number of observations per unit of time. Ex: 24 Hourly data.
alias : str
Custom name of the model.
prediction_intervals : Optional[ConformalIntervals]
Information to compute conformal prediction intervals.
By default, the model will compute the native prediction
intervals.
"""
def __init__(
self,
season_length: int = 1,
model: str = "Z",
alias: str = "CES",
prediction_intervals: Optional[ConformalIntervals] = None,
):
self.season_length = season_length
self.model = model
self.alias = alias
self.prediction_intervals = prediction_intervals
def __repr__(self):
return self.alias
def fit(
self,
y: np.ndarray,
X: Optional[np.ndarray] = None,
):
"""Fit the Complex Exponential Smoothing model.
Fit the Complex Exponential Smoothing model to a time series (numpy array) `y`
and optionally exogenous variables (numpy array) `X`.
Parameters
----------
y : numpy.array
Clean time series of shape (t, ).
X : array-like
Optional exogenous of shape (t, n_x).
Returns
-------
self :
Complex Exponential Smoothing fitted model.
"""
if is_constant(y):
model = Naive(
alias=self.alias, prediction_intervals=self.prediction_intervals
)
model.fit(y=y, X=X)
return model
self.model_ = auto_ces(y, m=self.season_length, model=self.model)
self.model_["actual_residuals"] = y - self.model_["fitted"]
self._store_cs(y=y, X=X)
return self
def predict(
self, h: int, X: Optional[np.ndarray] = None, level: Optional[List[int]] = None
):
"""Predict with fitted Exponential Smoothing.
Parameters
----------
h : int
Forecast horizon.
X : array-like
Optional exogenous of shape (h, n_x).
level: List[float]
Confidence levels (0-100) for prediction intervals.
Returns
-------
forecasts : dict
Dictionary with entries `mean` for point predictions and `level_*` for probabilistic predictions.
"""
fcst = forecast_ces(self.model_, h=h, level=level)
res = {"mean": fcst["mean"]}
if level is None:
return res
level = sorted(level)