Skip to content

Instantly share code, notes, and snippets.

@madagra
Created April 26, 2020 11:00
Show Gist options
  • Save madagra/44b5ee560f4e9c5f7ab034a473df6163 to your computer and use it in GitHub Desktop.
Save madagra/44b5ee560f4e9c5f7ab034a473df6163 to your computer and use it in GitHub Desktop.
Recursive strategy time series forecasting
def recursive_forecast(y, model, lags,
n_steps=FCAST_STEPS, step="1H"):
"""
Parameters
----------
y: pd.Series holding the input time-series to forecast
model: pre-trained machine learning model
lags: list of lags used for training the model
n_steps: number of time periods in the forecasting horizon
step: forecasting time period
Returns
-------
fcast_values: pd.Series with forecasted values
"""
# get the dates to forecast
last_date = y.index[-1] + pd.Timedelta(hours=1)
fcast_range = pd.date_range(last_date,
periods=n_steps,
freq=step)
fcasted_values = []
target = y.copy()
for date in fcast_range:
# build target time series using previously forecast value
new_point = fcasted_values[-1] if len(fcasted_values) > 0 else 0.0
target = target.append(pd.Series(index=[date], data=new_point))
# build feature vector using previous forecast values
features = create_ts_features(target, lags=lags)
# forecast
predictions = model.predict(features)
fcasted_values.append(predictions[-1])
return pd.Series(index=fcast_range, data=fcasted_values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment