-
Notifications
You must be signed in to change notification settings - Fork 2
/
Forecaster.py
2588 lines (2355 loc) · 155 KB
/
Forecaster.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
import pandas as pd
import numpy as np
import datetime
import os
import pandas_datareader as pdr
from collections import Counter
from scipy import stats
import rpy2.robjects as ro
from sklearn.metrics import r2_score
# make the working directory friendly for R
rwd = os.getcwd().replace('\\','/')
# add a descriptive error
class ForecastFormatError(Exception):
pass
class Forecaster:
""" object to forecast time series data
natively supports the extraction of FRED data, could be expanded to other APIs with few adjustments
the following models are supported:
adaboost (sklearn)
auto_arima (R forecast::auto.arima, no seasonal models)
auto_arima_seas (R forecast::auto.arima, seasonal models)
arima (statsmodels, not automatically optimized)
sarimax13 (Seasonal Auto Regressive Integrated Moving Average by X13 - R seasonal::seas)
average (any number of models can be averaged)
ets (exponental smoothing state space model - R forecast::ets)
gbt (gradient boosted trees - sklearn)
xgboost (xgboost)
hwes (holt-winters exponential smoothing - statsmodels hwes)
auto_hwes (holt-winters exponential smoothing - statsmodels hwes)
lasso (sklearn)
elasticnet (sklearn)
mlp (multi level perceptron - sklearn)
mlr (multi linear regression - sklearn)
prophet (facebook prophet - fbprophet)
rf (random forest - sklearn)
ridge (sklearn)
svr (support vector regressor - sklearn)
tbats (exponential smoothing state space model With box-cox transformation, arma errors, trend, and seasonal component - R forecast::tbats)
nnetar (time series neural network - R forecast::nnetar)
var (vector auto regression - R vars::VAR)
vecm (vector error correction model - R tsDyn::VECM)
more models can be added by building more methods
for every evaluated model, the following information is stored in the object attributes:
in self.info (dict), a key is added as the model name and a nested dictionary as the value
the nested dictionary has the following keys:
'holdout_periods' : int - the number of periods held out in the test set
'model_form' : str - the name of the model with any hyperparameters, external regressors, etc
'test_set_actuals' : list - the actual figures from the test set
'test_set_predictions' : list - the predicted figures from the test set evaluated with a model from the training set
'test_set_ape' : list - the absolute percentage error for each period from the forecasted training set figures, evaluated with the actual test set figures
'fitted_values' : list - the model's fitted values, when available. if not available, None
in self.mape (dict), a key is added as the model name and the Mean Absolute Percent Error as the value
in self.rmse (dict), a key is added as the model name and the Root Mean Square Error as the value
in self.mae (dict), a key is added as the model name and the Mean Absolute Error as the value
in self.r2 (dict), a key is added as the model name and the R Squared as the value
in self.forecasts (dict), a key is added as the model name and a list of forecasted figures as the value
in self.feature_importance (dict), a key is added to the dictionary as the model name and the value is a dataframe that gives some info about the features' prediction power
if it is an sklearn model, it will be permutation feature importance from the eli5 package (https://eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html)
any other model, it is a dataframe with at least the names of the variables in the index, with as much summary statistical info as possible
if the model doesn't use external regressors, no key is added here
Author Michael Keith: mikekeith52@gmail.com
"""
def __init__(self,name=None,y=None,current_dates=None,future_dates=None,current_xreg=None,future_xreg=None,forecast_out_periods=24,**kwargs):
""" You can load the object with data using __init__ or you can leave all default arguments and load the data with an attached API method (such as get_data_fred())
Keep the object types consistent (do not use tuples or numpy arrays instead of lists, for example)
Parameters: name : str
y : list
current_dates : list
an ordered list of dates that correspond to the ordered values in self.y
elements must be able to be parsed by pandas as dates
future_dates : list
an ordered list of dates that correspond to the future periods being forecasted
elements must be able to be parsed by pandas as dates
current_xreg : dict
future_xreg : dict
forecast_out_periods : int, default length of future_dates or 24 if that is None
all keyword arguments become attributes
"""
self.name = name
self.y = y
self.current_dates = current_dates
self.future_dates = future_dates
self.current_xreg = current_xreg
self.future_xreg = future_xreg
self.forecast_out_periods = forecast_out_periods if future_dates is None else len(future_dates)
self.info = {}
self.mape = {}
self.rmse = {}
self.mae = {}
self.r2 = {}
self.forecasts = {}
self.feature_importance = {}
self.ordered_xreg = None
self.best_model = ''
for key, value in kwargs.items():
setattr(self,key,value)
def _score_and_forecast(self,call_me,regr,X,y,X_train,y_train,X_test,y_test,Xvars):
""" scores a model on a test test (sklearn models specific)
forecasts out however many periods in the new data
writes info to self.info, self.mape, and self.forecasts (this process is described in more detail in the forecast methods)
Parameters: call_me : str
regr : sklearn.<regression_model>
X : pd.core.frame.DataFrame
y : pd.Series
X_train : pd.core.frame.DataFrame
y_train : pd.Series
X_test : pd.core.frame.DataFrame
y_test : pd.Series
Xvars : list or str
"""
regr.fit(X_train,y_train)
pred = regr.predict(X_test)
self.info[call_me]['test_set_actuals'] = list(y_test)
self.info[call_me]['test_set_predictions'] = list(pred)
self._metrics(call_me)
regr.fit(X,y)
new_data = pd.DataFrame(self.future_xreg)
if isinstance(Xvars,list):
new_data = new_data[Xvars]
f = regr.predict(new_data)
self.forecasts[call_me] = list(f)
self.info[call_me]['fitted_values'] = list(regr.predict(X))
def _set_remaining_info(self,call_me,test_length,model_form):
""" sets the holdout_periods and model_form values in the self.info nested dictionary, where call_me (model nickname) is the key
"""
self.info[call_me]['holdout_periods'] = test_length
self.info[call_me]['model_form'] = model_form
def _train_test_split(self,test_length,Xvars='all'):
""" returns an X/y full set, training set, and testing set (sklearn models specific)
resulting y objects are pandas series
resulting X objects are pandas dataframe
this is a non-random split and the resulting test set will be size specified in test_length
Parameters: test_length : int,
the length of the resulting test_set
Xvars : list or "all", default "all"
the independent variables to use in the resulting X dataframes
"""
from sklearn.model_selection import train_test_split
X = pd.DataFrame(self.current_xreg)
if isinstance(Xvars,list):
X = X[Xvars]
y = pd.Series(self.y)
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=test_length,shuffle=False)
return X, y, X_train, X_test, y_train, y_test
def _set_feature_importance(self,X,y,regr):
""" returns the permutation feature importances of any regression model in a pandas dataframe
leverages eli5 package (https://pypi.org/project/eli5/)
sklearn models specific
Parameters: X : pandas dataframe
X regressors used to predict the depdendent variable
y : pandas series
y series representing the known values of the dependent variable
regr : sklearn estimator
the estimator to use to score the permutation feature importance
"""
import eli5
from eli5.sklearn import PermutationImportance
perm = PermutationImportance(regr).fit(X,y)
weights_df = eli5.explain_weights_df(perm,feature_names=X.columns.tolist()).set_index('feature')
return weights_df
def _prepr(self,*libs,test_length,call_me,Xvars):
""" prepares the R environment by importing/installing libraries and writing out csv files (current/future datasets) to tmp folder
file names: tmp_r_current.csv, tmp_r_future.csv
*libs are libs to import and/or install from R
Parameters: call_me : str
Xvars : list, "all", or starts with "top_"
*libs: str
library names to import into the R environment
if library name not found in R environ, will attempt to install it (you will need to specify a CRAN mirror in a pop-up box)
"""
from rpy2.robjects.packages import importr
if isinstance(Xvars,str):
if Xvars.startswith('top_'):
top_xreg = int(Xvars.split('_')[1])
if top_xreg == 0:
Xvars = None
else:
self.set_ordered_xreg(chop_tail_periods=test_length) # have to reset here for differing test lengths in other models
if top_xreg > len(self.ordered_xreg):
Xvars = self.ordered_xreg[:]
else:
Xvars = self.ordered_xreg[:top_xreg]
elif Xvars == 'all':
Xvars = list(self.current_xreg.keys())
elif not Xvars is None:
raise ValueError(f'Xvars argument not recognized: {Xvars}')
for lib in libs:
try: importr(lib)
except: ro.r(f'install.packages("{lib}")') ; importr(lib) # install then import the r lib
current_df = pd.DataFrame(self.current_xreg)
current_df['y'] = self.y
if isinstance(Xvars,list):
current_df = current_df[['y'] + Xvars] # reorder columns
else:
current_df = current_df['y']
if 'tmp' not in os.listdir():
os.mkdir('tmp') # where all
current_df.to_csv(f'tmp/tmp_r_current.csv',index=False)
if not Xvars is None:
future_df = pd.DataFrame(self.future_xreg)
future_df.to_csv(f'tmp/tmp_r_future.csv',index=False)
def _sm_summary_to_fi(self,sm_model,call_me):
""" places summary output from a stasmodels model into self.feature_importance as a pandas dataframe
https://stackoverflow.com/questions/51734180/converting-statsmodels-summary-object-to-pandas-dataframe/52976810
"""
results_summary = sm_model.summary()
results_as_html = results_summary.tables[1].as_html()
self.feature_importance[call_me] = pd.read_html(results_as_html, header=0, index_col=0)[0]
def _get_info_dict(self):
return dict.fromkeys(['holdout_periods','model_form','test_set_actuals','test_set_predictions','test_set_ape','fitted_values'])
def _metrics(self,call_me):
""" creates mape, rmse, mae, and r2
"""
self.info[call_me]['test_set_ape'] = [np.abs(yhat-y) / np.abs(y) for yhat, y in zip(self.info[call_me]['test_set_predictions'],self.info[call_me]['test_set_actuals'])]
self.mape[call_me] = np.mean(self.info[call_me]['test_set_ape'])
self.rmse[call_me] = np.mean([(y - yhat)**2 for yhat,y in zip(self.info[call_me]['test_set_predictions'],self.info[call_me]['test_set_actuals'])])**0.5
self.mae[call_me] = np.mean([np.abs(y - yhat) for yhat,y in zip(self.info[call_me]['test_set_predictions'],self.info[call_me]['test_set_actuals'])])
# r2 needs at least 2 observations to work, so test_length = 1 will not evaluate
if len(self.info[call_me]['test_set_predictions']) > 1:
self.r2[call_me] = r2_score(self.info[call_me]['test_set_predictions'],self.info[call_me]['test_set_actuals'])
else:
self.r2[call_me] = None
def _ready_for_forecast(self,need_xreg=False):
""" runs before each attempt to forecast to make sure:
y is set as a list of numeric figures
current_dates is set as a list of datetime-like objects
future_dates is set as a list of datetime-like objects
if current_xreg is set, future_xreg is also set and both are dictionaries with lists as values
"""
_no_error_ = 'before forecasting, the following issues need to be corrected:'
error = _no_error_
if isinstance(self.y,list):
try:
[float(i) for i in self.y]
except ValueError:
error+='\n all elements in y attribute must be numeric'
else:
error+=f'\n y attribute must be a list, not {type(self.y)}'
dates = {'current_dates':self.current_dates,'future_dates':self.future_dates}
for k,v in dates.items():
if isinstance(v,list):
try:
if k == 'current_dates':
self.current_dates = pd.to_datetime(v).to_list()
else:
self.future_dates = pd.to_datetime(v).to_list()
except:
error+=f'\n the elements in the {k} attribute must be able to be parsed by pandas date parser -- try passing each element in yyyy-mm-dd format'
else:
error+=f'\n {k} attribute must be a list, got {type(v)}'
if not isinstance(self.forecast_out_periods,int):
error+=f'\n the forecast_out_periods attribute must be an integer type, found {type(self.forecast_out_periods)}'
else:
if self.forecast_out_periods < 1:
error+=f'\n forecast_out_periods must be at least 1 (is {self.forecast_out_periods})'
if (self.current_xreg is None) & (need_xreg):
error+='\n the forecast you are attempting to run needs at least one external regressor to work, could not find any in the current_xreg attribute'
else:
if isinstance(self.current_xreg,dict):
if not isinstance(self.future_xreg,dict):
error+=f'\n if you are passing external regressors to the current_xreg attribute, the future_xreg attribute must also be a dictionary type, found {type(self.future_xreg)} type'
else:
for k in self.current_xreg.keys():
if k not in self.future_xreg.keys():
error+=f'\n all keys in the current_xreg attribute must also be present in the future_xreg attribute, could not find {k}'
for k, v in self.current_xreg.items():
if (not isinstance(v,list)) | (not isinstance(self.future_xreg[k],list)):
error+=f'\n all values in the current_xreg and future_xreg dictionaries must be list types, check the {k} key'
elif len(v) != len(self.y):
error+=f'\n all values in the current_xreg dictionary must be the same length as the y attribute, check {k}'
elif len(self.future_xreg[k]) != self.forecast_out_periods:
error+=f'\n all values in the future_xreg dictionary must be the same length as the forecast_out_periods attribute value ({self.forecast_out_periods}), check {k}'
elif np.isnan(v).sum() > 0:
error+=f'\n cannot have missing values in any of the current_xreg values, check {k}'
elif np.isnan(self.future_xreg[k]).sum() > 0:
error+=f'\n cannot have missing values in any of the future_xreg values, check {k}'
elif not self.current_xreg is None:
error+=f'\n current_xreg attribute must be a dict type if attempting to use external regressors, or None if not, found {type(self.current_xreg)}'
if len(error) > len(_no_error_):
raise ForecastFormatError(error)
def get_data_fred(self,series,i=0,date_start='1900-01-01'):
""" imports data from FRED into a pandas dataframe
stores the results in self.name, self.y, and self.current_dates
Parameters: series : str
the name of the series to extract from FRED
i : int
the number of differences to take in the series to make it stationary
date_start : str
the date to begin the time series
must be in YYYY-mm-dd format
f = Forecaster()
f.get_data_fred('UTUR')
print(f.y)
>>> [5.8, 5.8, ..., 5.0, 4.1]
print(f.current_dates)
>>> [Timestamp('1976-01-01 00:00:00'), Timestamp('1976-02-01 00:00:00'), ..., Timestamp('2020-09-01 00:00:00'), Timestamp('2020-10-01 00:00:00')]
"""
self.name = series
df = pdr.get_data_fred(series,start=date_start)
if i > 0:
df[series] = df[series].diff(i)
df.dropna(inplace=True)
self.y = df[series].to_list()
self.current_dates = df.index.to_list()
def process_xreg_df(self,xreg_df,date_col,process_columns=False):
""" takes a dataframe of external regressors
any non-numeric data will be made into a 0/1 binary variable (using pandas.get_dummies(drop_first=True))
deals with columns with missing data
eliminates rows that don't correspond with self.y's timeframe
splits values between future and current observations
changes self.forecast_out_periods based on how many periods included in the dataframe past current_dates attribute
assumes the dataframe is aggregated to the same timeframe as self.y (monthly, quarterly, etc.)
for more complex processing, perform manipulations before passing through this function
stores results in self.current_xreg, self.future_xreg, self.future_dates, and self.forecast_out_periods
Parameters: xreg_df : pandas dataframe, required
this should include only independent regressors either in numeric form or that can be dummied into a 1/0 variable as well as a date column that can be parsed by pandas
do not include the dependent variable value
date_col : str, requried
the name of the date column in xreg_df that can be parsed with the pandas.to_datetime() function
process_columns : str, dict, or False; optional
how to process columns with missing data - most forecasts will not run when missing data is present in either xreg dict
supported: {'remove','impute_mean','impute_median','impute_mode','impute_min','impute_max',impute_0','forward_fill','backward_fill','impute_random'}
if str, must be one of supported and that method is applied to all columns with missing data
if dict, key is a column and value is one of supported, method only applied to columns with missing data
'impute_random' will fill in missing values with random draws from the same column
xreg_df = pd.DataFrame({'date':['2020-01-01','2020-02-01','2020-03-01','2020-04-01']},'x1':[1,2,3,5],'x2':[1,3,3,3])
f = Forecaster(y=[4,5,9],current_dates=['2020-01-01','2020-02-01','2020-03-01'])
f.process_xreg_df(xreg_df,date_col='date')
print(f.current_xreg)
>>> {'x1':[1,2,3],'x2':[1,3,3]}
print(f.future_xreg)
>>> {'x1':[5],'x2':[3]}
print(f.future_dates)
>>> [Timestamp('2020-04-01 00:00:00')]
print(f.forecast_out_periods)
>>> 1
"""
# for other processing methods, add a function here that follows the same pattern and it should flow down automatically
def _remove_(c): xreg_df.drop(columns=c,inplace=True)
def _impute_mean_(c): xreg_df[c].fillna(xreg_df[c].mean(),inplace=True)
def _impute_median_(c): xreg_df[c].fillna(xreg_df[c].median(),inplace=True)
def _impute_mode_(c): xreg_df[c].fillna(stats.mode(xreg_df[c])[0][0],inplace=True)
def _impute_min_(c): xreg_df[c].fillna(xreg_df[c].min(),inplace=True)
def _impute_max_(c): xreg_df[c].fillna(xreg_df[c].max(),inplace=True)
def _impute_0_(c): xreg_df[c].fillna(0,inplace=True)
def _forward_fill_(c): xreg_df[c].fillna(method='ffill',inplace=True)
def _backward_fill_(c): xreg_df[c].fillna(method='bfill',inplace=True)
def _impute_random_(c): xreg_df.loc[xreg_df[c].isnull(),c] = xreg_df[c].dropna().sample(xreg_df.loc[xreg_df[c].isnull()].shape[0]).to_list()
assert xreg_df.shape[0] == len(xreg_df[date_col].unique()), 'each date supplied must be unique'
xreg_df[date_col] = pd.to_datetime(xreg_df[date_col])
self.future_dates = xreg_df.loc[xreg_df[date_col] > list(self.current_dates)[-1],date_col].to_list()
xreg_df = xreg_df.loc[xreg_df[date_col] >= self.current_dates[0]]
xreg_df = pd.get_dummies(xreg_df,drop_first=True)
if not not process_columns:
if isinstance(process_columns,dict):
for c, v in process_columns.items():
try: locals()['_'+v+'_'](c) if xreg_df[c].isnull().sum() > 0 else None
except KeyError: raise ValueError(f'argument {v} not supported for key {c} in process_columns')
elif isinstance(process_columns,str):
for c in xreg_df:
try: locals()['_'+process_columns+'_'](c) if xreg_df[c].isnull().sum() > 0 else None
except KeyError: raise ValueError(f'argument passed to process_columns not supported: {process_columns}')
else:
raise ValueError(f'argument passed to process_columns not supported: {process_columns}')
current_xreg_df = xreg_df.loc[xreg_df[date_col].isin(self.current_dates)].drop(columns=date_col)
future_xreg_df = xreg_df.loc[xreg_df[date_col] > list(self.current_dates)[-1]].drop(columns=date_col)
assert current_xreg_df.shape[0] == len(self.y), 'something went wrong--make sure the dataframe spans the entire date-range as y and is at least one observation to the future and specify a date column in date_col parameter'
self.forecast_out_periods = future_xreg_df.shape[0]
self.current_xreg = current_xreg_df.to_dict(orient='list')
self.future_xreg = future_xreg_df.to_dict(orient='list')
def keep_smaller_history(self,n):
""" keeps a certain number of observations from the dependent variable's history and trims y, current_dates, and current_xreg attributes to all match
Paramaters: n : int, datetime/pandas timestamp object, or str in yyyy-mm-dd format
the last number of observations to keep from the time series' history or the last date to keep
"""
try:
self._ready_for_forecast()
except ForecastFormatError as e:
raise ForecastFormatError(f'before calling keep_smaller_history, please make sure all forecast properties are configured properly:\n{e}')
if isinstance(n,str):
n = datetime.datetime.strptime(n,'%Y-%m-%d')
if (type(n) is datetime.datetime) or (type(n) is pd.Timestamp):
n = len([i for i in self.current_dates if i >= n])
assert (isinstance(n,int)) & (n > 2), 'n must be an int, datetime object, or str in yyyy-mm-dd format and there must be more than 2 observations to keep'
self.y = self.y[-n:]
self.current_dates = self.current_dates[-n:]
for k, v in self.current_xreg.items():
self.current_xreg[k] = v[-n:]
def generate_future_dates(self,n,freq):
""" generates future dates and stores in the future_dates attribute
changes forecast_out_periods attribute appropriately
Parameters: n : int
the number of periods to forecast
the length of the resulting future_dates attribute
freq : str
a pandas datetime freq value
https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases
"""
self.future_dates = pd.date_range(start=self.current_dates[-1],periods=n+1,freq=freq).to_list()[1:]
self.set_forecast_out_periods(n)
def set_forecast_out_periods(self,n):
""" sets the self.forecast_out_periods attribute and truncates self.future_dates and self.future_xreg if needed
Parameters: n : int
the number of periods you want to forecast out for
if this is a larger value than the size of the future_dates attribute, some models may fail
if this is a smaller value the the size of the future_dates attribute, future_xreg and future_dates will be truncated
"""
if isinstance(n,int):
if n >= 1:
self.forecast_out_periods = n
if (self.future_dates is None) | (n > len(self.future_dates)):
raise ForecastFormatError(f'cannot set forecast_out_periods to {n} without a fully populated future_dates attribute--try using the generate_future_dates() method')
else:
self.future_dates = self.future_dates[:n]
if isinstance(self.future_xreg,dict):
for k,v in self.future_xreg.items():
self.future_xreg[k] = v[:n]
else:
raise ValueError(f'n must be greater than 1, got {n}')
else:
raise ValueError(f'n must be an int type, got {type(n)}')
def set_ordered_xreg(self,chop_tail_periods=0,include_only='all',exclude=None,quiet=True):
""" method for ordering stored externals from most to least correlated, according to absolute Pearson correlation coefficient value
will not error out if a given external has no variation in it -- will simply skip
when measuring correlation, will assume all transformations for stationarity have already been made
stores the results in ordered_xreg attribute as a list
if two vars are perfectly correlated, will skip the second one
resuting ordered_xreg attribute may therefore not contain all xregs but will contain as many as could be set
Parameters: chop_tail_periods : int, default 0
The number of periods to chop (to compare to a training dataset)
This is used to reduce the chance of overfitting the data by using mismatched test periods for forecasts
include_only : list or any other data type, default "all"
if this is a list, only the externals in the list will be considered when testing correlation
if this is not a list, then it will be ignored and all externals will be considered
if this is a list, exclude will be ignored
exclude : list or any other data type, default None
if this is a list, the externals in the list will be excluded when testing correlation
if this is not a list, then it will be ignored and no externals will be excluded
if include_only is a list, this is ignored
note: it is possible for include_only to be its default value, "all", and exclude to not be ignored if it is passed as a list type
quiet : bool, default True
if this is True, then if a given external is ignored (either because no correlation could be calculated or there are no observations after its tail has been chopped), you will not know
if this is False, then if a given external is ignored, it will print which external is being skipped
>>> f = Forecaster()
>>> f.get_data_fred('UTUR')
>>> f.process_xreg_df(xreg_df,chop_tail_periods=12)
>>> f.set_ordered_xreg()
>>> print(f.ordered_xreg)
['x2','x1'] # in this case x2 correlates more strongly than x1 with y on a test set with 12 holdout periods
"""
log_diff = lambda x: np.diff(np.log(x),n=1)
if isinstance(include_only,list):
use_these_externals = {}
for e in include_only:
use_these_externals[e] = self.current_xreg[e]
else:
use_these_externals = self.current_xreg.copy()
if isinstance(exclude,list):
for e in exclude:
use_these_externals.pop(e)
ext_reg = {}
for k, v in use_these_externals.items():
if chop_tail_periods > 0:
x = np.array(v[:-chop_tail_periods])
y = np.array(self.y[:-chop_tail_periods])
else:
x = np.array(v)
y = np.array(self.y[:])
if len(np.unique(x)) == 1:
if not quiet:
print(f'no variation in {k} for time period specified')
continue
else:
r_coeff = stats.pearsonr(y,x)
if np.abs(r_coeff[0]) not in ext_reg.values():
ext_reg[k] = np.abs(r_coeff[0])
k = Counter(ext_reg)
self.ordered_xreg = [h[0] for h in k.most_common()] # this should give us the ranked external regressors
def forecast(self,which,**kwargs):
""" forecasts with a str method to allow for loops
"""
getattr(self,'forecast_'+which)(**kwargs)
def forecast_auto_arima(self,test_length=1,Xvars=None,call_me='auto_arima'):
""" Auto-Regressive Integrated Moving Average
forecasts using auto.arima from the forecast package in R
uses an algorithm to find the best ARIMA model automatically by minimizing in-sample aic
does not search seasonal models
Parameters: test_length : int, default 1
the number of periods to holdout in order to test the model
must be at least 1 (AssertionError raised if not)
Xvars : list, "all", None, or starts with "top_", default None
the independent variables used to make predictions
if it is a list, will attempt to estimate a model with that list of Xvars
if it begins with "top_", the character(s) after should be an int and will attempt to estimate a model with the top however many Xvars
"top" is determined through absolute value of the pearson correlation coefficient on the training set
if using "top_" and the integer is a greater number than the available x regressors, the model will be estimated with all available x regressors that are not perfectly colinear and have variation
if it is "all", will attempt to estimate a model with all available x regressors, regardless of whether there is collinearity or no variation
because the auto.arima function fails in the cases of perfect collinearity or no variation, using "top_" or a list with one element is safest option
if no arima model can be estimated, will raise an error
call_me : str, default "auto_arima"
the model's nickname -- this name carries to the self.info, self.mape, and self.forecasts dictionaries
f = Forecaster()
f.get_data_fred('UTUR')
f.forecast_auto_arima(test_length=12,call_me='arima')
print(f.info['arima'])
>>> {'holdout_periods': 12,
>>> 'model_form': 'ARIMA(0,1,5)',
>>> 'test_set_actuals': [2.4, 2.4, ..., 5.0, 4.1],
>>> 'test_set_predictions': [2.36083282553252, 2.3119957980461803, ..., 2.09177057271149, 2.08127132827637],
>>> 'test_set_ape': [0.0163196560281154, 0.03666841748076, ..., 0.581645885457702, 0.49237284676186205]}
print(f.forecasts['arima'])
>>> [4.000616524942799, 4.01916650578768, ..., 3.7576542462753904, 3.7576542462753904]
print(f.mape['arima'])
>>> 0.4082393522799069
print(f.feature_importance['arima']) # stored as a pandas dataframe
>>> coef se tvalue pval
>>> ma5 0.189706 0.045527 4.166858 3.598788e-05
>>> ma4 -0.032062 0.043873 -0.730781 4.652316e-01
>>> ma3 -0.060743 0.048104 -1.262753 2.072261e-01
>>> ma2 -0.257684 0.044522 -5.787802 1.213441e-08
>>> ma1 0.222933 0.042513 5.243861 2.265347e-07
"""
self._ready_for_forecast()
assert isinstance(test_length,int), f'test_length must be an int, not {type(test_length)}'
assert test_length >= 1, 'test_length must be at least 1'
self.info[call_me] = self._get_info_dict()
self._prepr('forecast',test_length=test_length,call_me=call_me,Xvars=Xvars)
ro.r(f"""
rm(list=ls())
setwd('{rwd}')
h <- {self.forecast_out_periods}
data <- data.frame(read.csv('tmp/tmp_r_current.csv'))
data_train <- data[1:(nrow(data)-{test_length}),,drop=FALSE]
data_test <- data[(nrow(data)-{test_length} + 1):nrow(data),,drop=FALSE]
y <- data$y
y_train <- y[1:(nrow(data)-{test_length})]
y_test <- y[(nrow(data)-{test_length} + 1):nrow(data)]
""")
ro.r("""
if (ncol(data) > 1){
future_externals = read.csv('tmp/tmp_r_future.csv')
externals = names(data)[2:ncol(data)]
xreg_c <- as.matrix(data[,externals])
xreg_tr <- as.matrix(data_train[,externals])
xreg_te <- as.matrix(data_test[,externals])
xreg_f <- as.matrix(future_externals[,externals])
} else {
xreg_c <- NULL
xreg_tr <- NULL
xreg_te <- NULL
xreg_f <- NULL
}
ar <- auto.arima(y_train,xreg=xreg_tr)
f <- forecast(ar,xreg=xreg_te,h=length(y_test))
# f[[4]] are point estimates, f[[1]] is the ARIMA form
p <- f[[4]]
arima_form <- f[[1]]
write <- data.frame(actual=y_test,
forecast=p)
write$APE <- abs(write$actual - write$forecast) / abs(write$actual)
write$model_form <- arima_form
write.csv(write,'tmp/tmp_test_results.csv',row.names=F)
ar <- auto.arima(y,max.order=10,stepwise=F,xreg=xreg_c)
f <- forecast(ar,xreg=xreg_f,h=h)
p <- f[[4]]
arima_form <- f[[1]]
write <- data.frame(forecast=p)
write$model_form <- arima_form
write.csv(write,'tmp/tmp_forecast.csv',row.names=F)
write <- data.frame(fitted = fitted(ar))
write.csv(write,'tmp/tmp_fitted.csv',row.names=F)
summary_df = data.frame(coef=rev(coef(ar)),se=rev(sqrt(diag(vcov(ar)))))
if (exists('externals')){row.names(summary_df)[1:length(externals)] <- externals}
summary_df$tvalue = summary_df$coef/summary_df$se
write.csv(summary_df,'tmp/tmp_summary_output.csv')
""")
tmp_test_results = pd.read_csv('tmp/tmp_test_results.csv')
tmp_forecast = pd.read_csv('tmp/tmp_forecast.csv')
tmp_fitted = pd.read_csv('tmp/tmp_fitted.csv')
self.forecasts[call_me] = list(tmp_forecast['forecast'])
self.info[call_me]['holdout_periods'] = test_length
self.info[call_me]['model_form'] = tmp_forecast['model_form'][0]
self.info[call_me]['test_set_actuals'] = tmp_test_results['actual'].to_list()
self.info[call_me]['test_set_predictions'] = tmp_test_results['forecast'].to_list()
self._metrics(call_me)
self.info[call_me]['fitted_values'] = tmp_fitted['fitted'].to_list()
self.feature_importance[call_me] = pd.read_csv('tmp/tmp_summary_output.csv',index_col=0)
if self.feature_importance[call_me].shape[0] > 0: # for the (0,i,0) model case
self.feature_importance[call_me]['pval'] = stats.t.sf(np.abs(self.feature_importance[call_me]['tvalue']), len(self.y)-1)*2 # https://stackoverflow.com/questions/17559897/python-p-value-from-t-statistic
else:
self.feature_importance.pop(call_me)
def forecast_auto_arima_seas(self,start='auto',interval=12,test_length=1,Xvars=None,call_me='auto_arima_seas'):
""" Auto-Regressive Integrated Moving Average
forecasts using auto.arima from the forecast package in R
searches seasonal models, but the algorithm isn't as complex as forecast_auto_arima() and is harder to set up
Parameters: test_length : int, default 1
the number of periods to holdout in order to test the model
must be at least 1 (AssertionError raised if not)
start : tuple of length 2 or "auto", default "auto"
1st element is the start year
2nd element is the start period in the appropriate interval
for instance, if you have quarterly data and your first obs is 2nd quarter of 1980, this would be (1980,2)
if "auto", assumes the dates in self.current_dates are monthly in yyyy-mm-01 format and will use the first element in the list
interval : float, default 12
the number of periods in one season (365.25 for annual, 12 for monthly, etc.)
Xvars : list, "all", None, or starts with "top_", default None
the independent variables used to make predictions
if it is a list, will attempt to estimate a model with that list of Xvars
if it begins with "top_", the character(s) after should be an int and will attempt to estimate a model with the top however many Xvars
"top" is determined through absolute value of the pearson correlation coefficient on the training set
if using "top_" and the integer is a greater number than the available x regressors, the model will be estimated with all available x regressors that are not perfectly colinear and have variation
if it is "all", will attempt to estimate a model with all available x regressors, regardless of whether there is collinearity or no variation
because the auto.arima function fails in the cases of perfect collinearity or no variation, using "top_" or a list with one element is safest option
if no arima model can be estimated, will raise an error
call_me : str, default "auto_arima_seas"
the model's nickname -- this name carries to the self.info, self.mape, and self.forecasts dictionaries
***See forecast_auto_arima() documentation for an example of how to call a forecast method and access reults
"""
self._ready_for_forecast()
if start == 'auto':
try: start = tuple(np.array(str(self.current_dates[0]).split('-')[:2]).astype(int))
except: raise ValueError('could not set start automatically, try passing argument manually')
try:
float(interval)
except ValueError:
raise ValueError(f'interval must be numeric type, got {type(interval)}')
assert isinstance(test_length,int), f'test_length must be an int, not {type(test_length)}'
assert test_length >= 1, 'test_length must be at least 1'
self.info[call_me] = self._get_info_dict()
self._prepr('forecast',test_length=test_length,call_me=call_me,Xvars=Xvars)
ro.r(f"""
rm(list=ls())
setwd('{rwd}')
start_p <- c{start}
interval <- {interval}
test_length <- {test_length}
h <- {self.forecast_out_periods}
data <- data.frame(read.csv('tmp/tmp_r_current.csv'))
y <- ts(data$y,start=start_p,deltat=1/interval)
y_train <- subset(y,start=1,end=nrow(data)-test_length)
y_test <- subset(y,start=nrow(data)-test_length+1,end=nrow(data))
""")
ro.r("""
if (ncol(data) > 1){
future_externals = data.frame(read.csv('tmp/tmp_r_future.csv'))
externals <- names(data)[2:ncol(data)]
data_c <- data[,externals, drop=FALSE]
data_f <- future_externals[,externals, drop=FALSE]
all_externals_ts <- ts(rbind(data_c,data_f),start=start_p,deltat=1/interval)
xreg_c <- subset(all_externals_ts,start=1,end=nrow(data))
xreg_tr <- subset(all_externals_ts,start=1,end=nrow(data)-test_length)
xreg_te <- subset(all_externals_ts,start=nrow(data)-test_length+1,end=nrow(data))
if (test_length == 1){
xreg_te <- t(xreg_te)
}
xreg_f <- subset(all_externals_ts,start=nrow(data)+1)
} else {
xreg_c <- NULL
xreg_tr <- NULL
xreg_te <- NULL
xreg_f <- NULL
}
ar <- auto.arima(y_train,xreg=xreg_tr)
f <- forecast(ar,xreg=xreg_te,h=length(y_test))
# f[[4]] are point estimates, f[[1]] is the ARIMA form
p <- f[[4]]
arima_form <- f[[1]]
if (test_length==1){
write <- data.frame(actual=y_test[1],
forecast=p[1])
} else {
write <- data.frame(actual=y_test,
forecast=p)
}
write$APE <- abs(write$actual - write$forecast) / abs(write$actual)
write$model_form <- arima_form
write.csv(write,'tmp/tmp_test_results.csv',row.names=F)
ar <- auto.arima(y,xreg=xreg_c)
f <- forecast(ar,xreg=xreg_f,h=h)
p <- f[[4]]
arima_form <- f[[1]]
write <- data.frame(forecast=p)
write$model_form <- arima_form
write.csv(write,'tmp/tmp_forecast.csv',row.names=F)
write <- data.frame(fitted = fitted(ar))
write.csv(write,'tmp/tmp_fitted.csv',row.names=F)
summary_df = data.frame(coef=rev(coef(ar)),se=rev(sqrt(diag(vcov(ar)))))
if (exists('externals')){row.names(summary_df)[1:length(externals)] <- externals}
summary_df$tvalue = summary_df$coef/summary_df$se
write.csv(summary_df,'tmp/tmp_summary_output.csv')
""")
tmp_test_results = pd.read_csv('tmp/tmp_test_results.csv')
tmp_forecast = pd.read_csv('tmp/tmp_forecast.csv')
tmp_fitted = pd.read_csv('tmp/tmp_fitted.csv')
self.forecasts[call_me] = list(tmp_forecast['forecast'])
self.info[call_me]['holdout_periods'] = test_length
self.info[call_me]['model_form'] = tmp_forecast['model_form'][0]
self.info[call_me]['test_set_actuals'] = tmp_test_results['actual'].to_list()
self.info[call_me]['test_set_predictions'] = tmp_test_results['forecast'].to_list()
self._metrics(call_me)
self.info[call_me]['fitted_values'] = tmp_fitted['fitted'].to_list()
self.feature_importance[call_me] = pd.read_csv('tmp/tmp_summary_output.csv',index_col=0)
if self.feature_importance[call_me].shape[0] > 0: # for the (0,i,0) model case
self.feature_importance[call_me]['pval'] = stats.t.sf(np.abs(self.feature_importance[call_me]['tvalue']), len(self.y)-1)*2 # https://stackoverflow.com/questions/17559897/python-p-value-from-t-statistic
else:
self.feature_importance.pop(call_me)
def forecast_prophet(self,test_length=1,Xvars=None,call_me='prophet',**kwargs):
""" Facebook Prophet
Parameters: test_length : int, default 1
the number of periods to holdout in order to test the model
must be at least 1 (AssertionError raised if not)
Xvars : list, "all", None, or starts with "top_", default None
the independent variables used to make predictions
if it is a list, will attempt to estimate a model with that list of Xvars
if it begins with "top_", the character(s) after should be an int and will attempt to estimate a model with the top however many Xvars
"top" is determined through absolute value of the pearson correlation coefficient on the training set
if using "top_" and the integer is a greater number than the available x regressors, the model will be estimated with all available x regressors that are not perfectly colinear and have variation
call_me : str, default "prophet"
the model's nickname -- this name carries to the self.info, self.mape, and self.forecasts dictionaries
keywords are passed to Prophet() function
"""
from fbprophet import Prophet
self._ready_for_forecast()
assert isinstance(test_length,int), f'test_length must be an int, not {type(test_length)}'
assert test_length >= 1, 'test_length must be at least 1'
self.info[call_me] = self._get_info_dict()
if not Xvars is None:
if Xvars == 'all':
X = pd.DataFrame(self.current_xreg)
X_f = pd.DataFrame(self.future_xreg)
elif isinstance(Xvars,list):
X = pd.DataFrame(self.current_xreg).loc[:,Xvars]
X_f = pd.DataFrame(self.future_xreg).loc[:,Xvars]
elif Xvars.startswith('top_'):
nxreg = int(Xvars.split('_')[1])
self.set_ordered_xreg(chop_tail_periods=test_length)
X = pd.DataFrame(self.current_xreg).loc[:,self.ordered_xreg[:nxreg]]
X_f = pd.DataFrame(self.future_xreg).loc[:,self.ordered_xreg[:nxreg]]
else:
raise ValueError(f'Xvars argument not recognized: {Xvars}')
else:
X = pd.DataFrame()
X_f = pd.DataFrame()
if 'cap' in kwargs:
X['cap'] = [kwargs['cap']]*len(self.y)
X_f['cap'] = [kwargs['cap']]*self.forecast_out_periods
kwargs.pop('cap')
if 'floor' in kwargs:
X['floor'] = [kwargs['floor']]*len(self.y)
X_f['floor'] = [kwargs['floor']]*self.forecast_out_periods
kwargs.pop('floor')
X['y'] = self.y
X['ds'] = self.current_dates
X_f['ds'] = self.future_dates
# train/test
model = Prophet(**kwargs)
for x in X.iloc[:,:-2].columns:
if x not in ('cap','floor'):
model.add_regressor(x)
model.fit(X.iloc[:-test_length])
test = model.predict(X.iloc[-test_length:])
self.info[call_me]['holdout_periods'] = test_length
self.info[call_me]['model_form'] = 'FB Prophet'
self.info[call_me]['test_set_actuals'] = X.iloc[-test_length:,-2].to_list()
self.info[call_me]['test_set_predictions'] = test['yhat'].to_list()
self._metrics(call_me)
# forecast
model = Prophet(**kwargs)
for x in X.iloc[:,:-2].columns:
if x not in ('cap','floor'):
model.add_regressor(x)
model.fit(X)
pred = model.predict(X_f)
self.info[call_me]['fitted_values'] = model.predict(X)['yhat'].to_list()
self.forecasts[call_me] = pred['yhat'].to_list()
if X.shape[1] > 2:
self.feature_importance[call_me] = pd.DataFrame(index=X.columns.to_list()[:-2])
def forecast_sarimax13(self,test_length=1,start='auto',interval=12,Xvars=None,call_me='sarimax13',error='raise'):
""" Seasonal Auto-Regressive Integrated Moving Average - ARIMA-X13 - https://www.census.gov/srd/www/x13as/
Forecasts using the seas function from the seasonal package, also need the X13 software (x13as.exe) saved locally
Automatically takes the best model ARIMA model form that fulfills a certain set of criteria (low forecast error rate, high statistical significance, etc)
X13 is a sophisticated way to model seasonality with ARIMA maintained by the census bureau, and the seasonal package provides a simple wrapper around the software with R
The function here is simplified, but the power in X13 is its database offers precise ways to model seasonality, also takes into account outliers
Documentation: https://cran.r-project.org/web/packages/seasonal/seasonal.pdf, http://www.seasonal.website/examples.html
This package only allows for monthly or less granular observations, and only three years or fewer of predictions
the model will fail if there are 0 or negative values in the dependent variable attempted to be predicted
the model can fail for several other reasons (including lack of seasonality in the dependent variable)
Parameters: test_length : int, default 1
the number of periods to holdout in order to test the model
must be at least 1 (AssertionError raised if not)
start : tuple of length 2 or "auto", default "auto"
1st element is the start year
2nd element is the start period in the appropriate interval
for instance, if you have quarterly data and your first obs is 2nd quarter of 1980, this would be (1980,2)
if "auto", assumes the dates in self.current_dates are monthly in yyyy-mm-01 format and will use the first element in the list
interval : 1 of {1,2,4,12}, default 12
1 for annual, 2 for bi-annual, 4 for quarterly, 12 for monthly
unfortunately, x13 does not allow for more granularity than the monthly level
Xvars : list, "all", None, or starts with "top_", default None
the independent variables used to make predictions
if it is a list, will attempt to estimate a model with that list of Xvars
if it begins with "top_", the character(s) after should be an int and will attempt to estimate a model with the top however many Xvars
"top" is determined through absolute value of the pearson correlation coefficient on the training set
if using "top_" and the integer is a greater number than the available x regressors, the model will be estimated with all available x regressors that are not perfectly colinear and have variation
if it is "all", will attempt to estimate a model with all available x regressors, regardless of whether there is collinearity or no variation
because the seas function fails in the cases of perfect collinearity or no variation, using "top_" or a list with one element is safest option
x13 already has an extensive list of x regressors that it will pull automatically--read the documentation for more info
call_me : str, default "sarimax13"
the model's nickname -- this name carries to the self.info, self.mape, and self.forecasts dictionaries
error: one of {"raise","pass","print"}, default "raise"
if unable to estimate the model, "raise" will raise an error
if unable to estimate the model, "pass" will silently skip the model and delete all associated attribute keys (self.info)
if unable to estimate the model, "print" will skip the model, delete all associated attribute keys (self.info), and print the error
errors are common even if you specify everything correctly -- it has to do with the X13 estimator itself
one common error is caused when negative or 0 values are present in the dependent variables
***See forecast_auto_arima() documentation for an example of how to call a forecast method and access reults
"""
self._ready_for_forecast()
if min(self.y) <= 0:
if error == 'raise':
raise ValueError('cannot estimate nnetar model, negative or 0 values observed in the y attribute')
elif error == 'pass':
return None
elif error == 'print':
print('cannot estimate nnetar model, negative or 0 values observed in the y attribute')
return None
else:
raise ValueError(f'argument in error not recognized: {error}')
if start == 'auto':
try: start = tuple(np.array(str(self.current_dates[0]).split('-')[:2]).astype(int))
except: raise ValueError('could not set start automatically, try passing argument manually')
assert isinstance(test_length,int), f'test_length must be an int, not {type(test_length)}'
assert test_length >= 1, 'test_length must be at least 1'
self.info[call_me] = self._get_info_dict()
self._prepr('forecast','seasonal',test_length=test_length,call_me=call_me,Xvars=Xvars)
ro.r(f"""
rm(list=ls())
setwd('{rwd}')
start_p <- c{start}
interval <- {interval}
test_length <- {test_length}
data <- data.frame(read.csv('tmp/tmp_r_current.csv'))
y <- ts(data$y,start=start_p,deltat=1/interval)
y_train <- subset(y,start=1,end=nrow(data)-test_length)
y_test <- subset(y,start=nrow(data)-test_length+1,end=nrow(data))
""")
ro.r("""
if (ncol(data) > 1){
future_externals = data.frame(read.csv('tmp/tmp_r_future.csv'))
r <- max(0,36-nrow(future_externals))
filler <-as.data.frame(replicate(ncol(future_externals),rep(0,r))) # we always need at least three years of data for this package
# if we have less than three years, fill in the rest with 0s
# we still only use predictions matching whatever is stored in self.forecast_out_periods
# https://github.com/christophsax/seasonal/issues/200
names(filler) <- names(future_externals)
future_externals <- rbind(future_externals,filler)
externals <- names(data)[2:ncol(data)]
data_c <- data[,externals, drop=FALSE]
data_f <- future_externals[,externals, drop=FALSE]
all_externals_ts <- ts(rbind(data_c,data_f),start=start_p,deltat=1/interval)
} else {
all_externals_ts <- NULL
}
""")
try:
ro.r(f"""
m_test <- seas(x=y_train,xreg=all_externals_ts,forecast.save="forecasts",pickmdl.method="best")
p <- series(m_test, "forecast.forecasts")[1:test_length,]
m <- seas(x=y,xreg=all_externals_ts,forecast.save="forecasts",pickmdl.method="best")
f <- series(m, "forecast.forecasts")[1:{self.forecast_out_periods},]
arima_form <- paste('ARIMA-X13',m_test$model$arima$model)
write <- data.frame(actual=y_test,forecast=p[,1])
write$APE <- abs(write$actual - write$forecast) / abs(write$actual)
write$model_form <- arima_form
write.csv(write,'tmp/tmp_test_results.csv',row.names=F)
arima_form <- paste('ARIMA-X13',m$model$arima$model)
write <- data.frame(forecast=f[,1])
write$model_form <- arima_form
write.csv(write,'tmp/tmp_forecast.csv',row.names=F)
""")
except Exception as e:
self.info.pop(call_me)
if error == 'raise':
raise e
elif error == 'print':
print(f"skipping model, here's the error:\n{e}")
elif error != 'pass':
print(f'error argument not recognized: {error}')
raise e
return None
ro.r("""
# feature_importance -- cool output
summary_df <- data.frame(summary(m))
if (exists("externals")) {summary_df$term[1:length(externals)] <- externals}
write.csv(summary_df,'tmp/tmp_summary_output.csv',row.names=F)
""")
tmp_test_results = pd.read_csv('tmp/tmp_test_results.csv')
tmp_forecast = pd.read_csv('tmp/tmp_forecast.csv')
self.forecasts[call_me] = tmp_forecast['forecast'].to_list()
self.info[call_me]['holdout_periods'] = test_length
self.info[call_me]['model_form'] = tmp_forecast['model_form'][0]
self.info[call_me]['test_set_actuals'] = tmp_test_results['actual'].to_list()
self.info[call_me]['test_set_predictions'] = tmp_test_results['forecast'].to_list()
self._metrics(call_me)
self.feature_importance[call_me] = pd.read_csv('tmp/tmp_summary_output.csv',index_col=0)
def forecast_arima(self,test_length=1,Xvars=None,order=(0,0,0),seasonal_order=(0,0,0,0),trend=None,call_me='arima',**kwargs):
""" ARIMA model from statsmodels: https://www.statsmodels.org/stable/generated/statsmodels.tsa.arima.model.ARIMA.html
the args endog, exog, and dates passed automatically
the args order, seasonal_order, and trend should be specified in the method
all other arguments in the ARIMA() function can be passed to kwargs
using this framework, the following model types can be specified:
AR, MA, ARMA, ARIMA, SARIMA, regression with ARIMA errors
this is meant for manual arima modeling; for a more automated implementation, see the forecast_auto_arima() and forecast_sarimax13() methods