In this lab, we go through two data illustrations: an ARIMA model for quarterly GNP, and a SARIMA model for monthly retail sales of beer, wine and liquor stores. In both cases, the motivating question is the same: we want to predict the next few values of the series. We will first look at some simple, intuitive ways of doing this, and then argue that the ARIMA and SARIMA models are natural refinements of these simple methods.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.arima.model import ARIMA
import warnings
warnings.filterwarnings("ignore") # this suppresses convergence warnings from the ARIMA functionPart One: ARIMA for quarterly GNP¶
The data and the question¶
The dataset is quarterly US Gross National Product (GNP) from FRED (https://
gnp = pd.read_csv("GNP_05Nov2026.csv")
print(gnp.head())
print(gnp.tail())
dates = pd.to_datetime(gnp['observation_date']) # the first day of each quarter
y = gnp['GNP'].to_numpy()
n = len(y)
print("Number of quarters:", n, "; first quarter starts on:", dates.iloc[0].date(), "; last quarter starts on:", dates.iloc[-1].date())
plt.figure(figsize = (12, 5))
plt.plot(dates, y, color = 'black')
plt.xlabel('Year')
plt.ylabel('GNP (billions of dollars)')
plt.title('Quarterly US GNP')
plt.show() observation_date GNP
0 1947-01-01 244.142
1 1947-04-01 247.063
2 1947-07-01 250.716
3 1947-10-01 260.981
4 1948-01-01 267.133
observation_date GNP
313 2025-04-01 30576.464
314 2025-07-01 31145.018
315 2025-10-01 31508.490
316 2026-01-01 31885.228
317 2026-04-01 32559.355
Number of quarters: 318 ; first quarter starts on: 1947-01-01 ; last quarter starts on: 2026-04-01

The last observation is for the quarter April-June 2026. The question we want to answer is: what will GNP be in the next quarter (July-September 2026)? And in the next four quarters (up to April-June 2027)?
The plot shows that GNP is not the kind of series that fluctuates around a fixed level: it has grown more than a hundredfold since 1947, and it keeps growing. So it does not make sense to fit a model to the GNP values directly which pulls the series back towards a fixed mean (such as a stable AR model). On the other hand, the growth rate of GNP from one quarter to the next is a quantity which is much more stable over time. This is the key idea behind everything that follows.
Quarterly growth rates¶
As usual, we take logarithms. The difference of log GNP between consecutive quarters is the quarterly growth rate:
which is the percentage change in GNP from quarter to quarter (the approximation for near 1 is what makes this a percentage change). Multiplying by 100 is just for convenience, so that the numbers are percentages.
ylog = np.log(y)
g = 100 * np.diff(ylog) # quarterly growth rates in percent: g_t = 100 * (log y_t - log y_{t-1})
dates_g = dates[1:] # the growth rate g_t belongs to quarter t (the later of the two quarters)
print("Number of growth rates:", len(g))
print("Average quarterly growth rate (percent):", np.round(np.mean(g), 3))
print("Standard deviation of the growth rates (percent):", np.round(np.std(g), 3))
fig, ax = plt.subplots(1, 2, figsize = (14, 4))
ax[0].plot(dates, ylog, color = 'black')
ax[0].set_title('Log GNP')
ax[0].set_xlabel('Year')
ax[1].plot(dates_g, g, color = 'black')
ax[1].axhline(np.mean(g), color = 'red', linestyle = '--', label = 'average growth rate')
ax[1].set_title('Quarterly growth rates of GNP (percent)')
ax[1].set_xlabel('Year')
ax[1].legend()
plt.tight_layout()
plt.show()Number of growth rates: 317
Average quarterly growth rate (percent): 1.544
Standard deviation of the growth rates (percent): 1.28

Unlike GNP itself, the growth rates fluctuate around a fixed level (about 1.5% per quarter) with no trend. The two extreme values are the pandemic quarters of 2020: a fall of about 9% followed by a rise of about 8.5%.
print("Most negative growth rate:", np.round(np.min(g), 2), "percent, in the quarter starting on", dates_g.iloc[np.argmin(g)].date())
print("Most positive growth rate:", np.round(np.max(g), 2), "percent, in the quarter starting on", dates_g.iloc[np.argmax(g)].date())Most negative growth rate: -8.95 percent, in the quarter starting on 2020-04-01
Most positive growth rate: 8.45 percent, in the quarter starting on 2020-07-01
Predicting GNP is the same as predicting growth rates. Suppose we have predictions of the growth rates for the next quarters. Since , the corresponding predictions of GNP are
In other words, we start from the last observed GNP value, and grow it by the predicted growth rates, one quarter at a time. The following function does this conversion.
def gnp_from_growth(last_value, growth_forecasts):
# last_value: the last observed value of the series
# growth_forecasts: predicted growth rates (in percent) for the next k periods
# returns: the predicted values of the series for the next k periods
return last_value * np.exp(np.cumsum(growth_forecasts) / 100)Two simple ways of predicting the growth rates¶
Method 1 (historical average). The growth rates have fluctuated around a fixed level in the past. The simplest prediction is to assume that the future growth rates will equal this level, which we estimate by the average of all the past growth rates (about 1.54% per quarter).
Method 2 (recent average). One might object that the data from 1947 is not very relevant for predicting growth in 2026, and that the recent growth rates matter more. So we could instead use the average of the growth rates over the last two years (eight quarters), which is about 1.36%.
Both methods predict a constant growth rate for all future quarters; they differ only in which constant. Let us compute the resulting GNP predictions for the next four quarters.
k = 4 # forecast horizon: the next four quarters
future_dates = pd.date_range(start = dates.iloc[-1], periods = k + 1, freq = 'QS')[1:] # the first days of the next four quarters
print("Quarters to be predicted start on:", [d.date() for d in future_dates])
g_hist = np.mean(g) # Method 1: the historical average growth rate
n_recent = 8
g_recent = np.mean(g[-n_recent:]) # Method 2: the average growth rate over the last 8 quarters
print("Historical average growth rate:", np.round(g_hist, 3))
print("Average growth rate over the last", n_recent, "quarters:", np.round(g_recent, 3))
print("The last", n_recent, "growth rates:", np.round(g[-n_recent:], 3))
fcast_gnp_hist = gnp_from_growth(y[-1], np.repeat(g_hist, k))
fcast_gnp_recent = gnp_from_growth(y[-1], np.repeat(g_recent, k))
print("\nLast observed GNP:", y[-1])
print(pd.DataFrame({'Quarter starting on': future_dates.date,
'Method 1 (historical average)': np.round(fcast_gnp_hist, 1),
'Method 2 (recent average)': np.round(fcast_gnp_recent, 1)}).to_string(index = False))Quarters to be predicted start on: [datetime.date(2026, 7, 1), datetime.date(2026, 10, 1), datetime.date(2027, 1, 1), datetime.date(2027, 4, 1)]
Historical average growth rate: 1.544
Average growth rate over the last 8 quarters: 1.357
The last 8 growth rates: [0.941 1.437 0.803 1.39 1.842 1.16 1.189 2.092]
Last observed GNP: 32559.355
Quarter starting on Method 1 (historical average) Method 2 (recent average)
2026-07-01 33065.8 33004.1
2026-10-01 33580.2 33455.0
2027-01-01 34102.5 33912.0
2027-04-01 34633.0 34375.2
n_show = 24 # we show the last 24 quarters (six years) of the data in the plot
plot_dates = future_dates.insert(0, dates.iloc[-1]) # the last observed quarter followed by the four future quarters (so that the prediction lines start from the last data point)
plt.figure(figsize = (12, 5))
plt.plot(dates.iloc[-n_show:], y[-n_show:], color = 'black', marker = 'o', markersize = 3, label = 'Data (last six years)')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_gnp_hist]), color = 'blue', marker = 'o', markersize = 3, label = 'Method 1: historical average growth')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_gnp_recent]), color = 'green', marker = 'o', markersize = 3, label = 'Method 2: recent average growth')
plt.axvline(dates.iloc[-1], color = 'gray', linestyle = '--')
plt.xlabel('Year')
plt.ylabel('GNP (billions of dollars)')
plt.title('GNP predictions for the next four quarters from the two simple methods')
plt.legend(loc = 'upper left')
plt.show()
The two methods give somewhat different answers, and there is no principled way of choosing between them: Method 1 ignores the recent past completely, while Method 2 trusts it completely (and the choice of eight quarters is arbitrary; with four quarters instead of eight, the recent average becomes 1.57%). Note also that the average of eight growth rates is itself quite noisy: the growth rates have a standard deviation of about 1.3 percentage points, so the average of eight of them has a standard error of about percentage points.
A third possibility, which lies between the two methods, is to check whether the growth rates have some structure which can be used for prediction: for instance, is a quarter of above-average growth more likely to be followed by another quarter of above-average growth? If yes, then the recent growth rates carry some information about the next growth rate, and we should use the recent values partially, instead of either ignoring them (Method 1) or trusting them fully (Method 2). This is exactly what an ARMA model for the growth rates does.
Is there structure in the growth rates? Sample ACF and PACF¶
In the last lab, we saw that the sample ACF and the sample PACF are the standard diagnostics for finding a suitable ARMA model for a series which fluctuates around a fixed level. Let us look at them for the growth rates.
h_max = 20
fig, ax = plt.subplots(1, 2, figsize = (14, 4))
plot_acf(g, lags = h_max, ax = ax[0])
ax[0].set_title('Sample ACF of the growth rates')
plot_pacf(g, lags = h_max, ax = ax[1], method = 'ols')
ax[1].set_title('Sample PACF of the growth rates')
plt.tight_layout()
plt.show()
print("Sample ACF at lags 1-6:", np.round(acf(g, nlags = 6)[1:], 3))
print("Sample PACF at lags 1-6:", np.round(pacf(g, nlags = 6, method = 'ols')[1:], 3))
Sample ACF at lags 1-6: [ 0.248 0.257 0.091 0.022 -0.019 -0.009]
Sample PACF at lags 1-6: [ 0.248 0.208 -0.013 -0.053 -0.034 0.01 ]
The sample ACF and the sample PACF are both clearly positive at lags 1 and 2 (about 0.25 each), and essentially zero after that. (There are also some small positive autocorrelations at longer lags, around lags 9-11 and 16-20, i.e., 2.5 to 5 years, which hint at slow business-cycle swings in growth; they are too small to be useful for prediction, and we ignore them.) So there is some structure: a quarter of above-average growth tends to be followed by above-average growth in the next two quarters. Since the PACF cuts off after lag 2, a natural model for the growth rates is AR(2):
(Since the ACF also cuts off after lag 2, MA(2) is another natural candidate; we will see below that it gives almost the same predictions.) We fit the AR(2) model using the ARIMA function with order . Recall from the last lab that the ARIMA function parametrizes the model via the mean (reported as const), and not via the intercept .
md_ar2 = ARIMA(g, order = (2, 0, 0)).fit()
print(md_ar2.summary()) SARIMAX Results
==============================================================================
Dep. Variable: y No. Observations: 317
Model: ARIMA(2, 0, 0) Log Likelihood -510.992
Date: Fri, 13 Nov 2026 AIC 1029.984
Time: 18:31:04 BIC 1045.019
Sample: 0 HQIC 1035.990
- 317
Covariance Type: opg
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
const 1.5435 0.141 10.919 0.000 1.266 1.821
ar.L1 0.1955 0.025 7.879 0.000 0.147 0.244
ar.L2 0.2070 0.066 3.157 0.002 0.078 0.336
sigma2 1.4704 0.038 39.024 0.000 1.397 1.544
===================================================================================
Ljung-Box (L1) (Q): 0.00 Jarque-Bera (JB): 8092.89
Prob(Q): 0.96 Prob(JB): 0.00
Heteroskedasticity (H): 1.60 Skew: -0.11
Prob(H) (two-sided): 0.02 Kurtosis: 27.75
===================================================================================
Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).
The estimates are , , and . Note that is somewhat smaller than the standard deviation of the growth rates (1.28): the AR(2) model explains some, but not much, of the variability of the growth rates.
How does the AR(2) model predict? The prediction for the next quarter is obtained by setting to its mean (zero) in the AR(2) equation:
In words: start with the long-run average growth rate (this is Method 1), and then adjust it by a fraction of the deviations of the last two growth rates from the long-run average. The fractions and are estimated from the data, instead of being fixed in advance. With , we would get Method 1 exactly. Method 2 can also be written in this form: it is the AR(8) equation with all eight coefficients fixed at and no constant term (since the coefficients add up to one, there is no long-run level to which the predictions return). The AR(2) model is in between: it uses the recent growth rates, but only to the extent that the data says they are informative. For two quarters ahead, we use the same equation with replaced by its prediction :
and so on. Because and are small, the adjustments die out quickly and the predictions approach after a few quarters. Below we compute the first two predictions by hand and check that they coincide with the output of the get_forecast function (get_forecast(k) is the same as get_prediction(start = n, end = n + k - 1) that we used in previous labs).
mu_hat, phi1_hat, phi2_hat = md_ar2.params[0], md_ar2.params[1], md_ar2.params[2]
g_next1 = mu_hat + phi1_hat * (g[-1] - mu_hat) + phi2_hat * (g[-2] - mu_hat)
g_next2 = mu_hat + phi1_hat * (g_next1 - mu_hat) + phi2_hat * (g[-1] - mu_hat)
print("Predictions for the next two quarters computed by hand:", np.round([g_next1, g_next2], 4))
fcast_g_ar2 = md_ar2.get_forecast(k).predicted_mean
print("Predictions for the next four quarters from get_forecast:", np.round(fcast_g_ar2, 4))
print("For comparison: historical average", np.round(g_hist, 4), "and recent average", np.round(g_recent, 4))Predictions for the next two quarters computed by hand: [1.5773 1.6637]
Predictions for the next four quarters from get_forecast: [1.5773 1.6637 1.574 1.5744]
For comparison: historical average 1.5436 and recent average 1.3568
The last two growth rates (1.19% and 2.09%) are, on average, slightly above , and so the AR(2) predictions are slightly above the historical average (and above the recent average, which was pulled down by a couple of weak quarters in 2024-25).
Choosing and by AIC and BIC¶
Instead of reading the orders off the ACF and PACF plots, we can fit all ARMA(, ) models with (36 models) to the growth rates and compare their AIC and BIC values. Recall that smaller values are better, and that both criteria reward goodness of fit (the maximized log-likelihood) and penalize the number of parameters, with BIC penalizing more heavily than AIC.
One practical detail: the ARIMA function maximizes the likelihood numerically, and for some of the larger models, the default number of iterations (50) is not enough for the optimization to converge. We therefore increase the maximum number of iterations with the method_kwargs argument (this was mentioned in the Lecture 21 notes). We also record, for each model, whether the optimization converged.
pmax, qmax = 5, 5
results = []
for p in range(pmax + 1):
for q in range(qmax + 1):
md = ARIMA(g, order = (p, 0, q)).fit(method_kwargs = {'maxiter': 1000})
results.append({'p': p, 'q': q, 'AIC': md.aic, 'BIC': md.bic, 'converged': md.mle_retvals['converged']})
results_df = pd.DataFrame(results)
print("Models sorted by AIC (best first):")
print(results_df.sort_values('AIC').head(6).to_string(index = False))
print("\nModels sorted by BIC (best first):")
print(results_df.sort_values('BIC').head(6).to_string(index = False))
best_aic = results_df.loc[results_df['AIC'].idxmin()]
best_bic = results_df.loc[results_df['BIC'].idxmin()]
p_aic, q_aic = int(best_aic['p']), int(best_aic['q'])
p_bic, q_bic = int(best_bic['p']), int(best_bic['q'])
print("\nBest model by AIC: ARMA(%d, %d)" % (p_aic, q_aic))
print("Best model by BIC: ARMA(%d, %d)" % (p_bic, q_bic))Models sorted by AIC (best first):
p q AIC BIC converged
5 3 1021.495955 1059.084972 True
4 3 1024.374522 1058.204638 True
4 2 1024.976902 1055.048116 True
3 4 1026.526154 1060.356270 True
5 4 1027.123690 1068.471609 True
5 5 1027.470467 1072.577289 True
Models sorted by BIC (best first):
p q AIC BIC converged
2 0 1029.983870 1045.019477 True
0 2 1032.305467 1047.341074 True
1 2 1030.875734 1049.670243 True
0 3 1030.998618 1049.793126 True
1 1 1035.101112 1050.136719 True
3 0 1031.933848 1050.728357 True
Best model by AIC: ARMA(5, 3)
Best model by BIC: ARMA(2, 0)
BIC picks AR(2), which is the model suggested by the ACF and PACF plots, with MA(2) and ARMA(1, 2) close behind. AIC, on the other hand, picks a much larger model, ARMA(5, 3), with eight AR and MA coefficients. This is a common situation: when many models are compared, AIC has a tendency to pick models that are too large (its penalty for extra parameters is weaker than that of BIC). We will go with the BIC choice, AR(2), because it is simple, interpretable, and consistent with the ACF/PACF; but we keep the AIC model around and will check later whether its extra complexity actually helps in prediction. Below are the predicted growth rates for the next four quarters from the top models.
md_aic = ARIMA(g, order = (p_aic, 0, q_aic)).fit(method_kwargs = {'maxiter': 1000})
md_ma2 = ARIMA(g, order = (0, 0, 2)).fit()
md_arma12 = ARIMA(g, order = (1, 0, 2)).fit()
print(pd.DataFrame({'Quarter starting on': future_dates.date,
'AR(2)': np.round(md_ar2.get_forecast(k).predicted_mean, 3),
'MA(2)': np.round(md_ma2.get_forecast(k).predicted_mean, 3),
'ARMA(1, 2)': np.round(md_arma12.get_forecast(k).predicted_mean, 3),
'ARMA(%d, %d) (AIC choice)' % (p_aic, q_aic): np.round(md_aic.get_forecast(k).predicted_mean, 3)}).to_string(index = False))Quarter starting on AR(2) MA(2) ARMA(1, 2) ARMA(5, 3) (AIC choice)
2026-07-01 1.577 1.583 1.551 1.219
2026-10-01 1.664 1.709 1.678 1.224
2027-01-01 1.574 1.543 1.594 1.183
2027-04-01 1.574 1.543 1.562 1.355
The three models at the top of the BIC list give essentially the same predictions, so the choice among them does not matter much. The AIC model predicts noticeably lower growth.
Checking the residuals of AR(2)¶
If the AR(2) model is adequate, its residuals should look like i.i.d noise. As in Lecture 21, we drop the first two residuals (they are not meaningful residuals, since and cannot be predicted from two previous values) and look at the sample ACF of the rest.
resid = md_ar2.resid[2:]
fig, ax = plt.subplots(1, 2, figsize = (14, 4))
ax[0].plot(dates_g.iloc[2:], resid, color = 'black', linewidth = 1)
ax[0].axhline(0, color = 'red', linestyle = '--')
ax[0].set_title('Residuals of the AR(2) model for the growth rates')
plot_acf(resid, lags = 30, ax = ax[1])
ax[1].set_title('Sample ACF of the residuals')
plt.tight_layout()
plt.show()
The residual ACF shows no autocorrelation worth modeling (the autocorrelations at lags 1 and 2 have disappeared). The residuals do show the two huge pandemic values; the model cannot explain these, and no model based only on past GNP values could. Note also that the residuals are more variable before the mid-1980s than after (a well-known feature of US macroeconomic data); the model assumes a constant variance, which is a simplification that we accept here.
Predicting GNP: this is the ARIMA model¶
What we have done so far is: (i) take logarithms, (ii) difference once to get the growth rates, (iii) fit an ARMA(, ) model (with a mean) to the growth rates, and (iv) convert the growth rate predictions back to GNP predictions by summing them up and exponentiating. Steps (ii), (iii) and (iv) are exactly what the ARIMA(, 1, ) model for log GNP does. In the notation of Lecture 21, ARIMA(, 1, ) is the model for : the differences (the growth rates, up to the factor 100) follow an ARMA(, ) model with mean . The ARIMA function does the differencing, fits the ARMA model to the differences, and then undoes the differencing when computing forecasts (so that its forecasts are forecasts of log GNP, not of the growth rates).
One detail (also from Lecture 21): when , the ARIMA function sets by default. Since the growth rates have a clearly nonzero mean, we must ask for to be included by specifying trend = 't'. The estimated mean then appears in the output under the name x1.
md_arima = ARIMA(ylog, order = (2, 1, 0), trend = 't').fit()
print(md_arima.summary())
print("Mean growth rate (in percent) from the ARIMA fit:", np.round(100 * md_arima.params[0], 4), "; from the AR(2) fit to the growth rates:", np.round(md_ar2.params[0], 4))
print("AR coefficients from the ARIMA fit:", np.round(md_arima.params[1:3], 4), "; from the AR(2) fit to the growth rates:", np.round(md_ar2.params[1:3], 4)) SARIMAX Results
==============================================================================
Dep. Variable: y No. Observations: 318
Model: ARIMA(2, 1, 0) Log Likelihood 948.847
Date: Fri, 13 Nov 2026 AIC -1889.693
Time: 18:32:00 BIC -1874.658
Sample: 0 HQIC -1883.687
- 318
Covariance Type: opg
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
x1 0.0154 0.001 10.892 0.000 0.013 0.018
ar.L1 0.1960 0.025 7.922 0.000 0.148 0.245
ar.L2 0.2083 0.065 3.186 0.001 0.080 0.336
sigma2 0.0001 3.76e-06 39.053 0.000 0.000 0.000
===================================================================================
Ljung-Box (L1) (Q): 0.00 Jarque-Bera (JB): 8112.24
Prob(Q): 0.96 Prob(JB): 0.00
Heteroskedasticity (H): 1.60 Skew: -0.10
Prob(H) (two-sided): 0.02 Kurtosis: 27.78
===================================================================================
Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).
Mean growth rate (in percent) from the ARIMA fit: 1.5433 ; from the AR(2) fit to the growth rates: 1.5435
AR coefficients from the ARIMA fit: [0.196 0.2083] ; from the AR(2) fit to the growth rates: [0.1955 0.207 ]
The parameter estimates are the same as before (the x1 coefficient is in log units: percent; and sigma2 is also in log units). The predictions are also the same, as we check below. One advantage of the ARIMA function is that it directly provides standard errors and prediction intervals for the forecasts of log GNP (which we convert to GNP by exponentiating).
fcast = md_arima.get_forecast(k)
fcast_gnp_arima = np.exp(fcast.predicted_mean) # predictions of GNP from the ARIMA model
ci = fcast.conf_int(alpha = 0.05) # 95% prediction intervals for log GNP
lower, upper = np.exp(ci[:, 0]), np.exp(ci[:, 1]) # converted to GNP
print("GNP predictions from ARIMA(2, 1, 0) with drift: ", np.round(fcast_gnp_arima, 1))
print("GNP predictions from AR(2) on the growth rates: ", np.round(gnp_from_growth(y[-1], fcast_g_ar2), 1))
forecast_table = pd.DataFrame({'Quarter starting on': future_dates.date,
'Method 1 (historical average)': np.round(fcast_gnp_hist, 1),
'Method 2 (recent average)': np.round(fcast_gnp_recent, 1),
'ARIMA(2, 1, 0)': np.round(fcast_gnp_arima, 1),
'95% lower': np.round(lower, 1),
'95% upper': np.round(upper, 1)})
print()
print(forecast_table.to_string(index = False))GNP predictions from ARIMA(2, 1, 0) with drift: [33076.9 33632. 34165.5 34707.7]
GNP predictions from AR(2) on the growth rates: [33077. 33631.9 34165.4 34707.6]
Quarter starting on Method 1 (historical average) Method 2 (recent average) ARIMA(2, 1, 0) 95% lower 95% upper
2026-07-01 33065.8 33004.1 33076.9 32300.3 33872.1
2026-10-01 33580.2 33455.0 33632.0 32409.1 34901.0
2027-01-01 34102.5 33912.0 34165.5 32484.2 35933.9
2027-04-01 34633.0 34375.2 34707.7 32614.1 36935.8
plt.figure(figsize = (12, 5))
plt.plot(dates.iloc[-n_show:], y[-n_show:], color = 'black', marker = 'o', markersize = 3, label = 'Data (last six years)')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_gnp_hist]), color = 'blue', marker = 'o', markersize = 3, label = 'Method 1: historical average growth')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_gnp_recent]), color = 'green', marker = 'o', markersize = 3, label = 'Method 2: recent average growth')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_gnp_arima]), color = 'red', marker = 'o', markersize = 3, label = 'ARIMA(2, 1, 0) with drift')
plt.fill_between(future_dates, lower, upper, color = 'red', alpha = 0.15, label = '95% prediction interval (ARIMA)')
plt.axvline(dates.iloc[-1], color = 'gray', linestyle = '--')
plt.xlabel('Year')
plt.ylabel('GNP (billions of dollars)')
plt.title('GNP predictions for the next four quarters')
plt.legend(loc = 'upper left')
plt.show()
The three point predictions are close to each other (the differences between them are small compared to the width of the prediction intervals), which is reassuring. The ARIMA prediction for the next quarter is slightly above the other two, because the last two growth rates were above average and the model carries a fraction of this over to the next quarter. The prediction intervals widen with the horizon: the uncertainty about GNP four quarters ahead is the accumulated uncertainty of four growth rates.
Why is the ARIMA model more sensible than the simple methods?¶
Here are the main reasons.
The ARIMA model contains the simple methods as special cases, and lets the data decide between them. Method 1 is the ARIMA model with . Putting weight on recent growth rates (as in Method 2) corresponds to nonzero AR coefficients. The ARIMA model estimates these weights by maximum likelihood, instead of fixing them by an arbitrary rule such as “average the last eight quarters”.
The predictions have the right shape. If the last few quarters were unusually strong, the model predicts somewhat stronger-than-average growth in the next quarter or two (because of the positive autocorrelation), but then returns to the long-run average, since the data says that the effect of a strong quarter fades away quickly. Method 2 would instead extrapolate the recent average forever.
The model gives honest prediction intervals, which the simple methods do not.
Whether these advantages translate into more accurate predictions is an empirical question, which we can check by going back in time. We pretend that we are at the end of each quarter from 2000 onwards, use only the data up to that quarter to predict the growth rates of the next four quarters by each method, and record the prediction errors. The models are re-fitted at each origin (using only the past data). This gives more than a hundred prediction exercises per method, and we summarize the errors by the root mean squared error (RMSE) at each horizon . This takes about a minute because of the repeated fitting of the large AIC model.
H = 4
t_first = np.where(dates.dt.year >= 2000)[0][0] # position of the first quarter of 2000: this is our first forecast origin
origins = range(t_first, len(g) - H + 1)
methods = ['Method 1 (historical average)', 'Method 2 (average of last 8)', 'Method 2 (average of last 4)',
'AR(2) (BIC choice)', 'ARMA(%d, %d) (AIC choice)' % (p_aic, q_aic)]
errors = {m: [] for m in methods}
target_in_2020 = []
for t in origins:
past = g[:t] # the growth rates known at the origin (the data up to and including quarter t)
future = g[t:t+H] # the next H growth rates, which we are trying to predict
errors[methods[0]].append(future - np.mean(past))
errors[methods[1]].append(future - np.mean(past[-8:]))
errors[methods[2]].append(future - np.mean(past[-4:]))
md = ARIMA(past, order = (2, 0, 0)).fit()
errors[methods[3]].append(future - md.get_forecast(H).predicted_mean)
md = ARIMA(past, order = (p_aic, 0, q_aic)).fit(method_kwargs = {'maxiter': 1000})
errors[methods[4]].append(future - md.get_forecast(H).predicted_mean)
target_in_2020.append(np.any(dates_g.iloc[t:t+H].dt.year == 2020)) # does one of the H target quarters fall in 2020?
target_in_2020 = np.array(target_in_2020)
def rmse_table(errors, keep):
tab = {m: np.sqrt(np.mean(np.array(e)[keep]**2, axis = 0)) for m, e in errors.items()}
return pd.DataFrame(tab, index = ['h = %d' % h for h in range(1, H + 1)]).T
print("Number of forecast origins:", len(origins), "(from", dates.iloc[t_first].date(), "to", dates.iloc[len(g) - H].date(), ")")
print("\nRMSE of the growth rate predictions (in percentage points), all origins:")
print(rmse_table(errors, np.ones(len(origins), dtype = bool)).round(3))
print("\nRMSE after dropping the origins for which one of the four target quarters is in 2020:")
print(rmse_table(errors, ~target_in_2020).round(3))Number of forecast origins: 102 (from 2000-01-01 to 2025-04-01 )
RMSE of the growth rate predictions (in percentage points), all origins:
h = 1 h = 2 h = 3 h = 4
Method 1 (historical average) 1.553 1.553 1.550 1.552
Method 2 (average of last 8) 1.556 1.542 1.559 1.576
Method 2 (average of last 4) 1.617 1.562 1.612 1.624
AR(2) (BIC choice) 1.697 1.547 1.553 1.550
ARMA(5, 3) (AIC choice) 1.759 1.630 1.606 1.608
RMSE after dropping the origins for which one of the four target quarters is in 2020:
h = 1 h = 2 h = 3 h = 4
Method 1 (historical average) 0.928 0.921 0.904 0.906
Method 2 (average of last 8) 0.842 0.859 0.858 0.887
Method 2 (average of last 4) 0.794 0.815 0.900 0.919
AR(2) (BIC choice) 0.692 0.752 0.807 0.844
ARMA(5, 3) (AIC choice) 0.830 0.856 0.916 0.963
In the first table, all methods have RMSEs between 1.55 and 1.75 percentage points, with hardly any difference across horizons. This is because the errors are dominated by the two pandemic quarters of 2020 (errors of around 10 percentage points), which no method could have predicted. In fact, at the AR(2) model does slightly worse than the simple methods in this table: after the 9% fall in the second quarter of 2020, the model predicted continued below-average growth for the next quarter (a fraction of the fall is carried over), while GNP actually rebounded by 8.5%. The historical average, which ignores the recent past, happened to be closer. The second table drops these quarters, and the picture becomes clear. The AR(2) model has the smallest RMSE at every horizon, and the gain over the simple methods is largest at (an RMSE of about 0.7 compared to about 0.9 for the historical average and 0.8-0.85 for the recent averages). As grows, the AR(2) predictions approach the historical average, and the RMSEs of the two methods approach each other. The large AIC model does worse than AR(2) at every horizon (and worse than the historical average for ), even though it fits the past data better (that is why AIC chose it): the extra coefficients are fitting noise, not structure. This is the usual danger of large models, and the reason for preferring the simpler BIC choice.
One caveat deserves mention. The AR(2) model assumes that the growth rates fluctuate around one long-run level throughout 1947-2026. In reality, the average growth rate of (nominal) GNP has varied across decades (it was higher in the 1970s and 1980s, when inflation was high, than in the 2010s). Over periods when the level shifts, Method 2 can hold its own at longer horizons, as we saw in the comparison for GDP in Lecture 21. If one is worried about this, one can fit the model to more recent data only, or use a model that allows the level of the growth rates to drift (for example, an ARIMA model with ). We shall see a version of this idea in the second part of this lab.
Part Two: SARIMA for monthly retail sales of beer, wine and liquor stores¶
The data and the question¶
The dataset is the monthly retail sales of beer, wine and liquor stores in the United States, from FRED (https://
sales = pd.read_csv("MRTSSM4453USN_10Nov2026.csv")
print(sales.head())
print(sales.tail())
dates = pd.to_datetime(sales['observation_date'])
y = sales['MRTSSM4453USN'].to_numpy().astype(float)
n = len(y)
print("Number of months:", n, "; first month:", dates.iloc[0].date(), "; last month:", dates.iloc[-1].date())
december = (dates.dt.month == 12).to_numpy()
fig, ax = plt.subplots(1, 2, figsize = (15, 4.5))
ax[0].plot(dates, y, color = 'black')
ax[0].plot(dates[december], y[december], 'o', color = 'red', markersize = 3, label = 'December')
ax[0].set_title('Monthly retail sales of beer, wine and liquor stores')
ax[0].set_ylabel('Millions of dollars')
ax[0].legend()
n_show = 60
ax[1].plot(dates.iloc[-n_show:], y[-n_show:], color = 'black', marker = 'o', markersize = 3)
ax[1].plot(dates.iloc[-n_show:][december[-n_show:]], y[-n_show:][december[-n_show:]], 'o', color = 'red', markersize = 5)
ax[1].set_title('The last five years')
plt.tight_layout()
plt.show() observation_date MRTSSM4453USN
0 1992-01-01 1414
1 1992-02-01 1444
2 1992-03-01 1496
3 1992-04-01 1569
4 1992-05-01 1707
observation_date MRTSSM4453USN
411 2026-04-01 5344
412 2026-05-01 5967
413 2026-06-01 5835
414 2026-07-01 6096
415 2026-08-01 5637
Number of months: 416 ; first month: 1992-01-01 ; last month: 2026-08-01

The last observation is for August 2026. The question is: what will the sales be in September 2026? And in each of the next twelve months (up to August 2027)?
The series has a clear upward trend and a very strong seasonal pattern: every December (red dots) is the peak of the year (the holiday season), January and February are the lowest months, and there is a smaller bump in the summer. Note also that the seasonal swings have grown with the level of the series (the December peak was about 700-1000 million dollars above the neighboring months in the 1990s, and is about 2000 million dollars above them now). When the seasonal swings are proportional to the level, taking logarithms makes the seasonal pattern stable over time, since a proportional swing becomes a constant additive swing on the log scale. So, as usual, we work with logarithms.
ylog = np.log(y)
plt.figure(figsize = (12, 4))
plt.plot(dates, ylog, color = 'black')
plt.plot(dates[december], ylog[december], 'o', color = 'red', markersize = 3)
plt.title('Log of monthly retail sales of beer, wine and liquor stores')
plt.xlabel('Year')
plt.show()
Growth rates for seasonal data: compare with the same month of the previous year¶
For GNP, we converted the problem of predicting the level into the problem of predicting the growth rates from one quarter to the next. Let us see what the month-to-month growth rates look like for this dataset.
g1 = 100 * np.diff(ylog) # month-to-month changes in log sales (times 100)
months = dates.dt.month.to_numpy()[1:] # the month to which each change belongs
plt.figure(figsize = (12, 4))
plt.plot(dates.iloc[1:][-n_show:], g1[-n_show:], color = 'black', marker = 'o', markersize = 3)
plt.axhline(0, color = 'gray', linestyle = '--')
plt.title('Month-to-month changes in log sales (times 100), last five years')
plt.xlabel('Year')
plt.show()
ratio = y[1:] / y[:-1] # ratio of each month's sales to the previous month's sales
print("Average percentage change in sales from December to January:", np.round(100 * (np.mean(ratio[months == 1]) - 1), 1), "percent")
print("Average percentage change in sales from November to December:", np.round(100 * (np.mean(ratio[months == 12]) - 1), 1), "percent")
print("Sample ACF of the month-to-month changes at lags 12, 24, 36:", np.round(acf(g1, nlags = 36)[[12, 24, 36]], 3))
Average percentage change in sales from December to January: -37.0 percent
Average percentage change in sales from November to December: 32.9 percent
Sample ACF of the month-to-month changes at lags 12, 24, 36: [0.95 0.903 0.867]
The month-to-month changes are completely dominated by the seasonal pattern: sales fall by more than a third every January and rise by about a third every December, year after year, and the sample ACF of these changes at lags 12, 24 and 36 is above 0.85. (For changes this large, the log difference and the percentage change differ noticeably: a 37% fall in sales is a log change of , which is why the January values in the plot are around -45.) These numbers tell us about the seasonal pattern, but not about how fast the business is growing. The month-to-month change is simply not the natural notion of growth for seasonal data.
The natural notion is the year-over-year growth rate: compare each month with the same month of the previous year,
This is the seasonal difference from Lecture 21 (multiplied by 100). Comparing a December with the previous December, or a February with the previous February, removes the seasonal pattern (anything that repeats every twelve months cancels out), and what is left is the growth of the business over the past year. This is also how retail sales figures are usually reported in the news (“sales were up 3% from a year ago”).
s = 12
g12 = 100 * (ylog[s:] - ylog[:-s]) # year-over-year growth rates in percent: g_t = 100 * (log y_t - log y_{t-12})
dates_12 = dates[s:] # g12 starts in January 1993 (the first month which has a 'same month last year')
print("Number of year-over-year growth rates:", len(g12))
print("Historical average of the year-over-year growth rates:", np.round(np.mean(g12), 3), "percent")
plt.figure(figsize = (12, 4))
plt.plot(dates_12, g12, color = 'black')
plt.axhline(np.mean(g12), color = 'red', linestyle = '--', label = 'historical average')
plt.axhline(0, color = 'gray', linestyle = ':')
plt.title('Year-over-year growth rates of sales (percent)')
plt.xlabel('Year')
plt.legend()
plt.show()Number of year-over-year growth rates: 404
Historical average of the year-over-year growth rates: 3.594 percent

The seasonal pattern is gone. But, unlike the GNP growth rates, the year-over-year growth rates do not fluctuate around one fixed level: they wander. They were around 3% in the 1990s, closer to 5% in the 2000s, jumped above 10% during the pandemic (when restaurants and bars were closed and people bought alcohol in stores instead), and have been around zero since 2022.
years = dates_12.dt.year.to_numpy()
for (a, b) in [(1993, 1999), (2000, 2007), (2008, 2014), (2015, 2019), (2020, 2021), (2022, 2026)]:
sel = (years >= a) & (years <= b)
print("Average year-over-year growth rate in %d-%d: %5.2f percent" % (a, b, np.mean(g12[sel])))
print("The last 12 year-over-year growth rates:", np.round(g12[-12:], 2))Average year-over-year growth rate in 1993-1999: 2.87 percent
Average year-over-year growth rate in 2000-2007: 4.73 percent
Average year-over-year growth rate in 2008-2014: 3.29 percent
Average year-over-year growth rate in 2015-2019: 4.10 percent
Average year-over-year growth rate in 2020-2021: 11.44 percent
Average year-over-year growth rate in 2022-2026: -0.73 percent
The last 12 year-over-year growth rates: [-2.69 -1.51 -5.69 -2.23 3.16 -0.61 -1.64 -0.13 -0.6 3.06 2.96 -3.23]
Simple ways of predicting seasonal data¶
Predicting sales is the same as predicting year-over-year growth rates. If is a prediction of the year-over-year growth rate for the month (with ), then the corresponding prediction of sales is
In words: take the sales in the same month of the previous year (which we have observed), and grow them by the predicted year-over-year growth rate. This automatically reproduces the seasonal pattern: the prediction for December 2026 is based on December 2025, and so on. The simple methods from Part One now become:
Method 1 (historical average): predict the future year-over-year growth rates by the historical average (3.6%).
Method 2 (recent average): predict the future year-over-year growth rates by the average over the last twelve months (about -0.8%).
k = 12 # forecast horizon: the next twelve months
future_dates = pd.date_range(start = dates.iloc[-1], periods = k + 1, freq = 'MS')[1:]
print("Months to be predicted:", future_dates[0].date(), "to", future_dates[-1].date())
base = y[-12:] # the sales in the same months of the previous year: September 2025, ..., August 2026
g12_hist = np.mean(g12)
g12_recent = np.mean(g12[-12:])
print("Historical average year-over-year growth rate:", np.round(g12_hist, 3))
print("Average year-over-year growth rate over the last 12 months:", np.round(g12_recent, 3))
fcast_hist = base * np.exp(g12_hist / 100)
fcast_recent = base * np.exp(g12_recent / 100)
n_show = 48 # the last four years of data are shown in the plot
plot_dates = future_dates.insert(0, dates.iloc[-1]) # the last observed month followed by the twelve future months
plt.figure(figsize = (12, 5))
plt.plot(dates.iloc[-n_show:], y[-n_show:], color = 'black', marker = 'o', markersize = 3, label = 'Data (last four years)')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_hist]), color = 'blue', marker = 'o', markersize = 3, label = 'Method 1: historical average growth')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_recent]), color = 'green', marker = 'o', markersize = 3, label = 'Method 2: recent average growth')
plt.axvline(dates.iloc[-1], color = 'gray', linestyle = '--')
plt.ylim(4300, 9300)
plt.xlabel('Year')
plt.ylabel('Millions of dollars')
plt.title('Sales predictions for the next twelve months from the two simple methods')
plt.legend(loc = 'upper left', ncol = 2)
plt.show()Months to be predicted: 2026-09-01 to 2027-08-01
Historical average year-over-year growth rate: 3.594
Average year-over-year growth rate over the last 12 months: -0.762

Both methods reproduce the seasonal pattern, but they disagree by more than 4%, which is a large difference for sales predictions. Since the level of the year-over-year growth rate wanders, the historical average from 1993 onwards is not a good guide to the growth rate in 2026-27, and Method 2 seems more reasonable here. But, as before, the choice of a twelve-month window is arbitrary, and the average over the last twelve months lags behind when the growth rate is changing.
Differencing again: the changes in the year-over-year growth rates¶
Let us take stock. The year-over-year growth rates behave much more like log GNP (a wandering level) than like the GNP growth rates (fluctuations around a fixed level). In Part One, our response to a wandering level was to take differences. We do the same thing here, and look at the changes in the year-over-year growth rate from one month to the next:
So is what we get by applying both a seasonal difference (, which removes the seasonal pattern and converts sales into year-over-year growth rates) and a regular difference (, which removes the wandering level of the growth rates). This is the double differencing used in Lecture 21 for the CO and airline passengers data; here we have arrived at it from the question of how to predict sales.
w = np.diff(g12) # w_t = g_t - g_{t-1}: the change in the year-over-year growth rate from last month to this month
dates_w = dates[s+1:]
print("Mean of w:", np.round(np.mean(w), 3), "; standard deviation of w:", np.round(np.std(w), 3))
plt.figure(figsize = (12, 4))
plt.plot(dates_w, w, color = 'black', linewidth = 1)
plt.axhline(0, color = 'red', linestyle = '--')
plt.title(r'Changes in the year-over-year growth rate: $w_t = g_t - g_{t-1}$ (percentage points)')
plt.xlabel('Year')
plt.show()Mean of w: -0.025 ; standard deviation of w: 3.82

The series fluctuates around zero, with no trend and no seasonal pattern. This is the kind of series that we know how to model with ARMA models. Notice the sawtooth appearance of the plot: an upward move in the year-over-year growth rate tends to be followed by a downward move in the next month, and vice versa. We will come back to this when we interpret the fitted model.
What is the simplest model for , and what does it predict? The simplest model is that is pure noise with mean zero. Under this model, the best prediction of is zero, i.e., the best prediction of next month’s year-over-year growth rate is this month’s year-over-year growth rate: , and similarly for every . The sales prediction is then
This is Method 3 (latest growth). It adapts to changes in the growth rate faster than Method 2 (it uses only the latest growth rate instead of the average of the last twelve). The price is noise: the standard deviation of is about 3.8 percentage points, so the year-over-year growth rate jumps around a lot from month to month, and the latest value is a noisy estimate of the current level of growth. The latest value, , is lower than the recent average, so Method 3 predicts lower sales than Method 2.
fcast_latest = base * np.exp(g12[-1] / 100)
print("Latest year-over-year growth rate (August 2026):", np.round(g12[-1], 3))
print(pd.DataFrame({'Month': future_dates.date,
'Method 1 (historical average)': np.round(fcast_hist, 0),
'Method 2 (recent average)': np.round(fcast_recent, 0),
'Method 3 (latest growth)': np.round(fcast_latest, 0)}).to_string(index = False))Latest year-over-year growth rate (August 2026): -3.229
Month Method 1 (historical average) Method 2 (recent average) Method 3 (latest growth)
2026-09-01 5466.0 5233.0 5105.0
2026-10-01 5845.0 5596.0 5460.0
2026-11-01 6033.0 5776.0 5635.0
2026-12-01 7596.0 7272.0 7095.0
2027-01-01 5161.0 4941.0 4821.0
2027-02-01 4953.0 4742.0 4626.0
2027-03-01 5445.0 5213.0 5086.0
2027-04-01 5540.0 5303.0 5174.0
2027-05-01 6185.0 5922.0 5777.0
2027-06-01 6049.0 5791.0 5650.0
2027-07-01 6319.0 6050.0 5902.0
2027-08-01 5843.0 5594.0 5458.0
The SARIMA model¶
Just as the ARMA model for the GNP growth rates was a refinement of “the growth rate is a constant plus noise”, the SARIMA model is a refinement of “ is pure noise”. The idea is to look for structure in that can be used for prediction, and the structure can be of two kinds:
regular (month-to-month) structure: may depend on , i.e., on how the year-over-year growth rate changed in the last few months;
seasonal (year-to-year) structure: may depend on , i.e., on what happened in the same month in previous years.
The multiplicative seasonal ARMA model of Lecture 21 handles both kinds of structure with few parameters: an ordinary ARMA(, ) model for the month-to-month structure, and a seasonal ARMA(, ) model (which is an ARMA model in which the lags are multiples of 12) for the year-to-year structure, applied one after the other. The resulting model for is
where and are the usual AR and MA polynomials, and and are their seasonal counterparts. Together with the double differencing, this is the ARIMA(, 1, ) (, 1, ) model for . Note that there is no mean parameter in this model. A constant mean for would correspond to a quadratic trend in , and the ARIMA function refuses the options trend = 'c' and trend = 't' when (a constant or a linear trend in would be eliminated by the double differencing). This is fine because the mean of is essentially zero; a nonzero mean would mean that the growth rate trends up or down forever.
The model is fit with the ARIMA function, with the orders given as order and as seasonal_order. The function takes care of the two differences, and its forecasts are forecasts of itself.
Choosing , , , . Reading the orders off the ACF and PACF of is harder than in the nonseasonal case (one has to look at the regular lags and the seasonal lags 12, 24, 36, separately, and their interactions muddy the picture). We therefore simply fit all models with and (36 models; this takes about 20 seconds), keeping fixed throughout, and compare their AIC and BIC values. As in Lecture 21, and are not part of the search: AIC and BIC can only compare models that are fit to the same series, and changing or changes the series being modeled. Our choice was made by looking at the data above.
results = []
for p in range(3):
for q in range(3):
for P in range(2):
for Q in range(2):
md = ARIMA(ylog, order = (p, 1, q), seasonal_order = (P, 1, Q, 12)).fit()
results.append({'p': p, 'd': 1, 'q': q, 'P': P, 'D': 1, 'Q': Q, 'AIC': md.aic, 'BIC': md.bic})
results_df = pd.DataFrame(results)
print("Models sorted by AIC (best first):")
print(results_df.sort_values('AIC').head(6).to_string(index = False))
print("\nModels sorted by BIC (best first):")
print(results_df.sort_values('BIC').head(6).to_string(index = False))
best_bic = results_df.loc[results_df['BIC'].idxmin()]
p_bic, q_bic, P_bic, Q_bic = int(best_bic['p']), int(best_bic['q']), int(best_bic['P']), int(best_bic['Q'])
best_aic = results_df.loc[results_df['AIC'].idxmin()]
print("\nBest model by BIC: ARIMA(%d, 1, %d) x (%d, 1, %d)_12" % (p_bic, q_bic, P_bic, Q_bic))
print("Best model by AIC: ARIMA(%d, 1, %d) x (%d, 1, %d)_12" % (best_aic['p'], best_aic['q'], best_aic['P'], best_aic['Q']))Models sorted by AIC (best first):
p d q P D Q AIC BIC
2 1 1 1 1 1 -1809.333939 -1785.340320
2 1 0 1 1 1 -1809.188465 -1789.193783
2 1 2 1 1 1 -1807.404257 -1779.411701
2 1 1 0 1 1 -1794.145499 -1774.150816
2 1 0 0 1 1 -1792.861092 -1776.865345
2 1 2 0 1 1 -1792.150665 -1768.157046
Models sorted by BIC (best first):
p d q P D Q AIC BIC
2 1 0 1 1 1 -1809.188465 -1789.193783
2 1 1 1 1 1 -1809.333939 -1785.340320
2 1 2 1 1 1 -1807.404257 -1779.411701
2 1 0 0 1 1 -1792.861092 -1776.865345
2 1 1 0 1 1 -1794.145499 -1774.150816
0 1 2 1 1 1 -1790.769920 -1770.775237
Best model by BIC: ARIMA(2, 1, 0) x (1, 1, 1)_12
Best model by AIC: ARIMA(2, 1, 1) x (1, 1, 1)_12
BIC picks ARIMA(2, 1, 0) (1, 1, 1), and AIC picks ARIMA(2, 1, 1) (1, 1, 1), which is the same model with one extra MA coefficient. The two have almost the same AIC, and they give almost the same predictions; we go with the smaller model chosen by BIC. Let us fit it and look at the estimated coefficients.
md_sarima = ARIMA(ylog, order = (p_bic, 1, q_bic), seasonal_order = (P_bic, 1, Q_bic, 12)).fit()
print(md_sarima.summary()) SARIMAX Results
==========================================================================================
Dep. Variable: y No. Observations: 416
Model: ARIMA(2, 1, 0)x(1, 1, [1], 12) Log Likelihood 909.594
Date: Fri, 13 Nov 2026 AIC -1809.188
Time: 18:35:31 BIC -1789.194
Sample: 0 HQIC -1801.273
- 416
Covariance Type: opg
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
ar.L1 -0.7840 0.048 -16.412 0.000 -0.878 -0.690
ar.L2 -0.4359 0.045 -9.690 0.000 -0.524 -0.348
ar.S.L12 0.2623 0.076 3.440 0.001 0.113 0.412
ma.S.L12 -0.8785 0.046 -19.111 0.000 -0.969 -0.788
sigma2 0.0006 4.07e-05 15.256 0.000 0.001 0.001
===================================================================================
Ljung-Box (L1) (Q): 0.38 Jarque-Bera (JB): 22.82
Prob(Q): 0.54 Prob(JB): 0.00
Heteroskedasticity (H): 1.07 Skew: 0.26
Prob(H) (two-sided): 0.71 Kurtosis: 4.04
===================================================================================
Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).
What does the fitted model say? Written out, the model ARIMA(2, 1, 0) (1, 1, 1) for is
with , (ar.L1, ar.L2), (ar.S.L12) and (ma.S.L12). Here is what the two parts of the model are doing.
The regular AR(2) part has strongly negative coefficients. If the year-over-year growth rate jumped up last month (), the model expects it to come back down this month (), and vice versa. In other words, much of the month-to-month movement in the year-over-year growth rate is temporary and reverses the following month. This makes sense: sales in a given month are affected by things like the number of weekends in the month and the timing of holidays (Easter, Thanksgiving), which also differ from the same month of the previous year. These effects produce a blip in the year-over-year growth rate for one month, which then disappears. The AR(2) part tells the model not to take the latest growth rate at face value (which is exactly what Method 3 does), but to discount the part of it that looks like a temporary blip.
The seasonal MA coefficient is close to -1. A seasonal MA coefficient near -1 nearly cancels the seasonal difference ; the effect is that the model does not rely on the same month of last year alone, but effectively averages the same month over several past years, with weights that decay geometrically (by the factor per year). This gives a less noisy estimate of the seasonal pattern than a single year, while still allowing the pattern to change slowly over time (with exactly, the pattern would be fixed forever). The small positive seasonal AR coefficient adds a little persistence from the same month of the previous year.
So the SARIMA predictions can be read as follows: start from the simple rule “same month last year, grown by the latest year-over-year growth rate” (Method 3), and then correct it in two ways: discount the temporary blips in the recent growth rates (the regular part), and smooth the seasonal pattern over several past years (the seasonal part). The sizes of the corrections are estimated from the data.
As a check that the model is adequate, we look at the residual ACF. With , the first 13 residuals are not meaningful (see Lecture 21), and we drop them.
resid = md_sarima.resid[13:]
fig, ax = plt.subplots(1, 2, figsize = (14, 4))
ax[0].plot(dates.iloc[13:], resid, color = 'black', linewidth = 1)
ax[0].axhline(0, color = 'red', linestyle = '--')
ax[0].set_title('Residuals of the SARIMA model')
plot_acf(resid, lags = 40, ax = ax[1])
ax[1].set_title('Sample ACF of the residuals')
plt.tight_layout()
plt.show()
The residual ACF has no large values: a few autocorrelations at scattered lags are slightly outside the band (the largest, about 0.24, is at lag 23), but there is no systematic pattern, and nothing of note at the seasonal lags 12 and 24. The model is adequate for our purposes. The biggest residuals are the pandemic months of 2020.
Predicting sales with the SARIMA model¶
The get_forecast function gives the predictions of for the next twelve months, together with 95% prediction intervals; we exponentiate to get back to millions of dollars. We also print the implied predictions of the year-over-year growth rates, which can be compared directly with the three simple methods.
fcast = md_sarima.get_forecast(k)
fcast_sarima = np.exp(fcast.predicted_mean)
ci = fcast.conf_int(alpha = 0.05)
lower, upper = np.exp(ci[:, 0]), np.exp(ci[:, 1])
g12_sarima = 100 * (fcast.predicted_mean - np.log(base)) # the year-over-year growth rates implied by the SARIMA predictions
print("Year-over-year growth rates (percent) predicted by the SARIMA model for the next 12 months:")
print(np.round(g12_sarima, 2))
print("For comparison: Method 1 uses", np.round(g12_hist, 2), "; Method 2 uses", np.round(g12_recent, 2), "; Method 3 uses", np.round(g12[-1], 2), "for every month.")
forecast_table = pd.DataFrame({'Month': future_dates.date,
'Method 1': np.round(fcast_hist, 0),
'Method 2': np.round(fcast_recent, 0),
'Method 3': np.round(fcast_latest, 0),
'SARIMA': np.round(fcast_sarima, 0),
'95% lower': np.round(lower, 0),
'95% upper': np.round(upper, 0)})
print()
print(forecast_table.to_string(index = False))Year-over-year growth rates (percent) predicted by the SARIMA model for the next 12 months:
[ 3.52 0.45 0.42 2.89 -1.45 1.55 3.01 1.15 0.46 1.01 0.39 3.35]
For comparison: Method 1 uses 3.59 ; Method 2 uses -0.76 ; Method 3 uses -3.23 for every month.
Month Method 1 Method 2 Method 3 SARIMA 95% lower 95% upper
2026-09-01 5466.0 5233.0 5105.0 5462.0 5202.0 5735.0
2026-10-01 5845.0 5596.0 5460.0 5664.0 5388.0 5955.0
2026-11-01 6033.0 5776.0 5635.0 5844.0 5540.0 6166.0
2026-12-01 7596.0 7272.0 7095.0 7543.0 7097.0 8017.0
2027-01-01 5161.0 4941.0 4821.0 4907.0 4606.0 5229.0
2027-02-01 4953.0 4742.0 4626.0 4853.0 4537.0 5190.0
2027-03-01 5445.0 5213.0 5086.0 5414.0 5041.0 5814.0
2027-04-01 5540.0 5303.0 5174.0 5406.0 5019.0 5822.0
2027-05-01 6185.0 5922.0 5777.0 5995.0 5548.0 6478.0
2027-06-01 6049.0 5791.0 5650.0 5894.0 5438.0 6390.0
2027-07-01 6319.0 6050.0 5902.0 6120.0 5630.0 6653.0
2027-08-01 5843.0 5594.0 5458.0 5829.0 5346.0 6355.0
plt.figure(figsize = (13, 5.5))
plt.plot(dates.iloc[-n_show:], y[-n_show:], color = 'black', marker = 'o', markersize = 3, label = 'Data (last four years)')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_hist]), color = 'blue', marker = 'o', markersize = 3, label = 'Method 1: historical average growth')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_recent]), color = 'green', marker = 'o', markersize = 3, label = 'Method 2: recent average growth')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_latest]), color = 'orange', marker = 'o', markersize = 3, label = 'Method 3: latest growth')
plt.plot(plot_dates, np.concatenate([[y[-1]], fcast_sarima]), color = 'red', marker = 'o', markersize = 3, label = 'SARIMA')
plt.fill_between(future_dates, lower, upper, color = 'red', alpha = 0.15, label = '95% prediction interval (SARIMA)')
plt.axvline(dates.iloc[-1], color = 'gray', linestyle = '--')
plt.ylim(4300, 9300)
plt.xlabel('Year')
plt.ylabel('Millions of dollars')
plt.title('Sales predictions for the next twelve months')
plt.legend(loc = 'upper left', ncol = 2)
plt.show()
All four predictions follow the same seasonal shape (they are all built on the same months of the previous year), and for most months the SARIMA prediction lies between Methods 1 and 2. Its implied year-over-year growth rates are mostly small and positive: the model has discounted the latest value of as partly a blip, and it also uses the smoothed seasonal pattern rather than last year’s values alone, which is why its growth rates are not the same for all twelve months. The prediction intervals are wide (roughly one month ahead and twelve months ahead); they quantify something that the simple methods cannot.
Why is the SARIMA model more sensible than the simple methods?¶
The reasons are the same as in Part One. The simple methods are special cases of the SARIMA model: Method 3 is the SARIMA model with all ARMA coefficients equal to zero, and Methods 1 and 2 correspond to particular (and arbitrary) ways of averaging past growth rates. The SARIMA model estimates how much weight to put on the recent growth rates and on past years from the data, and it quantifies the uncertainty of its predictions. In addition, the SARIMA model uses a seasonal pattern that is averaged over several years, instead of copying last year’s pattern exactly (with all its noise).
As before, we check whether this translates into better predictions by going back in time. We take every month from January 2019 onwards as a forecast origin, use only the data up to the origin to predict the next twelve months by each method (re-fitting the SARIMA model at each origin), and compute the RMSE of the prediction errors at horizons . The errors are computed on the log scale and multiplied by 100, so they are approximately percentage errors. The evaluation period includes the pandemic years, in which the growth rate changed abruptly. This takes about a minute.
H = 12
t_first = np.where(dates.dt.year >= 2019)[0][0] # position of January 2019: our first forecast origin
origins = range(t_first, n - H + 1)
methods = ['Method 1 (historical average)', 'Method 2 (recent average)', 'Method 3 (latest growth)', 'SARIMA']
errors = {m: [] for m in methods}
for t in origins:
past = ylog[:t] # log sales known at the origin (the data up to and including month t)
future = ylog[t:t+H] # log sales for the next H months, which we are trying to predict
base_log = past[-12:] # log sales in the same months of the previous year
g12_past = 100 * (past[12:] - past[:-12]) # the year-over-year growth rates known at the origin
errors[methods[0]].append(100 * (future - (base_log + np.mean(g12_past) / 100)))
errors[methods[1]].append(100 * (future - (base_log + np.mean(g12_past[-12:]) / 100)))
errors[methods[2]].append(100 * (future - (base_log + g12_past[-1] / 100)))
md = ARIMA(past, order = (p_bic, 1, q_bic), seasonal_order = (P_bic, 1, Q_bic, 12)).fit()
errors[methods[3]].append(100 * (future - md.get_forecast(H).predicted_mean))
rmse = {m: np.sqrt(np.mean(np.array(e)**2, axis = 0)) for m, e in errors.items()}
rmse_df = pd.DataFrame(rmse, index = ['h = %d' % h for h in range(1, H + 1)]).T
print("Number of forecast origins:", len(origins), "(from", dates.iloc[t_first].date(), "to", dates.iloc[n - H].date(), ")")
print("\nRMSE of the sales predictions (approximate percentage errors):")
print(rmse_df[['h = 1', 'h = 2', 'h = 3', 'h = 6', 'h = 9', 'h = 12']].round(2))Number of forecast origins: 81 (from 2019-01-01 to 2025-09-01 )
RMSE of the sales predictions (approximate percentage errors):
h = 1 h = 2 h = 3 h = 6 h = 9 h = 12
Method 1 (historical average) 6.91 6.95 7.04 7.12 7.19 7.25
Method 2 (recent average) 5.19 5.65 6.08 7.20 7.88 8.29
Method 3 (latest growth) 3.95 4.08 4.13 5.97 7.21 8.65
SARIMA 2.94 3.12 3.58 5.06 6.17 7.29
The SARIMA model has the smallest RMSE at every horizon up to nine months. One month ahead, its RMSE is about 3%, compared to about 4% for Method 3, 5% for Method 2 and 7% for Method 1; the ordering of the three simple methods at short horizons reflects how quickly they adapt to the changing growth rates of this period. As the horizon grows, the advantage of SARIMA shrinks: at twelve months ahead, SARIMA and Method 1 are about equal (7.3%), and Methods 2 and 3 are somewhat worse (the latest growth rate is a noisy guide to the growth rate a year from now). This is the same lesson as for GNP, and as for the GDP comparison in Lecture 21: the model structure (the ARMA coefficients) buys accuracy at short horizons, while long-range predictions are dominated by the assumed future growth rate, which no method can know in advance.
Summary¶
The two analyses followed the same steps.
Transform and difference the data until it fluctuates around a fixed level: logarithms and one difference for GNP (giving the quarterly growth rates), logarithms and a seasonal difference followed by a regular difference for the retail sales (giving the changes in the year-over-year growth rates). The choice of (and ) is made by looking at the data, and not by AIC/BIC.
The simplest model for the differenced series (a constant plus noise, where the constant is zero for the doubly differenced sales) corresponds to a simple and intuitive prediction rule: “future growth equals the historical average growth” for GNP, and “same month last year, grown by the latest year-over-year growth rate” for the sales.
The ARMA (or multiplicative seasonal ARMA) model refines this rule by using the structure in the differenced series, with orders chosen by AIC/BIC (preferring BIC when they disagree, as the AIC choice tends to be too large). The ARIMA function fits this model to the original series directly, undoes the differencing in its forecasts, and gives prediction intervals.
Going back in time and comparing predictions with what actually happened shows where the model helps: mainly at short horizons.