import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.tsa.ar_model import AutoRegPACF (Partial AutoCorrelation Function)¶
In Lecture 19, we looked at the following heuristic procedure for selecting the AR order (i.e., selecting for fitting the AR() model):
Here is an approach that we can use to select the order in AR().
For each , we fit an AR() model to the data. We record , the estimated coefficient of the last lag in that model, together with its approximate 95% confidence interval. We then plot these estimates and intervals against .
The idea is that if the data follow an AR() model, additional lags beyond have zero coefficients. We therefore look for a cutoff after which the estimates fluctuate near zero, with most of their confidence intervals containing zero. The location of this cutoff suggests a suitable AR order.
This is a heuristic. We examine the entire plot rather than stopping at the first interval containing zero, because later coefficients may still be substantial. Conversely, an isolated interval excluding zero at a large lag may occur simply by chance when many orders are examined. The suggested order can be assessed further by checking residuals and comparing forecasting performance.
As an illustration, let us again use the sunspots dataset.
sunspots = pd.read_csv('SN_y_tot_V2.0_17Sept2026.csv', header = None, sep = ';')
print(sunspots.head())
y = sunspots.iloc[:,1].values
n = len(y)
plt.figure(figsize = (12, 6))
plt.plot(y)
plt.show() 0 1 2 3 4
0 1700.5 8.3 -1.0 -1 1
1 1701.5 18.3 -1.0 -1 1
2 1702.5 26.7 -1.0 -1 1
3 1703.5 38.3 -1.0 -1 1
4 1704.5 60.0 -1.0 -1 1

p_max = 30 # Choose the maximum AR order (this is somewhat arbitrary; choose a large enough value to see the pattern)
p_values = range(1, p_max + 1)
phi, ci = [], []
for p in p_values:
fit = AutoReg(y, lags = p).fit()
phi.append(fit.params[-1])
ci.append(fit.conf_int()[-1])
ci = np.array(ci)
plt.figure(figsize=(10, 5))
plt.plot(p_values, phi, 'ko')
plt.vlines(p_values, ci[:, 0], ci[:, 1], color='black')
plt.axhline(0, color='red', linestyle='--')
plt.xticks(p_values)
plt.xlabel('AR order $p$')
plt.ylabel(r'$\widehat{\phi}_{p,p}$')
plt.title('Last AR coefficient with 95% intervals')
plt.show()
In the above plot, we are plotting both the fitted value for (when AR(p) is fit) as well as the corresponding 95% confidence interval. We can get a simpler version of this plot by plotting only the fitted (and omitting the confidence intervals).
p_max = 30
p_values = range(1, p_max + 1)
phi = []
for p in p_values:
fit = AutoReg(y, lags=p).fit()
phi.append(fit.params[-1])
plt.figure(figsize=(10, 5))
plt.plot(p_values, phi, 'ko')
plt.vlines(p_values, 0, phi, color='black')
plt.axhline(0, color='red', linestyle='--')
plt.xticks(p_values)
plt.xlabel('AR order $p$')
plt.ylabel(r'$\widehat{\phi}_{p,p}$')
plt.title('Last fitted AR coefficient')
plt.show()
In the literature, the above plot is referred to as the sample PACF (Partial AutoCorrelation Function) plot of the data. There is an inbuilt function in statsmodels to compute this (pacf) and to plot this (plot_pacf). Here is how these functions work.
p_max = 30
from statsmodels.tsa.stattools import pacf
pacf_vals = pacf(y, nlags=p_max, method = 'ols') #these pacf values start with the value 1 at lag 0.
from statsmodels.graphics.tsaplots import plot_pacf
plot_pacf(y, lags = p_max)
plt.title("Sample PACF of the Sunspots Data")
plt.show()
The PACF values (given by the functions pacf and plotted by plot_pacf) start with the value 1 at . In other words, the PACF value at is always 1 (regardless of the data) so we ignore this value; and pay attention only to PACF for .
Below we check if the PACF values outputted by the pacf function match exactly with our calculation of the coefficients when fitting AR().
print(np.column_stack([phi, pacf_vals[1:]])) [[ 0.81703769 0.81703769]
[-0.69541909 -0.69541909]
[-0.14446005 -0.14446005]
[ 0.0137408 0.0137408 ]
[-0.01016752 -0.01016752]
[ 0.1384172 0.1384172 ]
[ 0.2035669 0.2035669 ]
[ 0.22328627 0.22328627]
[ 0.21954062 0.21954062]
[ 0.02056707 0.02056707]
[ 0.01077726 0.01077726]
[-0.00809312 -0.00809312]
[ 0.00533023 0.00533023]
[ 0.04167164 0.04167164]
[-0.05026545 -0.05026545]
[-0.07467993 -0.07467993]
[-0.16296494 -0.16296494]
[-0.12285519 -0.12285519]
[ 0.0513226 0.0513226 ]
[-0.02407729 -0.02407729]
[ 0.09988241 0.09988241]
[ 0.01448813 0.01448813]
[-0.13093041 -0.13093041]
[-0.07242642 -0.07242642]
[ 0.00174815 0.00174815]
[-0.11308473 -0.11308473]
[ 0.05036624 0.05036624]
[ 0.071989 0.071989 ]
[-0.13397222 -0.13397222]
[-0.02359065 -0.02359065]]
Both the values coincide exactly. This is actually a general fact. The sample PACF at ‘lag’ is actually defined as the fitted estimate of when the AR() model is fit to the data.
The natural question then is the following: Why is the estimate of when AR() is fit to the data known as the partial autocorrelation at lag ? This is explained below.
Regression and Partial Correlation¶
Once again, the sample pacf at lag is defined as the estimate of when the AR() model is fit to the data. Why does this definition have the name “partial correlation”? In statistics, the partial correlation between two variables given a bunch of other variables is defined as the correlation between the residuals and . Below we calculate the partial correlation in terms of residuals, and then see how it is related to our definition of the sample pacf.
Let us first fix a value of and then compute the sample PACF at lag directly (without using inbuilt library functions).
p = 9 #fix a value of p
yreg = y[p:] #these are the response values in the autoregression
Xmat = np.ones((n-p, 1)) #this will be the design matrix (X) in the autoregression
for j in range(1, p+1):
col = y[p-j : n-j].reshape(-1, 1)
Xmat = np.column_stack([Xmat, col])
armod = sm.OLS(yreg, Xmat).fit()
print(armod.params)
pacf_lag_p = armod.params[-1]
print(pacf_lag_p)[ 1.26279267e+01 1.17023433e+00 -4.19499656e-01 -1.36597826e-01
1.03750543e-01 -6.69284094e-02 1.44401407e-03 1.57749176e-02
-4.38532862e-02 2.19540620e-01]
0.2195406201858306
Here the response variable yreg denotes . The first column of Xmat is the column of ones, the second column is , third column is and so on with the last column being .
print(np.column_stack([yreg, Xmat]))
print(y)[[ 13.3 1. 16.7 ... 26.7 18.3 8.3]
[ 5. 1. 13.3 ... 38.3 26.7 18.3]
[ 0. 1. 5. ... 60. 38.3 26.7]
...
[125.5 1. 83.2 ... 39.8 69.8 113.3]
[154.7 1. 125.5 ... 21.7 39.8 69.8]
[123.2 1. 154.7 ... 7. 21.7 39.8]]
[ 8.3 18.3 26.7 38.3 60. 96.7 48.3 33.3 16.7 13.3 5. 0.
0. 3.3 18.3 45. 78.3 105. 100. 65. 46.7 43.3 36.7 18.3
35. 66.7 130. 203.3 171.7 121.7 78.3 58.3 18.3 8.3 26.7 56.7
116.7 135. 185. 168.3 121.7 66.7 33.3 26.7 8.3 18.3 36.7 66.7
100. 134.8 139. 79.5 79.7 51.2 20.3 16. 17. 54. 79.3 90.
104.8 143.2 102. 75.2 60.7 34.8 19. 63. 116.3 176.8 168. 136.
110.8 58. 51. 11.7 33. 154.2 257.3 209.8 141.3 113.5 64.2 38.
17. 40.2 138.2 220. 218.2 196.8 149.8 111. 100. 78.2 68.3 35.5
26.7 10.7 6.8 11.3 24.2 56.7 75. 71.8 79.2 70.3 46.8 16.8
13.5 4.2 0. 2.3 8.3 20.3 23.2 59. 76.3 68.3 52.9 38.5
24.2 9.2 6.3 2.2 11.4 28.2 59.9 83. 108.5 115.2 117.4 80.8
44.3 13.4 19.5 85.8 192.7 227.3 168.7 143. 105.5 63.3 40.3 18.1
25.1 65.8 102.7 166.3 208.3 182.5 126.3 122. 102.7 74.1 39. 12.7
8.2 43.4 104.4 178.3 182.2 146.6 112.1 83.5 89.2 57.8 30.7 13.9
62.8 123.6 232. 185.3 169.2 110.1 74.5 28.3 18.9 20.7 5.7 10.
53.7 90.5 99. 106.1 105.8 86.3 42.4 21.8 11.2 10.4 11.8 59.5
121.7 142. 130. 106.6 69.4 43.8 44.4 20.2 15.7 4.6 8.5 40.8
70.1 105.5 90.1 102.8 80.9 73.2 30.9 9.5 6. 2.4 16.1 79.
95. 173.6 134.6 105.7 62.7 43.5 23.7 9.7 27.9 74. 106.5 114.7
129.7 108.2 59.4 35.1 18.6 9.2 14.6 60.2 132.8 190.6 182.6 148.
113. 79.2 50.8 27.1 16.1 55.3 154.3 214.7 193. 190.7 118.9 98.3
45. 20.1 6.6 54.2 200.7 269.3 261.7 225.1 159. 76.4 53.4 39.9
15. 22. 66.8 132.9 150. 149.4 148. 94.4 97.6 54.1 49.2 22.5
18.4 39.3 131. 220.1 218.9 198.9 162.4 91. 60.5 20.6 14.8 33.9
123. 211.1 191.8 203.3 133. 76.1 44.9 25.1 11.6 28.9 88.3 136.3
173.9 170.4 163.6 99.3 65.3 45.8 24.7 12.6 4.2 4.8 24.9 80.8
84.5 94. 113.3 69.8 39.8 21.7 7. 3.6 8.8 29.6 83.2 125.5
154.7 123.2]
Now let us calculate the same sample PACF value using partial correlation. Specifically, we will calculate the partial correlation between the variables and given all the intervening variables . For this, we first need to calculate the residual of given as well as the residual of given .
The residual of given is calculated as follows.
armod1 = sm.OLS(yreg, Xmat[:,:-1]).fit()
res_y = armod1.residThe residual of given is calculated as follows.
armod2 = sm.OLS(Xmat[:,-1], Xmat[:,:-1]).fit()
res_x = armod2.residThe sample correlation between these two residuals is the sample PACF at lag :
pcorr = np.corrcoef(res_y, res_x)[0, 1]
print(pcorr, pacf_lag_p)0.22133128716736616 0.2195406201858306
Note that this is basically the same as the Sample PACF at lag . The minor discrepancy occurs because the two residuals do not have exactly the same variance. More precisely, the regression coefficient in a multiple linear regression of on a set of covariates satisfies the following formula:
var_res_y = np.var(res_y)
var_res_x = np.var(res_x)
print(var_res_y, var_res_x)570.0746123783798 579.4120815077788
These residual variances are similar but not exactly the same. This explains why the correlation between the residuals does not exactly equal the fitted regression coefficient . But if we multiply the partial correlation by the ratio of the standard deviations, we recover the sample pacf at lag p (i.e., ) exactly.
reg_coeff = pcorr * np.sqrt(var_res_y/var_res_x)
print(reg_coeff, pacf_lag_p)0.21954062018583118 0.2195406201858306
The PACF is a standard diagnostic that is used to determine the order for a suitable AR model.
ACF (AutoCorrelation Function)¶
ACF is a standard diagnostic that is used to determine the order for a suitable MA model. Recall the definition of the MA() model. Given a positive integer , the Moving Average model with order (denoted by MA()) is defined by the equation:
where . The MA() model has unknown parameters which are estimated from observed data: .
For the MA() model, the correlation between and is given by: $$
$y_ty_{t+h}h > qqhh$ is given by
Note that is always equal to 1.
The sample ACF can be computed for any time series dataset, although it is only useful for data for which stationary models are appropriate.
If the sample ACF for a particular dataset becomes small (not exactly zero because of randomness) when exceeds a particular , then MA() is probably a good model for that dataset. This diagnostic is very commonly used when working with MA models.
It is a common diagnostic tool to look at both the ACF and PACF for a given dataset. By eyeballing them, once can find a suitable AR() or a suitable MA() model for the data. Below, we look at the ACF and PACF for the sunspots dataset.
from statsmodels.graphics.tsaplots import plot_acf
h_max = 40
fig, axes = plt.subplots(nrows = 2, ncols = 1, figsize = (12, 6))
plot_acf(y, lags = h_max, ax = axes[0])
axes[0].set_title("Sample ACF")
plot_pacf(y, lags = h_max, ax = axes[1])
axes[1].set_title("Sample PACF")
plt.tight_layout()
plt.show()
For this dataset, the ACF does not seem to have a simple structure in favor of an MA model. On the other hand, the PACF has two clear spikes at lags 1 and 2 suggesting AR(2). One can also go for the AR(9) model to take into account the spikes at lags 7, 8, 9. Below we fit both these models and obtain predictions.
armd_2 = AutoReg(y, lags = 2).fit()
armd_9 = AutoReg(y, lags = 9).fit()
k = 200
fcast_9 = armd_9.get_prediction(start = n, end = n+k-1)
fcast_mean_9 = fcast_9.predicted_mean
fcast_2 = armd_2.get_prediction(start = n, end = n+k-1)
fcast_mean_2 = fcast_2.predicted_mean
yhat_9 = np.concatenate([y, fcast_mean_9])
yhat_2 = np.concatenate([y, fcast_mean_2])
plt.figure(figsize=(12, 6))
time_all = np.arange(1, n + k + 1)
plt.plot(time_all, yhat_9, color='C0')
plt.plot(range(1, n + 1), y, label='Original Data', color='C1')
plt.plot(range(n + 1, n + k + 1), fcast_mean_9, label='Forecasts (AR-9)', color='blue')
plt.plot(range(n + 1, n + k + 1), fcast_mean_2, label='Forecasts (AR-2)', color='green')
plt.axvline(x=n, color='black', linestyle='--', label='Forecast Start')
plt.xlabel('Time')
plt.ylabel('Data')
plt.title('Time Series + AR(p) Forecasts')
plt.legend()
plt.show()
Visually the AR(9) predictions appear better at least for the initial few predictions.
AutoReg vs ARIMA¶
There are two inbuilt functions in statsmodels for fitting AR models: (a) AutoReg (which we used previously), and (b) ARIMA (which can be used more generally for all ARIMA models). We compare and contrast these two ways below. We use the GNP dataset (from FRED).
gnp = pd.read_csv("GNP_05Nov2026.csv")
#this is quarterly data
print(gnp.head())
y = gnp['GNP'].to_numpy()
plt.plot(y, color = 'black')
plt.xlabel('Time (in quarters)')
plt.ylabel('GNP in Billions of Dollars')
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

Instead of the raw GNP, we work with their logarithms as usual.
ylog = np.log(y)
plt.plot(ylog, color = 'black')
plt.title('Log of GNP over time')
plt.xlabel('Time (in quarters)')
plt.ylabel('Log of GNP')
plt.show()
We fit AR models to differences of the logs (after multiplying by 100). The data now becomes percent change in GNP.
ylogdiff = 100 * np.diff(ylog)
plt.plot(ylogdiff, color = 'black')
plt.title('Percent change in GNP over time')
plt.xlabel('Time (in quarters)')
plt.ylabel('Percent change in GNP')
plt.show()
Let us now fit the AR(1) model to this dataset. Let us first fit it using AutoReg.
md_autoreg = AutoReg(ylogdiff, lags = 1).fit()
print(md_autoreg.summary()) AutoReg Model Results
==============================================================================
Dep. Variable: y No. Observations: 317
Model: AutoReg(1) Log Likelihood -516.768
Method: Conditional MLE S.D. of innovations 1.242
Date: Sun, 08 Nov 2026 AIC 1039.536
Time: 14:06:18 BIC 1050.803
Sample: 1 HQIC 1044.037
317
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
const 1.1627 0.109 10.640 0.000 0.949 1.377
y.L1 0.2477 0.055 4.544 0.000 0.141 0.355
Roots
=============================================================================
Real Imaginary Modulus Frequency
-----------------------------------------------------------------------------
AR.1 4.0369 +0.0000j 4.0369 0.0000
-----------------------------------------------------------------------------
AutoReg uses the method of conditional MLE, which maximizes the conditional likelihood of given . This conditional likelihood is given by:
#the estimates of $\phi_0$ and $\phi_1$ are given by:
print(md_autoreg.params)
#if you want the estimate of sigma^2, do the following:
print(md_autoreg.sigma2)[1.16274269 0.24771615]
1.5415767673398826
Next we use the ARIMA function to fit AR(1). ARIMA models have a triplet of indices . stands for the AR order, stands for the amount of differencing, and stands for the MA order. To fit AR(1) through the ARIMA function, we need to use , and .
from statsmodels.tsa.arima.model import ARIMA
md_arima = ARIMA(ylogdiff, order = (1,0,0)).fit()
print(md_arima.summary()) SARIMAX Results
==============================================================================
Dep. Variable: y No. Observations: 317
Model: ARIMA(1, 0, 0) Log Likelihood -517.973
Date: Sun, 08 Nov 2026 AIC 1041.945
Time: 14:07:18 BIC 1053.222
Sample: 0 HQIC 1046.450
- 317
Covariance Type: opg
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
const 1.5437 0.112 13.783 0.000 1.324 1.763
ar.L1 0.2470 0.020 12.587 0.000 0.209 0.285
sigma2 1.5371 0.040 38.100 0.000 1.458 1.616
===================================================================================
Ljung-Box (L1) (Q): 0.82 Jarque-Bera (JB): 6927.23
Prob(Q): 0.36 Prob(JB): 0.00
Heteroskedasticity (H): 1.64 Skew: -0.06
Prob(H) (two-sided): 0.01 Kurtosis: 25.90
===================================================================================
Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).
ARIMA parametrizes the AR(1) model differently from AutoReg. It writes the AR(1) model as:
In other words, there is no parameter. It is replaced by . This means that or . So to compare the parameter estimates given by AutoReg and ARIMA, we need to convert the estimates from AutoReg to .
pars_autoreg = [md_autoreg.params[0]/(1 - md_autoreg.params[1]), md_autoreg.params[1], md_autoreg.sigma2]
pars_arima = md_arima.params
print(np.column_stack([pars_autoreg, pars_arima]))[[1.54561697 1.54372907]
[0.24771615 0.24699388]
[1.54157677 1.53707575]]
The parameter estimates are similar but not exactly the same. This is because ARIMA is using a different method of parameter estimation compared to AutoReg. ARIMA works with the full likelihood of (not the conditional likelihood of given ). We saw in lecture 17 that the full likelihood for AR(1) is given by:
Instead of parametrizing using and , an alternative parametrization is via and . With this the likelihood becomes:
The following function computes the log-likelihood given values of the parameters.
def loglik_ar1(dt, pars):
n = len(dt)
mu = pars[0]
phi1 = pars[1]
sigma2 = pars[2]
sigma = np.sqrt(sigma2)
# First term: density of y1 under stationary AR(1)
ll_start = 0.5 * np.log(1 - phi1**2) - 0.5*np.log(2*np.pi) - np.log(sigma) \
- (1 - phi1**2) * (dt[0] - mu)**2 / (2*sigma2)
# Second term: density of y2,...,yn
residuals = (dt[1:] - mu) - phi1*(dt[:-1] - mu)
ssr = np.sum(residuals**2)
ll_rest = -(n-1)*0.5*np.log(2*np.pi) - (n-1)*np.log(sigma) - ssr/(2*sigma2)
return ll_start + ll_restWe can attempt to maximize this full log-likelihood using an inbuilt optimization function, starting with the parameter estimates given by AutoReg. The code for doing this is given below. This gives almost the same results as the parameter estimates given by ARIMA.
from scipy.optimize import minimize
def neg_loglik_ar1(pars, dt):
return -loglik_ar1(dt, pars)
init_pars = pars_autoreg
bounds = [(-np.inf, np.inf), (-0.99, 0.99), (1e-6, np.inf)] #note that the bound on phi1 ensures stationarity
res = minimize(neg_loglik_ar1, init_pars, args=(ylogdiff,), bounds=bounds)
print("MLE estimates from custom optimization:")
print(np.column_stack([pars_autoreg, pars_arima, res.x]))
print(loglik_ar1(ylogdiff, pars_autoreg), loglik_ar1(ylogdiff, pars_arima), loglik_ar1(ylogdiff, res.x))
#check that pars_arima and res.x are very close to each other (and they give the same log-likelihood)MLE estimates from custom optimization:
[[1.54561697 1.54372907 1.54375572]
[0.24771615 0.24699388 0.24699483]
[1.54157677 1.53707575 1.53708839]]
-517.9735374533072 -517.9725743205034 -517.9725742723975
Another difference between AutoReg and ARIMA is that ARIMA, by default, only searches for parameters in the stable region but AutoReg does not place any such restrictions. Stable region corresponds to the values of the parameters for which the roots of the polynomial are strictly larger than 1 in modulus. Another name for the stable region is ‘causal-stationary’ region (or simply ‘stationary’ region). For AR(1), the stable region corresponds to (because the AR(1) polynomial is whose root is . So root having modulus strictly larger than 1 is equivalent to ).
To illustrate this difference between AutoReg and ARIMA, let us fit the AR(1) model to the original data (without any differencing and logging). Then the AutoReg will give an estimate of that is strictly larger than 1. But ARIMA will still give an estimate from the stable region (strictly smaller than 1 in absolute value).
#Below we fit these models to the original data without any differencing or logging.
md_autoreg_y = AutoReg(y, lags = 1).fit()
print(md_autoreg_y.params[1])
#AutoReg's estimate of phi1 is slightly more than 1
md_arima_y = ARIMA(y, order = (1, 0, 0)).fit()
print(md_arima_y.params[1])
#ARIMA's estimate is less than 1 (even though quite close to 1)
#Also ARIMA gives an error/warning that initial parameters that is is using are out of the stationary region.
1.0121954720762598
0.9999195196243736
/Users/aditya/mambaforge/envs/stat153fall2026/lib/python3.14/site-packages/statsmodels/tsa/statespace/sarimax.py:966: UserWarning: Non-stationary starting autoregressive parameters found. Using zeros as starting parameters.
warn('Non-stationary starting autoregressive parameters'
If we want the ARIMA function to not focus only on the stable region, then we have to explicitly use the clause ‘enforce_stationarity = False’.
md_arima_y_nostable = ARIMA(y, order = (1, 0, 0), enforce_stationarity = False).fit()
print(md_arima_y_nostable.params[1])1.012079994049166
Let us now get back to fitting models for the logarithms for . Instead of applying the ARIMA function to ylogdiff, we can apply it directly to ylog. In this case, we have to choose (as opposed to ).
md_ylog = ARIMA(ylog*100, order = (1, 1, 0)).fit() #note that now d = 1
print(md_ylog.summary()) SARIMAX Results
==============================================================================
Dep. Variable: y No. Observations: 318
Model: ARIMA(1, 1, 0) Log Likelihood -566.939
Date: Sun, 08 Nov 2026 AIC 1137.877
Time: 14:37:05 BIC 1145.395
Sample: 0 HQIC 1140.880
- 318
Covariance Type: opg
==============================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------
ar.L1 0.6924 0.030 23.317 0.000 0.634 0.751
sigma2 2.0896 0.076 27.320 0.000 1.940 2.239
===================================================================================
Ljung-Box (L1) (Q): 62.72 Jarque-Bera (JB): 22699.21
Prob(Q): 0.00 Prob(JB): 0.00
Heteroskedasticity (H): 2.01 Skew: 2.66
Prob(H) (two-sided): 0.00 Kurtosis: 44.11
===================================================================================
Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).
The difference now is that the parameter is no longer present. In other words, the model that is fit here is:
Whenever the differencing order is 1 or more, ARIMA does not use the intercept parameter. This makes a noticeable difference in predictions however.
k = 100
n = len(ylog)
tme = range(1, n+1)
tme_future = range(n+1, n+k+1)
fcast = md_ylog.get_prediction(start = n, end = n+k-1)
fcast_mean = fcast.predicted_mean #this gives the point predictions
plt.plot(tme, ylog*100, label = 'Data')
plt.plot(tme_future, fcast_mean, label = 'Forecast (ARIMA on ylog with d = 1)', color = 'green')
plt.axvline(x=n, color='gray', linestyle='--')
plt.legend()
plt.show()
On the other hand, if we use the model on ylogdiff, then the predictions for ylog are computed in the following way. We basically obtain predictions for the differenced series, and then use the predictions for to get predictions for . This is done by taking telescoping sums of , and then adding .
n = len(y)
k = 100
fcast_diff_1 = md_arima.get_prediction(start = n-1, end = n+k-2).predicted_mean #these are the forecasts for the differenced data
last_observed_ylog = 100*ylog[-1]
fcast_1 = np.zeros(k)
fcast_1[0] = last_observed_ylog + fcast_diff_1[0]
for i in range(1, k):
fcast_1[i] = fcast_1[i-1] + fcast_diff_1[i]plt.plot(tme, ylog*100, label = 'Data')
plt.plot(tme_future, fcast_mean, label = 'Forecast (ARIMA on ylog with d = 1)', color = 'green')
plt.plot(tme_future, fcast_1, label = 'Forecast (ARIMA on ylogdiff with d = 0)', color = 'red')
plt.axvline(x=n, color='gray', linestyle='--')
plt.legend()
plt.show()
So here the presence of the intercept is leading to more intuitive predictions.
Another dataset from FRED¶
Here is a FRED dataset on total construction spending in the United States (https://
ttlcons = pd.read_csv('TTLCONS_05Nov2026.csv')
print(ttlcons.head())
y = ttlcons['TTLCONS'].to_numpy()
print(len(y))
plt.plot(y)
plt.title('Total Construction Spending')
plt.xlabel('Time (months)')
plt.show() observation_date TTLCONS
0 1993-01-01 458080
1 1993-02-01 462967
2 1993-03-01 458399
3 1993-04-01 469425
4 1993-05-01 468998
405

As usual, we fit models to logarithms of the data.
ylog = np.log(y)
plt.plot(ylog, color = 'black')
plt.title('Log of Total Construction Spending')
plt.xlabel('Time (months)')
plt.show() 
In order to obtain candidate models, let us first difference the data, and then look at acf and pacf.
ylogdiff = 100 * np.diff(ylog)
plt.plot(ylogdiff, color = 'black')
plt.title('Percent change in Total Construction Spending')
plt.xlabel('Time (months)')
plt.show()
Here is how to compute the ACF and PACF.
h_max = 50
fig, axes = plt.subplots(nrows = 2, ncols = 1, figsize = (12, 6))
plot_acf(ylogdiff, lags = h_max, ax = axes[0])
axes[0].set_title("Sample ACF")
plot_pacf(ylogdiff, lags = h_max, ax = axes[1])
axes[1].set_title("Sample PACF")
plt.tight_layout()
plt.show()
These plots suggest:
AR(3) for the differenced log data (to account for the three spikes in PACF)
MA(6) for the differenced log data (to account for the six spikes in ACF)
ARIMA(3, 1, 0) for the log data (this is technically the same as Model 1 but the ARIMA function does not include intercepts while fitting this model so it can lead to different predictions)
ARIMA(0, 1, 6) for the log data
We can also take another difference of the data, and then look at acf and pacf.
ylogdiff2 = np.diff(np.diff(ylog))
plt.plot(ylogdiff2)
plt.title("Double Differenced Data")
plt.show()
h_max = 50
fig, axes = plt.subplots(nrows = 2, ncols = 1)
plot_acf(ylogdiff2, lags = h_max, ax = axes[0])
axes[0].set_title("Sample ACF")
plot_pacf(ylogdiff2, lags = h_max, ax = axes[1])
axes[1].set_title("Sample PACF")
plt.tight_layout()
plt.show()
The ACF plot above (which has a single spike) suggests the ARIMA(0, 1, 2) model for ylog.
Here is how to calculate the predictions for each of the five models.
k = 100
n = len(ylog)
tme = range(1, n+1)
tme_future = range(n+1, n+k+1)First is Model One: AR(3) for the differenced log data.
#Model One: AR(3) for the differenced log data
md1 = ARIMA(ylogdiff, order = (3, 0, 0)).fit()
fcast_diff_1 = (md1.get_prediction(start = n-1, end = n+k-2).predicted_mean)/100 #these are the forecasts for the differenced data
last_observed_ylog = ylog[-1]
fcast_1 = np.zeros(k)
fcast_1[0] = last_observed_ylog + fcast_diff_1[0]
for i in range(1, k):
fcast_1[i] = fcast_1[i-1] + fcast_diff_1[i]plt.plot(tme, ylog, label = 'Data')
plt.plot(tme_future, fcast_1, label = 'Model One', color = 'red')
plt.axvline(x=n, color='gray', linestyle='--')
plt.legend()
plt.show()
Next is Model Two: MA(6) on differenced log data.
#Model Two: MA(6) for the differenced log data
md2 = ARIMA(ylogdiff, order = (0, 0, 6)).fit()
fcast_diff_2 = (md2.get_prediction(start = n-1, end = n+k-2).predicted_mean)/100 #these are the forecasts for the differenced data
last_observed_ylog = ylog[-1]
fcast_2 = np.zeros(k)
fcast_2[0] = last_observed_ylog + fcast_diff_2[0]
for i in range(1, k):
fcast_2[i] = fcast_2[i-1] + fcast_diff_2[i]plt.plot(tme, ylog, label = 'Data')
plt.plot(tme_future, fcast_1, label = 'Model One', color = 'red')
plt.plot(tme_future, fcast_2, label = 'Model Two', color = 'green')
plt.axvline(x=n, color='gray', linestyle='--')
plt.legend()
plt.show()
So Model One and Model Two lead to basically the same predictions.
Next is Model Three which ARIMA(3, 1, 0).
#Model Three: ARIMA(3, 1, 0) for the log data
md3 = ARIMA(ylog, order = (3, 1, 0)).fit()
fcast_3 = md3.get_prediction(start = n, end = n+k-1).predicted_mean/Users/aditya/mambaforge/envs/stat153fall2026/lib/python3.14/site-packages/statsmodels/base/model.py:607: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
warnings.warn("Maximum Likelihood optimization failed to "
plt.plot(tme, ylog, label = 'Data')
plt.plot(tme_future, fcast_1, label = 'Model One', color = 'red')
plt.plot(tme_future, fcast_2, label = 'Model Two', color = 'green')
plt.plot(tme_future, fcast_3, label = 'Model Three', color = 'black')
plt.axvline(x=n, color='gray', linestyle='--')
plt.legend()
plt.show()
The prediction is flat because of the lack of the intercept term in ARIMA(3, 1, 0).
#Model Four: ARIMA(0, 1, 6) for the log data
md4 = ARIMA(ylog, order = (0, 1, 6)).fit()
fcast_4 = md4.get_prediction(start = n, end = n+k-1).predicted_meanplt.plot(tme, ylog, label = 'Data')
plt.plot(tme_future, fcast_1, label = 'Model One', color = 'red')
plt.plot(tme_future, fcast_2, label = 'Model Two', color = 'green')
plt.plot(tme_future, fcast_3, label = 'Model Three', color = 'black')
plt.plot(tme_future, fcast_4, label = 'Model Four', color = 'orange')
plt.axvline(x=n, color='gray', linestyle='--')
plt.legend()
plt.show()
The forecasts for models 3 and 4 are largely similar.
Finally below are the predictions for model 5.
#Model Five: ARIMA(0, 2, 1) for the log data
md5 = ARIMA(ylog, order = (0, 2, 1)).fit()
fcast_5 = md5.get_prediction(start = n, end = n+k-1).predicted_meanplt.plot(tme, ylog, label = 'Data')
plt.plot(tme_future, fcast_1, label = 'Model One', color = 'red')
plt.plot(tme_future, fcast_2, label = 'Model Two', color = 'green')
plt.plot(tme_future, fcast_3, label = 'Model Three', color = 'black')
plt.plot(tme_future, fcast_4, label = 'Model Four', color = 'orange')
plt.plot(tme_future, fcast_5, label = 'Model Five', color = 'darkgreen')
plt.axvline(x=n, color='gray', linestyle='--')
plt.legend()
plt.show()
Let us try to manually fit the AR(1) model to the double differenced data (so the model will involve an intercept), and then manually convert the predictions on the double differenced data to predictions on the original data.
md6 = ARIMA(ylogdiff2, order = (0, 0, 1)).fit()
fcast_diff_6 = md6.get_prediction(start = n-2, end = n+k-3).predicted_mean
tmp1 = ylog[-1] - ylog[-2]
fcast_d1 = np.zeros(k)
fcast_d1[0] = tmp1 + fcast_diff_6[0]
for i in range(1, k):
fcast_d1[i] = fcast_d1[i-1] + fcast_diff_6[i]tmp2 = ylog[-1]
fcast_6 = np.zeros(k)
fcast_6[0] = tmp2 + fcast_d1[0]
for i in range(1, k):
fcast_6[i] = fcast_6[i-1] + fcast_d1[i]plt.plot(tme, ylog, label = 'Data')
plt.plot(tme_future, fcast_1, label = 'Model One', color = 'red')
plt.plot(tme_future, fcast_2, label = 'Model Two', color = 'green')
plt.plot(tme_future, fcast_3, label = 'Model Three', color = 'black')
plt.plot(tme_future, fcast_4, label = 'Model Four', color = 'orange')
plt.plot(tme_future, fcast_5, label = 'Model Five', color = 'darkgreen')
plt.plot(tme_future, fcast_6, label = 'Model Six', color = 'darkblue')
plt.axvline(x=n, color='gray', linestyle='--')
plt.legend()
plt.show()
All these models give quite different predictions. Which prediction do you like?