Skip to content

Instantly share code, notes, and snippets.

@ChadFulton
Created February 9, 2019 01:41
Show Gist options
  • Save ChadFulton/3e7f5cb71d71a137c654171dc38e3c2c to your computer and use it in GitHub Desktop.
Save ChadFulton/3e7f5cb71d71a137c654171dc38e3c2c to your computer and use it in GitHub Desktop.
SARIMAX - Forecasting weekly data
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Forecasts\n",
"2001-10-28/2001-11-03 -5.533356\n",
"2001-11-04/2001-11-10 -2.526965\n",
"2001-11-11/2001-11-17 0.475321\n",
"Freq: W-SAT, dtype: float64\n",
"\n",
"Actual data\n",
"2001-10-28/2001-11-03 -5.533356\n",
"2001-11-04/2001-11-10 -2.526965\n",
"2001-11-11/2001-11-17 0.475321\n",
"Freq: W-SAT, dtype: float64\n"
]
}
],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"import statsmodels.api as sm\n",
"\n",
"from scipy.signal import lfilter\n",
"\n",
"# Simulate some data\n",
"nobs = 100\n",
"rs = np.random.RandomState(seed=1234)\n",
"# (I made the shocks really small so that it'd be obvious\n",
"# that SARIMAX was forecasting the correct periods)\n",
"eps = lfilter([1], [1, -0.5], rs.normal(scale=1e-10, size=nobs))\n",
"exog = rs.normal(size=(nobs, 2))\n",
"beta = np.array([5, -2])\n",
"endog = exog.dot(beta) + eps\n",
"\n",
"# Set the data be be weekly, anchored to Saturday\n",
"index = pd.PeriodIndex(start='2000-01', periods=nobs, freq='W-SAT')\n",
"endog = pd.Series(endog, index=index)\n",
"exog = pd.DataFrame(exog, index=index)\n",
"\n",
"# Setup the dates we want to estimate the model on and forecast until\n",
"end_estimation = pd.Period('2001-10-27', freq=endog.index.freq)\n",
"end_forecast = pd.Period('2001-11-17', freq=endog.index.freq)\n",
"\n",
"# Setup the model and just smooth at the correct parameters\n",
"# so that we can check how forecast is doing\n",
"mod = sm.tsa.SARIMAX(endog.loc[:end_estimation], exog.loc[:end_estimation], order=(1, 0, 0))\n",
"res = mod.smooth([5, -2, 0.5, 1e-10])\n",
"\n",
"# Make the forecasts\n",
"print('Forecasts')\n",
"print(res.forecast(end_forecast, exog=exog.loc[end_estimation + 1:end_forecast]))\n",
"print('\\nActual data')\n",
"print(endog.loc[end_estimation + 1:end_forecast])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment