Custom predictors for recursive multi-step forecasting¶
It may be interesting to include additional characteristics of the time series in addition to the lags, for example, the moving average of the n last values can be used to capture the trend of the series.
The ForecasterAutoregCustom class is very similar to the ForecasterAutoreg class described in the previous section, but it is the user who defines the function used to create the predictors.
# Custom function to create poredictors# ==============================================================================defcreate_predictors(y):''' Create first 10 lags of a time series. Calculate moving average with window 20. '''X_train=pd.DataFrame({'y':y.copy()})foriinrange(0,10):X_train[f'lag_{i+1}']=X_train['y'].shift(i)X_train['moving_avg']=X_train['y'].rolling(20).mean()X_train=X_train.drop(columns='y').tail(1).to_numpy()returnX_train
1 2 3 4 5 6 7 8 910
# Create and fit forecaster# ==============================================================================forecaster=ForecasterAutoregCustom(regressor=RandomForestRegressor(random_state=123),fun_predictors=create_predictors,window_size=20)forecaster.fit(y=data_train)forecaster
# Predict# ==============================================================================steps=36predictions=forecaster.predict(steps=steps)# Add datetime index to predictionspredictions=pd.Series(data=predictions,index=data_test.index)predictions.head(3)
# When using as regressor LinearRegression, Ridge or Lasso# forecaster.get_coef()# When using as regressor RandomForestRegressor or GradientBoostingRegressorforecaster.get_feature_importances()