/
model.py
1818 lines (1675 loc) · 66.6 KB
/
model.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
"""
Notes
-----
Code written using below textbook as a reference.
Results are checked against the expected outcomes in the text book.
Properties:
Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and
practice. OTexts, 2014.
Author: Terence L van Zyl
Modified: Kevin Sheppard
"""
from statsmodels.compat.pandas import deprecate_kwarg
import contextlib
from typing import Any
from collections.abc import Hashable, Sequence
import warnings
import numpy as np
import pandas as pd
from scipy.optimize import basinhopping, least_squares, minimize
from scipy.special import inv_boxcox
from scipy.stats import boxcox
from statsmodels.tools.validation import (
array_like,
bool_like,
dict_like,
float_like,
int_like,
string_like,
)
from statsmodels.tsa.base.tsa_model import TimeSeriesModel
from statsmodels.tsa.exponential_smoothing.ets import (
_initialization_heuristic,
_initialization_simple,
)
from statsmodels.tsa.holtwinters import (
_exponential_smoothers as smoothers,
_smoothers as py_smoothers,
)
from statsmodels.tsa.holtwinters._exponential_smoothers import HoltWintersArgs
from statsmodels.tsa.holtwinters._smoothers import (
to_restricted,
to_unrestricted,
)
from statsmodels.tsa.holtwinters.results import (
HoltWintersResults,
HoltWintersResultsWrapper,
)
from statsmodels.tsa.tsatools import freq_to_period
SMOOTHERS = {
("mul", "add"): smoothers.holt_win_add_mul_dam,
("mul", "mul"): smoothers.holt_win_mul_mul_dam,
("mul", None): smoothers.holt_win__mul,
("add", "add"): smoothers.holt_win_add_add_dam,
("add", "mul"): smoothers.holt_win_mul_add_dam,
("add", None): smoothers.holt_win__add,
(None, "add"): smoothers.holt_add_dam,
(None, "mul"): smoothers.holt_mul_dam,
(None, None): smoothers.holt__,
}
PY_SMOOTHERS = {
("mul", "add"): py_smoothers.holt_win_add_mul_dam,
("mul", "mul"): py_smoothers.holt_win_mul_mul_dam,
("mul", None): py_smoothers.holt_win__mul,
("add", "add"): py_smoothers.holt_win_add_add_dam,
("add", "mul"): py_smoothers.holt_win_mul_add_dam,
("add", None): py_smoothers.holt_win__add,
(None, "add"): py_smoothers.holt_add_dam,
(None, "mul"): py_smoothers.holt_mul_dam,
(None, None): py_smoothers.holt__,
}
def opt_wrapper(func):
def f(*args, **kwargs):
err = func(*args, **kwargs)
if isinstance(err, np.ndarray):
return err.T @ err
return err
return f
class _OptConfig:
alpha: float
beta: float
phi: float
gamma: float
level: float
trend: float
seasonal: np.ndarray
y: np.ndarray
params: np.ndarray
mask: np.ndarray
mle_retvals: Any
def unpack_parameters(self, params) -> "_OptConfig":
self.alpha = params[0]
self.beta = params[1]
self.gamma = params[2]
self.level = params[3]
self.trend = params[4]
self.phi = params[5]
self.seasonal = params[6:]
return self
class ExponentialSmoothing(TimeSeriesModel):
"""
Holt Winter's Exponential Smoothing
Parameters
----------
endog : array_like
The time series to model.
trend : {"add", "mul", "additive", "multiplicative", None}, optional
Type of trend component.
damped_trend : bool, optional
Should the trend component be damped.
seasonal : {"add", "mul", "additive", "multiplicative", None}, optional
Type of seasonal component.
seasonal_periods : int, optional
The number of periods in a complete seasonal cycle, e.g., 4 for
quarterly data or 7 for daily data with a weekly cycle.
initialization_method : str, optional
Method for initialize the recursions. One of:
* None
* 'estimated'
* 'heuristic'
* 'legacy-heuristic'
* 'known'
None defaults to the pre-0.12 behavior where initial values
are passed as part of ``fit``. If any of the other values are
passed, then the initial values must also be set when constructing
the model. If 'known' initialization is used, then `initial_level`
must be passed, as well as `initial_trend` and `initial_seasonal` if
applicable. Default is 'estimated'. "legacy-heuristic" uses the same
values that were used in statsmodels 0.11 and earlier.
initial_level : float, optional
The initial level component. Required if estimation method is "known".
If set using either "estimated" or "heuristic" this value is used.
This allows one or more of the initial values to be set while
deferring to the heuristic for others or estimating the unset
parameters.
initial_trend : float, optional
The initial trend component. Required if estimation method is "known".
If set using either "estimated" or "heuristic" this value is used.
This allows one or more of the initial values to be set while
deferring to the heuristic for others or estimating the unset
parameters.
initial_seasonal : array_like, optional
The initial seasonal component. An array of length `seasonal`
or length `seasonal - 1` (in which case the last initial value
is computed to make the average effect zero). Only used if
initialization is 'known'. Required if estimation method is "known".
If set using either "estimated" or "heuristic" this value is used.
This allows one or more of the initial values to be set while
deferring to the heuristic for others or estimating the unset
parameters.
use_boxcox : {True, False, 'log', float}, optional
Should the Box-Cox transform be applied to the data first? If 'log'
then apply the log. If float then use the value as lambda.
bounds : dict[str, tuple[float, float]], optional
An dictionary containing bounds for the parameters in the model,
excluding the initial values if estimated. The keys of the dictionary
are the variable names, e.g., smoothing_level or initial_slope.
The initial seasonal variables are labeled initial_seasonal.<j>
for j=0,...,m-1 where m is the number of period in a full season.
Use None to indicate a non-binding constraint, e.g., (0, None)
constrains a parameter to be non-negative.
dates : array_like of datetime, optional
An array-like object of datetime objects. If a Pandas object is given
for endog, it is assumed to have a DateIndex.
freq : str, optional
The frequency of the time-series. A Pandas offset or 'B', 'D', 'W',
'M', 'A', or 'Q'. This is optional if dates are given.
missing : str
Available options are 'none', 'drop', and 'raise'. If 'none', no nan
checking is done. If 'drop', any observations with nans are dropped.
If 'raise', an error is raised. Default is 'none'.
Notes
-----
This is a full implementation of the holt winters exponential smoothing as
per [1]_. This includes all the unstable methods as well as the stable
methods. The implementation of the library covers the functionality of the
R library as much as possible whilst still being Pythonic.
See the notebook `Exponential Smoothing
<../examples/notebooks/generated/exponential_smoothing.html>`__
for an overview.
References
----------
.. [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles
and practice. OTexts, 2014.
"""
@deprecate_kwarg("damped", "damped_trend")
def __init__(
self,
endog,
trend=None,
damped_trend=False,
seasonal=None,
*,
seasonal_periods=None,
initialization_method="estimated",
initial_level=None,
initial_trend=None,
initial_seasonal=None,
use_boxcox=False,
bounds=None,
dates=None,
freq=None,
missing="none",
):
super().__init__(endog, None, dates, freq, missing=missing)
self._y = self._data = array_like(
endog, "endog", ndim=1, contiguous=True, order="C"
)
options = ("add", "mul", "additive", "multiplicative")
trend = string_like(trend, "trend", options=options, optional=True)
if trend in ["additive", "multiplicative"]:
trend = {"additive": "add", "multiplicative": "mul"}[trend]
self.trend = trend
self.damped_trend = bool_like(damped_trend, "damped_trend")
seasonal = string_like(
seasonal, "seasonal", options=options, optional=True
)
if seasonal in ["additive", "multiplicative"]:
seasonal = {"additive": "add", "multiplicative": "mul"}[seasonal]
self.seasonal = seasonal
self.has_trend = trend in ["mul", "add"]
self.has_seasonal = seasonal in ["mul", "add"]
if (self.trend == "mul" or self.seasonal == "mul") and not np.all(
self._data > 0.0
):
raise ValueError(
"endog must be strictly positive when using"
"multiplicative trend or seasonal components."
)
if self.damped_trend and not self.has_trend:
raise ValueError("Can only dampen the trend component")
if self.has_seasonal:
self.seasonal_periods = int_like(
seasonal_periods, "seasonal_periods", optional=True
)
if seasonal_periods is None:
try:
self.seasonal_periods = freq_to_period(self._index_freq)
except Exception:
raise ValueError(
"seasonal_periods has not been provided and index "
"does not have a known freq. You must provide "
"seasonal_periods"
)
if self.seasonal_periods <= 1:
raise ValueError("seasonal_periods must be larger than 1.")
assert self.seasonal_periods is not None
else:
self.seasonal_periods = 0
self.nobs = len(self.endog)
options = ("known", "estimated", "heuristic", "legacy-heuristic")
self._initialization_method = string_like(
initialization_method,
"initialization_method",
optional=False,
options=options,
)
self._initial_level = float_like(
initial_level, "initial_level", optional=True
)
self._initial_trend = float_like(
initial_trend, "initial_trend", optional=True
)
self._initial_seasonal = array_like(
initial_seasonal, "initial_seasonal", optional=True
)
estimated = self._initialization_method == "estimated"
self._estimate_level = estimated
self._estimate_trend = estimated and self.trend is not None
self._estimate_seasonal = estimated and self.seasonal is not None
self._bounds = self._check_bounds(bounds)
self._use_boxcox = use_boxcox
self._lambda = np.nan
self._y = self._boxcox()
self._initialize()
self._fixed_parameters = {}
def _check_bounds(self, bounds):
bounds = dict_like(bounds, "bounds", optional=True)
if bounds is None:
return
msg = (
"bounds must be a dictionary of 2-element tuples of the form"
" (lb, ub) where lb < ub, lb>=0 and ub<=1"
)
variables = self._ordered_names()
for key in bounds:
if key not in variables:
supported = ", ".join(variables[:-1])
supported += ", and " + variables[-1]
raise KeyError(
f"{key} does not match the list of supported variables "
f"names: {supported}."
)
bound = bounds[key]
if not isinstance(bound, tuple):
raise TypeError(msg)
lb = bound[0] if bound[0] is not None else -np.inf
ub = bound[1] if bound[1] is not None else np.inf
if len(bound) != 2 or lb >= ub:
raise ValueError(msg)
if ("smoothing" in key or "damp" in key) and (
bound[0] < 0.0 or bound[1] > 1.0
):
raise ValueError(
f"{key} must have a lower bound >= 0.0 and <= 1.0"
)
return bounds
def _boxcox(self):
if self._use_boxcox is None or self._use_boxcox is False:
self._lambda = np.nan
return self._y
if self._use_boxcox is True:
y, self._lambda = boxcox(self._y)
elif isinstance(self._use_boxcox, (int, float)):
self._lambda = float(self._use_boxcox)
y = boxcox(self._y, self._use_boxcox)
else:
raise TypeError("use_boxcox must be True, False or a float.")
return y
@contextlib.contextmanager
def fix_params(self, values):
"""
Temporarily fix parameters for estimation.
Parameters
----------
values : dict
Values to fix. The key is the parameter name and the value is the
fixed value.
Yields
------
None
No value returned.
Examples
--------
>>> from statsmodels.datasets.macrodata import load_pandas
>>> data = load_pandas()
>>> import statsmodels.tsa.api as tsa
>>> mod = tsa.ExponentialSmoothing(data.data.realcons, trend="add",
... initialization_method="estimated")
>>> with mod.fix_params({"smoothing_level": 0.2}):
... mod.fit()
"""
values = dict_like(values, "values")
valid_keys = ("smoothing_level",)
if self.has_trend:
valid_keys += ("smoothing_trend",)
if self.has_seasonal:
valid_keys += ("smoothing_seasonal",)
m = self.seasonal_periods
valid_keys += tuple([f"initial_seasonal.{i}" for i in range(m)])
if self.damped_trend:
valid_keys += ("damping_trend",)
if self._initialization_method in ("estimated", None):
extra_keys = [
key.replace("smoothing_", "initial_")
for key in valid_keys
if "smoothing_" in key
]
valid_keys += tuple(extra_keys)
for key in values:
if key not in valid_keys:
valid = ", ".join(valid_keys[:-1]) + ", and " + valid_keys[-1]
raise KeyError(
f"{key} if not allowed. Only {valid} are supported in "
"this specification."
)
if "smoothing_level" in values:
alpha = values["smoothing_level"]
if alpha <= 0.0:
raise ValueError("smoothing_level must be in (0, 1)")
beta = values.get("smoothing_trend", 0.0)
if beta > alpha:
raise ValueError("smoothing_trend must be <= smoothing_level")
gamma = values.get("smoothing_seasonal", 0.0)
if gamma > 1 - alpha:
raise ValueError(
"smoothing_seasonal must be <= 1 - smoothing_level"
)
try:
self._fixed_parameters = values
yield
finally:
self._fixed_parameters = {}
def _initialize(self):
if self._initialization_method == "known":
return self._initialize_known()
msg = (
f"initialization method is {self._initialization_method} but "
"initial_{0} has been set."
)
if self._initial_level is not None:
raise ValueError(msg.format("level"))
if self._initial_trend is not None:
raise ValueError(msg.format("trend"))
if self._initial_seasonal is not None:
raise ValueError(msg.format("seasonal"))
if self._initialization_method == "legacy-heuristic":
return self._initialize_legacy()
elif self._initialization_method == "heuristic":
return self._initialize_heuristic()
elif self._initialization_method == "estimated":
if self.nobs < 10 + 2 * (self.seasonal_periods // 2):
return self._initialize_simple()
else:
return self._initialize_heuristic()
def _initialize_simple(self):
trend = self.trend if self.has_trend else False
seasonal = self.seasonal if self.has_seasonal else False
lvl, trend, seas = _initialization_simple(
self._y, trend, seasonal, self.seasonal_periods
)
self._initial_level = lvl
self._initial_trend = trend
self._initial_seasonal = seas
def _initialize_heuristic(self):
trend = self.trend if self.has_trend else False
seasonal = self.seasonal if self.has_seasonal else False
lvl, trend, seas = _initialization_heuristic(
self._y, trend, seasonal, self.seasonal_periods
)
self._initial_level = lvl
self._initial_trend = trend
self._initial_seasonal = seas
def _initialize_legacy(self):
lvl, trend, seasonal = self.initial_values(force=True)
self._initial_level = lvl
self._initial_trend = trend
self._initial_seasonal = seasonal
def _initialize_known(self):
msg = "initialization is 'known' but initial_{0} not given"
if self._initial_level is None:
raise ValueError(msg.format("level"))
excess = "initial_{0} set but model has no {0} component"
if self.has_trend and self._initial_trend is None:
raise ValueError(msg.format("trend"))
elif not self.has_trend and self._initial_trend is not None:
raise ValueError(excess.format("trend"))
if self.has_seasonal and self._initial_seasonal is None:
raise ValueError(msg.format("seasonal"))
elif not self.has_seasonal and self._initial_seasonal is not None:
raise ValueError(excess.format("seasonal"))
def predict(self, params, start=None, end=None):
"""
In-sample and out-of-sample prediction.
Parameters
----------
params : ndarray
The fitted model parameters.
start : int, str, or datetime
Zero-indexed observation number at which to start forecasting, ie.,
the first forecast is start. Can also be a date string to
parse or a datetime type.
end : int, str, or datetime
Zero-indexed observation number at which to end forecasting, ie.,
the first forecast is start. Can also be a date string to
parse or a datetime type.
Returns
-------
ndarray
The predicted values.
"""
if start is None:
freq = getattr(self._index, "freq", 1)
if isinstance(freq, int):
start = self._index.shape[0]
else:
start = self._index[-1] + freq
start, end, out_of_sample, _ = self._get_prediction_index(
start=start, end=end
)
if out_of_sample > 0:
res = self._predict(h=out_of_sample, **params)
else:
res = self._predict(h=0, **params)
return res.fittedfcast[start : end + out_of_sample + 1]
def _enforce_bounds(self, p, sel, lb, ub):
initial_p = p[sel]
# Ensure strictly inbounds
loc = initial_p <= lb
upper = ub[loc].copy()
upper[~np.isfinite(upper)] = 100.0
eps = 1e-4
initial_p[loc] = lb[loc] + eps * (upper - lb[loc])
loc = initial_p >= ub
lower = lb[loc].copy()
lower[~np.isfinite(lower)] = -100.0
eps = 1e-4
initial_p[loc] = ub[loc] - eps * (ub[loc] - lower)
return initial_p
@staticmethod
def _check_blocked_keywords(
d: dict, keys: Sequence[Hashable], name="kwargs"
):
for key in keys:
if key in d:
raise ValueError(f"{name} must not contain '{key}'")
def _check_bound_feasibility(self, bounds):
if bounds[1][0] > bounds[0][1]:
raise ValueError(
"The bounds for smoothing_trend and smoothing_level are "
"incompatible since smoothing_trend <= smoothing_level."
)
if bounds[2][0] > (1 - bounds[0][1]):
raise ValueError(
"The bounds for smoothing_seasonal and smoothing_level "
"are incompatible since smoothing_seasonal <= "
"1 - smoothing_level."
)
@staticmethod
def _setup_brute(sel, bounds, alpha):
# More points when fewer parameters
ns = 87 // sel[:3].sum()
if not sel[0]:
# Easy case since no cross-constraints
nparams = int(sel[1]) + int(sel[2])
args = []
for i in range(1, 3):
if sel[i]:
bound = bounds[i]
step = bound[1] - bound[0]
lb = bound[0] + 0.005 * step
if i == 1:
ub = min(bound[1], alpha) - 0.005 * step
else:
ub = min(bound[1], 1 - alpha) - 0.005 * step
args.append(np.linspace(lb, ub, ns))
points = np.stack(np.meshgrid(*args))
points = points.reshape((nparams, -1)).T
return np.ascontiguousarray(points)
bound = bounds[0]
step = 0.005 * (bound[1] - bound[0])
points = np.linspace(bound[0] + step, bound[1] - step, ns)
if not sel[1] and not sel[2]:
return points[:, None]
combined = []
b_bounds = bounds[1]
g_bounds = bounds[2]
if sel[1] and sel[2]:
for a in points:
b_lb = b_bounds[0]
b_ub = min(b_bounds[1], a)
g_lb = g_bounds[0]
g_ub = min(g_bounds[1], 1 - a)
if b_lb > b_ub or g_lb > g_ub:
# infeasible point
continue
nb = int(np.ceil(ns * np.sqrt(a)))
ng = int(np.ceil(ns * np.sqrt(1 - a)))
b = np.linspace(b_lb, b_ub, nb)
g = np.linspace(g_lb, g_ub, ng)
both = np.stack(np.meshgrid(b, g)).reshape(2, -1).T
final = np.empty((both.shape[0], 3))
final[:, 0] = a
final[:, 1:] = both
combined.append(final)
elif sel[1]:
for a in points:
b_lb = b_bounds[0]
b_ub = min(b_bounds[1], a)
if b_lb > b_ub:
# infeasible point
continue
nb = int(np.ceil(ns * np.sqrt(a)))
final = np.empty((nb, 2))
final[:, 0] = a
final[:, 1] = np.linspace(b_lb, b_ub, nb)
combined.append(final)
else: # sel[2]
for a in points:
g_lb = g_bounds[0]
g_ub = min(g_bounds[1], 1 - a)
if g_lb > g_ub:
# infeasible point
continue
ng = int(np.ceil(ns * np.sqrt(1 - a)))
final = np.empty((ng, 2))
final[:, 1] = np.linspace(g_lb, g_ub, ng)
final[:, 0] = a
combined.append(final)
return np.vstack(combined)
def _ordered_names(self):
names = (
"smoothing_level",
"smoothing_trend",
"smoothing_seasonal",
"initial_level",
"initial_trend",
"damping_trend",
)
m = self.seasonal_periods
names += tuple([f"initial_seasonal.{i}" for i in range(m)])
return names
def _update_for_fixed(self, sel, alpha, beta, gamma, phi, l0, b0, s0):
if self._fixed_parameters:
fixed = self._fixed_parameters
names = self._ordered_names()
not_fixed = np.array([name not in fixed for name in names])
if (~sel[~not_fixed]).any():
invalid = []
for name, s, nf in zip(names, sel, not_fixed):
if not s and not nf:
invalid.append(name)
invalid_names = ", ".join(invalid)
raise ValueError(
"Cannot fix a parameter that is not being "
f"estimated: {invalid_names}"
)
sel &= not_fixed
alpha = fixed.get("smoothing_level", alpha)
beta = fixed.get("smoothing_trend", beta)
gamma = fixed.get("smoothing_seasonal", gamma)
phi = fixed.get("damping_trend", phi)
l0 = fixed.get("initial_level", l0)
b0 = fixed.get("initial_trend", b0)
for i in range(self.seasonal_periods):
s0[i] = fixed.get(f"initial_seasonal.{i}", s0[i])
return sel, alpha, beta, gamma, phi, l0, b0, s0
def _construct_bounds(self):
trend_lb = 0.0 if self.trend == "mul" else None
season_lb = 0.0 if self.seasonal == "mul" else None
lvl_lb = None if trend_lb is None and season_lb is None else 0.0
bounds = [
(0.0, 1.0), # alpha
(0.0, 1.0), # beta
(0.0, 1.0), # gamma
(lvl_lb, None), # level
(trend_lb, None), # trend
(0.8, 0.995), # phi
]
bounds += [(season_lb, None)] * self.seasonal_periods
if self._bounds is not None:
assert isinstance(self._bounds, dict)
for i, name in enumerate(self._ordered_names()):
bounds[i] = self._bounds.get(name, bounds[i])
# Update bounds to account for fixed parameters
fixed = self._fixed_parameters
if "smoothing_level" in fixed:
# Update bounds if fixed alpha
alpha = fixed["smoothing_level"]
# beta <= alpha
if bounds[1][1] > alpha:
bounds[1] = (bounds[1][0], alpha)
# gamma <= 1 - alpha
if bounds[2][1] > (1 - alpha):
bounds[2] = (bounds[2][0], 1 - alpha)
# gamma <= 1 - alpha
if "smoothing_trend" in fixed:
# beta <= alpha
beta = fixed["smoothing_trend"]
bounds[0] = (max(beta, bounds[0][0]), bounds[0][1])
if "smoothing_seasonal" in fixed:
gamma = fixed["smoothing_seasonal"]
# gamma <= 1 - alpha => alpha <= 1 - gamma
bounds[0] = (bounds[0][0], min(1 - gamma, bounds[0][1]))
# Ensure bounds are feasible
for i, name in enumerate(self._ordered_names()):
lb = bounds[i][0] if bounds[i][0] is not None else -np.inf
ub = bounds[i][1] if bounds[i][1] is not None else np.inf
if lb >= ub:
raise ValueError(
"After adjusting for user-provided bounds fixed values, "
f"the resulting set of bounds for {name}, {bounds[i]}, "
"are infeasible."
)
self._check_bound_feasibility(bounds)
return bounds
def _get_starting_values(
self,
params,
start_params,
use_brute,
sel,
hw_args,
bounds,
alpha,
func,
):
if start_params is None and use_brute and np.any(sel[:3]):
# Have a quick look in the region for a good starting place for
# alpha, beta & gamma using fixed values for initial
m = self.seasonal_periods
sv_sel = np.array([False] * (6 + m))
sv_sel[:3] = True
sv_sel &= sel
hw_args.xi = sv_sel.astype(int)
hw_args.transform = False
# Setup the grid points, respecting constraints
points = self._setup_brute(sv_sel, bounds, alpha)
opt = opt_wrapper(func)
best_val = np.inf
best_params = points[0]
for point in points:
val = opt(point, hw_args)
if val < best_val:
best_params = point
best_val = val
params[sv_sel] = best_params
elif start_params is not None:
if len(start_params) != sel.sum():
msg = "start_params must have {0} values but has {1}."
nxi, nsp = len(sel), len(start_params)
raise ValueError(msg.format(nxi, nsp))
params[sel] = start_params
return params
def _optimize_parameters(
self, data: _OptConfig, use_brute, method, kwargs
) -> _OptConfig:
# Prepare starting values
alpha = data.alpha
beta = data.beta
phi = data.phi
gamma = data.gamma
y = data.y
start_params = data.params
has_seasonal = self.has_seasonal
has_trend = self.has_trend
trend = self.trend
seasonal = self.seasonal
damped_trend = self.damped_trend
m = self.seasonal_periods
params = np.zeros(6 + m)
l0, b0, s0 = self.initial_values(
initial_level=data.level, initial_trend=data.trend
)
init_alpha = alpha if alpha is not None else 0.5 / max(m, 1)
init_beta = beta
if beta is None and has_trend:
init_beta = 0.1 * init_alpha
init_gamma = gamma
if has_seasonal and gamma is None:
init_gamma = 0.05 * (1 - init_alpha)
init_phi = phi if phi is not None else 0.99
# Selection of parameters to optimize
sel = np.array(
[
alpha is None,
has_trend and beta is None,
has_seasonal and gamma is None,
self._estimate_level,
self._estimate_trend,
damped_trend and phi is None,
]
+ [has_seasonal and self._estimate_seasonal] * m,
)
(
sel,
init_alpha,
init_beta,
init_gamma,
init_phi,
l0,
b0,
s0,
) = self._update_for_fixed(
sel, init_alpha, init_beta, init_gamma, init_phi, l0, b0, s0
)
func = SMOOTHERS[(seasonal, trend)]
params[:6] = [init_alpha, init_beta, init_gamma, l0, b0, init_phi]
if m:
params[-m:] = s0
if not np.any(sel):
from statsmodels.tools.sm_exceptions import EstimationWarning
message = (
"Model has no free parameters to estimate. Set "
"optimized=False to suppress this warning"
)
warnings.warn(message, EstimationWarning, stacklevel=3)
data = data.unpack_parameters(params)
data.params = params
data.mask = sel
return data
orig_bounds = self._construct_bounds()
bounds = np.array(orig_bounds[:3], dtype=float)
hw_args = HoltWintersArgs(
sel.astype(int), params, bounds, y, m, self.nobs
)
params = self._get_starting_values(
params,
start_params,
use_brute,
sel,
hw_args,
bounds,
init_alpha,
func,
)
# We always use [0, 1] for a, b and g and handle transform inside
mod_bounds = [(0, 1)] * 3 + orig_bounds[3:]
relevant_bounds = [bnd for bnd, flag in zip(mod_bounds, sel) if flag]
bounds = np.array(relevant_bounds, dtype=float)
lb, ub = bounds.T
lb[np.isnan(lb)] = -np.inf
ub[np.isnan(ub)] = np.inf
hw_args.xi = sel.astype(int)
# Ensure strictly inbounds
initial_p = self._enforce_bounds(params, sel, lb, ub)
# Transform to unrestricted space
params[sel] = initial_p
params[:3] = to_unrestricted(params, sel, hw_args.bounds)
initial_p = params[sel]
# Ensure parameters are transformed internally
hw_args.transform = True
if method in ("least_squares", "ls"):
# Least squares uses a different format for bounds
ls_bounds = lb, ub
self._check_blocked_keywords(kwargs, ("args", "bounds"))
res = least_squares(
func, initial_p, bounds=ls_bounds, args=(hw_args,), **kwargs
)
success = res.success
elif method in ("basinhopping", "bh"):
# Take a deeper look in the local minimum we are in to find the
# best solution to parameters, maybe hop around to try escape the
# local minimum we may be in.
minimizer_kwargs = {"args": (hw_args,), "bounds": relevant_bounds}
kwargs = kwargs.copy()
if "minimizer_kwargs" in kwargs:
self._check_blocked_keywords(
kwargs["minimizer_kwargs"],
("args", "bounds"),
name="kwargs['minimizer_kwargs']",
)
minimizer_kwargs.update(kwargs["minimizer_kwargs"])
del kwargs["minimizer_kwargs"]
default_kwargs = {
"minimizer_kwargs": minimizer_kwargs,
"stepsize": 0.01,
}
default_kwargs.update(kwargs)
obj = opt_wrapper(func)
res = basinhopping(obj, initial_p, **default_kwargs)
success = res.lowest_optimization_result.success
else:
obj = opt_wrapper(func)
self._check_blocked_keywords(kwargs, ("args", "bounds", "method"))
res = minimize(
obj,
initial_p,
args=(hw_args,),
bounds=relevant_bounds,
method=method,
**kwargs,
)
success = res.success
# finally transform to restricted space
params[sel] = res.x
params[:3] = to_restricted(params, sel, hw_args.bounds)
res.x = params[sel]
if not success:
from statsmodels.tools.sm_exceptions import ConvergenceWarning
warnings.warn(
"Optimization failed to converge. Check mle_retvals.",
ConvergenceWarning,
)
params[sel] = res.x
data.unpack_parameters(params)
data.params = params
data.mask = sel
data.mle_retvals = res
return data
@deprecate_kwarg("smoothing_slope", "smoothing_trend")
@deprecate_kwarg("initial_slope", "initial_trend")
@deprecate_kwarg("damping_slope", "damping_trend")
def fit(
self,
smoothing_level=None,
smoothing_trend=None,
smoothing_seasonal=None,
damping_trend=None,
*,
optimized=True,
remove_bias=False,
start_params=None,
method=None,
minimize_kwargs=None,
use_brute=True,
use_boxcox=None,
use_basinhopping=None,
initial_level=None,
initial_trend=None,
):
"""
Fit the model
Parameters
----------
smoothing_level : float, optional
The alpha value of the simple exponential smoothing, if the value
is set then this value will be used as the value.
smoothing_trend : float, optional
The beta value of the Holt's trend method, if the value is
set then this value will be used as the value.
smoothing_seasonal : float, optional
The gamma value of the holt winters seasonal method, if the value
is set then this value will be used as the value.
damping_trend : float, optional
The phi value of the damped method, if the value is
set then this value will be used as the value.
optimized : bool, optional
Estimate model parameters by maximizing the log-likelihood.
remove_bias : bool, optional
Remove bias from forecast values and fitted values by enforcing
that the average residual is equal to zero.
start_params : array_like, optional
Starting values to used when optimizing the fit. If not provided,
starting values are determined using a combination of grid search
and reasonable values based on the initial values of the data. See
the notes for the structure of the model parameters.
method : str, default "L-BFGS-B"
The minimizer used. Valid options are "L-BFGS-B" , "TNC",
"SLSQP" (default), "Powell", "trust-constr", "basinhopping" (also
"bh") and "least_squares" (also "ls"). basinhopping tries multiple
starting values in an attempt to find a global minimizer in
non-convex problems, and so is slower than the others.
minimize_kwargs : dict[str, Any]
A dictionary of keyword arguments passed to SciPy's minimize
function if method is one of "L-BFGS-B", "TNC",
"SLSQP", "Powell", or "trust-constr", or SciPy's basinhopping
or least_squares functions. The valid keywords are optimizer
specific. Consult SciPy's documentation for the full set of
options.
use_brute : bool, optional
Search for good starting values using a brute force (grid)
optimizer. If False, a naive set of starting values is used.
use_boxcox : {True, False, 'log', float}, optional
Should the Box-Cox transform be applied to the data first? If 'log'
then apply the log. If float then use the value as lambda.
.. deprecated:: 0.12