-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
tsfit.py
1030 lines (889 loc) · 32.8 KB
/
tsfit.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
from __future__ import annotations
import math
import warnings
from numbers import Integral
import numpy as np
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.metrics import r2_score
from sklearn.utils.validation import check_is_fitted
from tsbootstrap.ranklags import RankLags
from tsbootstrap.time_series_model import TimeSeriesModel
from tsbootstrap.utils.types import (
ModelTypes,
OrderTypes,
OrderTypesWithoutNone,
)
from tsbootstrap.utils.validate import (
validate_literal_type,
validate_X,
validate_X_and_y,
)
class TSFit(BaseEstimator, RegressorMixin):
"""
Performs fitting for various time series models including 'ar', 'arima', 'sarima', 'var', and 'arch'.
Attributes
----------
rescale_factors : dict
Rescaling factors for the input data and exogenous variables.
model : Union[AutoRegResultsWrapper, ARIMAResultsWrapper, SARIMAXResultsWrapper, VARResultsWrapper, ARCHModelResult]
The fitted model.
Methods
-------
fit(X, y=None)
Fit the chosen model to the data.
get_coefs()
Return the coefficients of the fitted model.
get_intercepts()
Return the intercepts of the fitted model.
get_residuals()
Return the residuals of the fitted model.
get_fitted_X()
Return the fitted values of the model.
get_order()
Return the order of the fitted model.
predict(X, n_steps=1)
Predict future values using the fitted model.
score(X, y_true)
Compute the R-squared score for the fitted model.
Raises
------
ValueError
If the model type or the model order is invalid.
Notes
-----
The following table shows the valid model types and their corresponding orders.
+--------+-------------------+-------------------+
| Model | Valid orders | Invalid orders |
+========+===================+===================+
| 'ar' | int | list, tuple |
+--------+-------------------+-------------------+
| 'arima'| tuple of length 3 | int, list, tuple |
+--------+-------------------+-------------------+
| 'sarima'| tuple of length 4| int, list, tuple |
+--------+-------------------+-------------------+
| 'var' | int | list, tuple |
+--------+-------------------+-------------------+
| 'arch' | int | list, tuple |
+--------+-------------------+-------------------+
Examples
--------
>>> from tsbootstrap import TSFit
>>> import numpy as np
>>> X = np.random.normal(size=(100, 1))
>>> fit_obj = TSFit(order=2, model_type='ar') # doctest: +SKIP
>>> fit_obj.fit(X) # doctest: +SKIP
TSFit(order=2, model_type='ar')
>>> fit_obj.get_coefs() # doctest: +SKIP
array([[ 0.003, -0.002]])
>>> fit_obj.get_intercepts() # doctest: +SKIP
array([0.001])
>>> fit_obj.get_residuals() # doctest: +SKIP
array([[ 0.001],
[-0.002],
[-0.002],
[-0.002],
[-0.002], ...
>>> fit_obj.get_fitted_X() # doctest: +SKIP
array([[ 0.001],
[-0.002],
[-0.002],
[-0.002],
[-0.002], ...
>>> fit_obj.get_order() # doctest: +SKIP
2
>>> fit_obj.predict(X, n_steps=5) # doctest: +SKIP
array([[ 0.001],
[-0.002],
[-0.002],
[-0.002],
[-0.002], ...
>>> fit_obj.score(X, X) # doctest: +SKIP
0.999
"""
_tags = {"python_dependencies": ["arch", "statsmodels"]}
def __init__(
self, order: OrderTypesWithoutNone, model_type: ModelTypes, **kwargs
) -> None:
"""
Initialize the TSFit object.
Parameters
----------
order : int, List[int], Tuple[int, int, int], Tuple[int, int, int, int]
Order of the model.
model_type : str
Type of the model.
**kwargs
Additional parameters to be passed to the model.
Raises
------
ValueError
If the model type or the model order is invalid.
"""
self.model_type = model_type
self.order = order
self.rescale_factors = {}
self.model_params = kwargs
@property
def model_type(self) -> str:
"""The type of the model."""
return self._model_type
@model_type.setter
def model_type(self, value: ModelTypes) -> None:
"""Set the model type."""
validate_literal_type(value, ModelTypes)
value = value.lower()
self._model_type = value
@property
def order(self) -> OrderTypesWithoutNone:
"""The order of the model."""
return self._order
@order.setter
def order(self, value) -> None:
"""Set the order of the model."""
if not isinstance(value, (Integral, list, tuple)): # noqa: UP038
raise TypeError(
f"Invalid order '{value}', should be an integer, list, or tuple."
)
if isinstance(value, list) and len(value) > 1:
value_orig = value
value = sorted(value)
if value != value_orig:
warning_msg = f"Order '{value_orig}' is a list. Sorting the list to '{value}'."
warnings.warn(warning_msg, stacklevel=2)
if isinstance(value, (list, tuple)) and len(value) == 0: # noqa: UP038
raise ValueError(
f"Invalid order '{value}', should be a non-empty list/tuple."
)
if isinstance(value, tuple) and self.model_type not in [
"arima",
"sarima",
]:
raise ValueError(
f"Invalid order '{value}', should be an integer for model type '{self.model_type}'"
)
if isinstance(value, Integral) and self.model_type in {
"sarima",
"arima",
}:
if self.model_type == "sarima":
value = (value, 0, 0, value + 1)
warning_msg = f"{self.model_type.upper()} model requires a tuple of order (p, d, q, s), where d is the order of differencing and s is the seasonal period. Setting d=0, q=0, and s=2."
else:
value = (value, 0, 0)
warning_msg = f"{self.model_type.upper()} model requires a tuple of order (p, d, q), where d is the order of differencing. Setting d=0, q=0."
warnings.warn(warning_msg, stacklevel=2)
self._order = value
def get_params(self, deep=True):
"""
Get parameters for this estimator.
Parameters
----------
deep : bool, optional
When set to True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns
-------
dict
Parameter names mapped to their values.
"""
return {
"order": self.order,
"model_type": self.model_type,
**self.model_params,
}
def set_params(self, **params):
"""
Set the parameters of this estimator.
Parameters
----------
**params
Estimator parameters.
"""
for key, value in params.items():
if hasattr(self, key):
setattr(self, key, value)
else:
self.model_params[key] = value
return self
'''
def __repr__(self):
"""
Official string representation of a TSFit object.
"""
return f"TSFit(order={self.order}, model_type='{self.model_type}')"
'''
def fit(self, X: np.ndarray, y=None) -> TSFit:
"""
Fit the chosen model to the data.
Parameters
----------
X : np.ndarray
Input data of shape (n_timepoints, n_features).
y : np.ndarray, optional
Exogenous variables, by default None.
Returns
-------
TSFit
The fitted TSFit object.
Raises
------
ValueError
If the model type or the model order is invalid.
RuntimeError
If the maximum number of iterations is reached before the variance is within the desired range.
"""
# Check if the input shapes are valid
X, y = validate_X_and_y(
X,
y,
model_is_var=self.model_type == "var",
model_is_arch=self.model_type == "arch",
)
def _rescale_inputs(X: np.ndarray, y=None):
"""
Rescale the inputs to ensure that the variance of the input data is within the interval [1, 1000].
Parameters
----------
X : np.ndarray
The input data.
y : np.ndarray, optional
The exogenous variables, by default None.
Returns
-------
Tuple[np.ndarray, np.ndarray, Tuple[float, List[float] | None]]
A tuple containing the rescaled input data, the rescaled exogenous variables, and the rescaling factors used.
Raises
------
RuntimeError
If the maximum number of iterations is reached before the variance is within the desired range.
"""
def rescale_array(arr: np.ndarray, max_iter: int = 100):
"""
Iteratively rescales an array to ensure its variance is within the interval [1, 1000].
Parameters
----------
arr : np.ndarray
The input array to be rescaled.
max_iter : int, optional
The maximum number of iterations for rescaling, by default 100.
Returns
-------
Tuple[np.ndarray, float]
A tuple containing the rescaled array and the total rescaling factor used.
Raises
------
RuntimeError
If the maximum number of iterations is reached before the variance is within the desired range.
"""
variance = np.var(arr)
if math.isclose(variance, 0, abs_tol=0.01):
raise RuntimeError(
"Variance of the input data is 0. Cannot rescale the input data."
)
total_rescale_factor = 1
iterations = 0
while not 1 <= variance <= 1000:
if iterations >= max_iter:
raise RuntimeError(
f"Maximum iterations ({max_iter}) reached. Variance is still not in the range [1, 1000]. Variance = {variance}. Results from the ARCH/GARCH model can not be trusted."
)
rescale_factor = np.sqrt(100 / variance)
arr = arr * rescale_factor
total_rescale_factor *= rescale_factor
variance = np.var(arr)
iterations += 1
return arr, total_rescale_factor
X, x_rescale_factor = rescale_array(X)
if y is not None:
y_rescale_factors = []
for i in range(y.shape[1]):
y[:, i], factor = rescale_array(y[:, i])
y_rescale_factors.append(factor)
else:
y_rescale_factors = None
return X, y, (x_rescale_factor, y_rescale_factors)
fit_func = TimeSeriesModel(X=X, y=y, model_type=self.model_type)
self.model = fit_func.fit(order=self.order, **self.model_params)
if self.model_type == "arch":
(
X,
y,
(x_rescale_factor, y_rescale_factors),
) = _rescale_inputs(X, y)
self.rescale_factors["x"] = x_rescale_factor
self.rescale_factors["y"] = y_rescale_factors
return self
def get_coefs(self) -> np.ndarray:
"""
Return the coefficients of the fitted model.
Returns
-------
np.ndarray
The coefficients of the fitted model.
Raises
------
NotFittedError
If the model is not fitted.
Notes
-----
The shape of the coefficients depends on the model type.
+--------+---------------------------------+
| Model | Coefficient shape |
+========+=================================+
| 'ar' | (1, order) |
+--------+---------------------------------+
| 'arima'| (1, order) |
+--------+---------------------------------+
| 'sarima'| (1, order) |
+--------+---------------------------------+
| 'var' | (n_features, n_features, order) |
+--------+---------------------------------+
| 'arch' | (1, order) |
+--------+---------------------------------+
"""
# Check if the model is already fitted
check_is_fitted(self, ["model"])
if self.model_type != "arch":
n_features = (
self.model.model.endog.shape[1]
if len(self.model.model.endog.shape) > 1
else 1
)
else:
n_features = (
self.model.model.y.shape[1]
if len(self.model.model.y.shape) > 1
else 1
)
return self._get_coefs_helper(self.model, n_features)
def get_intercepts(self) -> np.ndarray:
"""
Return the intercepts of the fitted model.
Returns
-------
np.ndarray
The intercepts of the fitted model.
Raises
------
NotFittedError
If the model is not fitted.
Notes
-----
The shape of the intercepts depends on the model type.
+--------+---------------------------+
| Model | Intercept shape |
+========+===========================+
| 'ar' | (1, trend_terms) |
+--------+---------------------------+
| 'arima'| (1, trend_terms) |
+--------+---------------------------+
| 'sarima'| (1, trend_terms) |
+--------+---------------------------+
| 'var' | (n_features, trend_terms) |
+--------+---------------------------+
| 'arch' | (0,) |
+--------+---------------------------+
"""
# Check if the model is already fitted
check_is_fitted(self, ["model"])
n_features = (
self.model.model.endog.shape[1]
if len(self.model.model.endog.shape) > 1
else 1
)
return self._get_intercepts_helper(self.model, n_features)
def get_residuals(self) -> np.ndarray:
"""
Return the residuals of the fitted model.
Returns
-------
np.ndarray
The residuals of the fitted model.
Raises
------
NotFittedError
If the model is not fitted.
Notes
-----
The shape of the residuals depends on the model type.
+--------+-------------------+
| Model | Residual shape |
+========+===================+
| 'ar' | (n, 1) |
+--------+-------------------+
| 'arima'| (n, 1) |
+--------+-------------------+
| 'sarima'| (n, 1) |
+--------+-------------------+
| 'var' | (n, k) |
+--------+-------------------+
| 'arch' | (n, 1) |
+--------+-------------------+
"""
# Check if the model is already fitted
check_is_fitted(self, ["model"])
return self._get_residuals_helper(self.model)
def get_fitted_X(self) -> np.ndarray:
"""
Return the fitted values of the model.
Returns
-------
np.ndarray
The fitted values of the model.
Raises
------
NotFittedError
If the model is not fitted.
Notes
-----
The shape of the fitted values depends on the model type.
+--------+--------------------+
| Model | Fitted values shape|
+========+====================+
| 'ar' | (n, 1) |
+--------+--------------------+
| 'arima'| (n, 1) |
+--------+--------------------+
| 'sarima'| (n, 1) |
+--------+--------------------+
| 'var' | (n, k) |
+--------+--------------------+
| 'arch' | (n, 1) |
+--------+--------------------+
"""
# Check if the model is already fitted
check_is_fitted(self, ["model"])
return self._get_fitted_X_helper(self.model)
def get_order(self) -> OrderTypesWithoutNone:
"""
Return the order of the fitted model.
Returns
-------
OrderTypesWithoutNone
The order of the fitted model.
Raises
------
NotFittedError
If the model is not fitted.
Notes
-----
The shape of the order depends on the model type.
+--------+-------------------+
| Model | Order shape |
+========+===================+
| 'ar' | int |
+--------+-------------------+
| 'arima'| tuple of length 3 |
+--------+-------------------+
| 'sarima'| tuple of length 4|
+--------+-------------------+
| 'var' | int |
+--------+-------------------+
| 'arch' | int |
+--------+-------------------+
"""
# Check if the model is already fitted
check_is_fitted(self, ["model"])
return self._get_order_helper(self.model)
def predict(self, X: np.ndarray, y=None, n_steps: int = 1) -> np.ndarray:
"""
Predict time series values using the fitted model.
Parameters
----------
X : np.ndarray
Input data of shape (n_timepoints, n_features).
y : np.ndarray, optional
Exogenous variables, by default None.
n_steps : int, optional
Number of steps to forecast, by default 1.
Returns
-------
np.ndarray
Predicted values.
Raises
------
RuntimeError
If the model is not fitted.
"""
# Check if the model is already fitted
check_is_fitted(self, ["model"])
# Check if the input shapes are valid
X = validate_X(X, model_is_var=self.model_type == "var")
if self.model_type == "var":
return self.model.forecast(X, n_steps, exog_future=y)
elif self.model_type == "arch":
# Adjust the code according to how ARCH predictions are made in your setup
return (
self.model.forecast(horizon=n_steps, x=y, method="analytic")
.mean.values[-1]
.ravel()
)
elif self.model_type in ["ar", "arima", "sarima"]:
# For AutoReg, ARIMA, and SARIMA, use the built-in forecast method
return self.model.forecast(steps=n_steps, exog=y)
def score(self, X: np.ndarray, y_true: np.ndarray) -> float:
"""
Compute the R-squared score for the fitted model.
Parameters
----------
X : np.ndarray
The input data.
y_true : np.ndarray
The true values.
Returns
-------
float
The R-squared score.
Raises
------
NotFittedError
If the model is not fitted.
ValueError
If the number of lags is greater than the length of the input data.
"""
y_pred = self.predict(X)
# Use r2 as the score
return r2_score(y_true, y_pred)
# These helper methods are internal and still take the model as a parameter.
# They can be used by the public methods above which do not take the model parameter.
def _get_coefs_helper(self, model, n_features) -> np.ndarray:
trend_terms = TSFit._calculate_trend_terms(self.model_type, model)
if self.model_type == "var":
# Exclude the trend terms and reshape the remaining coefficients
return (
model.params[trend_terms:]
.reshape(n_features, self.get_order(), n_features)
.transpose(0, 2, 1)
)
# shape = (n_features, order, n_features)
elif self.model_type == "ar":
# Exclude the trend terms
if isinstance(self.order, list):
# Autoreg does not sort the passed lags, but the output from model.params is sorted
coefs = np.zeros((1, len(self.order)))
for i, _ in enumerate(self.order):
# Exclude the trend terms
coefs[0, i] = model.params[trend_terms + i]
else:
# Exclude the trend terms
coefs = model.params[trend_terms:].reshape(1, -1)
# shape = (1, order)
return coefs
elif self.model_type in ["arima", "sarima"]:
# Exclude the trend terms
# shape = (1, order)
return model.params[trend_terms:].reshape(1, -1)
elif self.model_type == "arch":
# ARCH models don't include trend terms by default, so just return the params as is
return model.params
def _get_intercepts_helper(self, model, n_features) -> np.ndarray:
trend_terms = TSFit._calculate_trend_terms(self.model_type, model)
if self.model_type == "var":
# Include just the trend terms and reshape
return model.params[:trend_terms].reshape(n_features, trend_terms)
# shape = (n_features, trend_terms)
elif self.model_type in ["ar", "arima", "sarima"]:
# Include just the trend terms
return model.params[:trend_terms].reshape(1, trend_terms)
# shape = (1, trend_terms)
elif self.model_type == "arch":
# ARCH models don't include trend terms by default, so just return the params as is
return np.array([])
@staticmethod
def _calculate_trend_terms(model_type: str, model) -> int:
"""
Determine the number of trend terms based on the 'trend' attribute of the model.
"""
if model_type in ["ar", "arima", "sarima"]:
trend = model.model.trend
if trend == "n" or trend is None:
trend_terms = 0
elif trend in ["c", "t"]:
trend_terms = 1
elif trend == "ct":
trend_terms = 2
else:
raise ValueError(f"Unknown trend term: {trend}")
return trend_terms
elif model_type == "var":
trend = model.trend
if trend == "nc":
trend_terms_per_variable = 0
elif trend == "c":
trend_terms_per_variable = 1
elif trend == "ct":
trend_terms_per_variable = 2
elif trend == "ctt":
trend_terms_per_variable = 3
else:
raise ValueError(f"Unknown trend term: {trend}")
return trend_terms_per_variable
def _get_residuals_helper(self, model) -> np.ndarray:
model_resid = model.resid
# Ensure model_resid has the correct shape, (n, 1) or (n, k)
if model_resid.ndim == 1:
model_resid = model_resid.reshape(-1, 1)
if self.model_type in ["ar", "var"]:
max_lag = (
self.model.model.endog.shape[0] - model_resid.shape[0]
) # np.max(self.get_order())
values_to_add_back = self.model.model.endog[:max_lag]
# Ensure values_to_add_back has the same shape as model_resid
if values_to_add_back.ndim != model_resid.ndim:
values_to_add_back = values_to_add_back.reshape(-1, 1)
model_resid = np.vstack((values_to_add_back, model_resid))
if self.model_type == "arch":
model_resid = model_resid / self.rescale_factors["x"]
return model_resid
def _get_fitted_X_helper(self, model) -> np.ndarray:
if self.model_type != "arch":
model_fittedvalues = model.fittedvalues
# Ensure model_fittedvalues has the correct shape, (n, 1) or (n, k)
if model_fittedvalues.ndim == 1:
model_fittedvalues = model_fittedvalues.reshape(-1, 1)
if self.model_type in ["ar", "var"]:
max_lag = (
self.model.model.endog.shape[0]
- model_fittedvalues.shape[0]
) # np.max(self.get_order())
values_to_add_back = self.model.model.endog[:max_lag]
# Ensure values_to_add_back has the same shape as model_fittedvalues
if values_to_add_back.ndim != model_fittedvalues.ndim:
values_to_add_back = values_to_add_back.reshape(-1, 1)
model_fittedvalues = np.vstack(
(values_to_add_back, model_fittedvalues)
)
return model_fittedvalues
else:
return (
model.resid + model.conditional_volatility
) / self.rescale_factors["x"]
def _get_order_helper(self, model) -> OrderTypesWithoutNone:
"""
Return the order of the fitted model.
"""
if self.model_type == "arch":
return model.model.volatility.p
elif self.model == "var":
return model.k_ar
elif self.model_type == "ar" and isinstance(self.order, list):
return sorted(self.order)
else:
return self.order
def _lag(self, X: np.ndarray, n_lags: int) -> np.ndarray:
"""
Lag the input data.
Parameters
----------
X : np.ndarray
The input data.
n_lags : int
The number of lags.
Returns
-------
np.ndarray
The lagged data.
Raises
------
ValueError
If the number of lags is greater than the length of the input data.
"""
if len(X) < n_lags:
raise ValueError(
"Number of lags is greater than the length of the input data."
)
return np.column_stack(
[X[i : -(n_lags - i), :] for i in range(n_lags)]
)
class TSFitBestLag(BaseEstimator, RegressorMixin):
"""
A class used to fit time series data and find the best lag for forecasting.
Attributes
----------
rank_lagger : RankLags
An instance of the RankLags class.
ts_fit : TSFit
An instance of the TSFit class.
model : Union[AutoRegResultsWrapper, ARIMAResultsWrapper, SARIMAXResultsWrapper, VARResultsWrapper, ARCHModelResult]
The fitted time series model.
rescale_factors : Dict[str, Union[float, List[float] | None]]
The rescaling factors used for the input data and exogenous variables.
Methods
-------
fit(X, y=None)
Fit the time series model to the data.
get_coefs()
Return the coefficients of the fitted model.
get_intercepts()
Return the intercepts of the fitted model.
get_residuals()
Return the residuals of the fitted model.
get_fitted_X()
Return the fitted values of the model.
get_order()
Return the order of the fitted model.
get_model()
Return the fitted time series model.
predict(X, n_steps=1)
Predict future values using the fitted model.
score(X, y_true)
Compute the R-squared score for the fitted model.
"""
def __init__(
self,
model_type: str,
max_lag: int = 10,
order: OrderTypes = None,
save_models=False,
**kwargs,
):
self.model_type = model_type
self.max_lag = max_lag
self.order = order
self.save_models = save_models
self.model_params = kwargs
self.rank_lagger = None
self.ts_fit = None
self.model = None
self.rescale_factors = {"x": 1, "y": None}
def _compute_best_order(self, X) -> int:
"""
Internal method to compute the best order for the given data.
Parameters
----------
X : np.ndarray
The input data.
Returns
-------
int
The best order for the given data.
"""
self.rank_lagger = RankLags(
X=X,
max_lag=self.max_lag,
model_type=self.model_type,
save_models=self.save_models,
)
best_order = self.rank_lagger.estimate_conservative_lag()
return best_order
def fit(self, X: np.ndarray, y=None):
"""
Fit the time series model to the data.
Parameters
----------
X : np.ndarray
The input data.
y : np.ndarray, optional, default=None
Exogenous variables to include in the model.
Returns
-------
self
The fitted model.
"""
if self.order is None:
self.order = self._compute_best_order(X)
if self.save_models:
self.model = self.rank_lagger.get_model(self.order)
self.ts_fit = TSFit(
order=self.order, model_type=self.model_type, **self.model_params
)
self.model = self.ts_fit.fit(X, y=y).model
self.rescale_factors = self.ts_fit.rescale_factors
return self
def get_coefs(self) -> np.ndarray:
"""
Return the coefficients of the fitted model.
Returns
-------
np.ndarray
The coefficients of the fitted model.
"""
return self.ts_fit.get_coefs()
def get_residuals(self) -> np.ndarray:
"""
Return the residuals of the fitted model.
Returns
-------
np.ndarray
The residuals of the fitted model.
"""
return self.ts_fit.get_residuals()
def get_fitted_X(self) -> np.ndarray:
"""
Return the fitted values of the model.
Returns
-------
np.ndarray
The fitted values of the model.
"""
return self.ts_fit.get_fitted_X()
def get_order(self) -> OrderTypesWithoutNone:
"""
Return the order of the fitted model.
Returns
-------
int, List[int], Tuple[int, int, int], Tuple[int, int, int, int]
The order of the fitted model.
"""
return self.ts_fit.get_order()
def get_model(self):
"""
Return the fitted time series model.
Returns
-------
Union[AutoRegResultsWrapper, ARIMAResultsWrapper, SARIMAXResultsWrapper, VARResultsWrapper, ARCHModelResult]
The fitted time series model.
Raises
------
ValueError
If models were not saved during initialization.
"""
if self.save_models:
return self.rank_lagger.get_model(self.order)
else:
raise ValueError(
"Models were not saved. Please set save_models=True during initialization."
)
def predict(self, X: np.ndarray, n_steps: int = 1):
"""
Predict future values using the fitted model.
Parameters
----------
X : np.ndarray
The input data.
n_steps : int, optional, default=1
The number of steps to predict.
Returns
-------
np.ndarray
The predicted values.
"""
return self.ts_fit.predict(X, n_steps)
def score(self, X: np.ndarray, y_true: np.ndarray):
"""
Compute the R-squared score for the fitted model.