Skip to content
ImagineWorld

ARIMA Models

node_idnode-book_building-statistical-models-in-python_chapter-11-arima-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleARIMA Models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we will discuss univariate time series models. These are models that only consider a single variable and create forecasts based only on the previous samples in the time series. We will start by looking at models for stationary time series data and then progress to models for non-stationary time series data. We will also discuss how to identify appropriate models based on the characteristics of time series. This will provide a powerful set of models for forecasting time series.

In this chapter, we’re going to cover the following main topics:

  • Models for stationary time series
  • Models for non-stationary time series
  • More on model evaluation

In this chapter, we use two additional Python libraries for time series analysis: sktime and pmdarima. Please install the following versions of these libraries to run the provided code. Instructions for installing libraries can be found in Chapter 1, Sampling and Generalization.

  • sktime==0.15.0
  • pmdarima==2.02

More information about sktime can be found at this link: https://www.sktime.org/en/stable/get_started.html

More information about pmdarima can be found at this link: http://alkaline-ml.com/pmdarima/

In this section, we will discuss Autoregressive (AR), Moving Average (MA), and Autoregressive Moving Average (ARMA) models that are useful for stationary data. These models are useful when modeling patterns and variance around process means that output over time. When we have data that does not exhibit autocorrelation, we can use statistical and machine learning models that do not make assumptions about time, such as Logistic Regression or Naïve Bayes, so long as the data supports such use cases.

In Chapter 10, Introduction to Time Series we considered how the Partial Auto-Correlation Function (PACF) correlates one data point to another lag, controlling for those lags between. We also discussed how inspection of the PACF plot is a frequently used method for assessing the ordering of an autoregressive model. Thereto, the autoregressive model is one that considers specific points in the past to be directly correlated to the value of a given point at lag zero. Suppose we have a process with random, normally distributed white noise,, where. If – using real constants of where – we can formulate the process in the following way:

Letting represent the overall process sample mean (in our examples, we will consider zero-mean processes), we can consider this to be an autoregressive process of order p, or AR(p) [1]. We can define the autocorrelation for the AR(p) model as follows:

There is also this example:

In the preceding example, where is the lag k autocorrelation. is both the slope and autocorrelation for an AR(1) process.

AR(p) model structure and components

To prevent confusion, note that with the equation y t − μ − ϕ 1(y t−1 − μ) − ϕ 2(y t−2 − μ) − … − ϕ p(y p − μ) = ϵ t we are attempting to build a mathematical model that represents the process such that if perfectly modeled, all that remains is the random, normally distributed white noise,. This effectively means the model leaves zero residual error (in other words, a perfect fit). Each term – where k is a lag in time – represents the value at that point in time and each corresponding value of is the coefficient value required for the such that when taken in combination with all other values of y, the model statistically approximates zero error.

The backshift operator notation, or simply operator notation, is a simplified, shorthand method of formulating models. It is called “backshift” because it shifts time back one lag from t to t-1. The purpose is to avoid the necessitation of writing the subscript following every φ coefficient and instead writing while including only once, which is handy when writing AR(p) models with high orders of p. In the following equation, the zero-mean form of an AR(1) follows the following structure:

The equation reduces to the following example:

In backshift operator notation, we can say this:

Note on in an AR(1)

It’s worth noting at this point that an AR(1) process is stationary if. That is, when the absolute value of the lag-one autocorrelation is < 1, the AR(1) process is stationary. When, an ARIMA model may still be useful, but when, the process is considered to be explosive and should not be modeled. This is because a value means the root is outside of, and not bounded by, the unit circle. A value of is on the unit circle but can be differenced to remove the unit root. The root for the case of an AR(1) can be calculated as A set of data producing cannot be filtered in a way that puts its root outside the unit circle.

When all roots of an AR(p) are outside the unit circle, the given realization (one time series sampled from a stochastic process) will converge to the mean, have constant variance, and be independent of time. This is an ideal scenario for time series data.

Let’s walk through an example of an AR(1) process with and therefore a stationary root. Assume we have identified the following first-order autoregressive process:

This is converted to operator notation:

When looking for roots, we can use the following notation:

This gives us a root of z:

Therefore, since the root is greater than 1 and thus outside the unit circle, the AR(1) representation of the process is stationary. In Python, we can build this process using the upcoming code. First, we build the AR(1) parameters, which we want to have a 0.5. Because we substitute 0.5 into the model, we insert 0.5 and not -0.5 for arparams. Also, note based on that 0.5 is the lag-1 autocorrelation. The process we build will have an arbitrary sample size of nsample=200. We build the component of using the np.r_[1, - arparams] step:

from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
import matplotlib.pyplot as plt
import statsmodels.api as sm
import numpy as np
arparams = np.array([0.5])
ar = np.r_[1, -arparams]
ar_process = sm.tsa.ArmaProcess(ar)
y = ar_process.generate_sample(nsample=200)

Now that we have the code to create the AR(1) we looked at the equation for, let’s see the roots and compare it to our manually calculated z:

ar_process.arroots

array([2.])

We can see the Python output, 2. is the same as the calculation we performed. We know that since the absolute value of the root is greater than 1, the AR(1) process is stationary, but let’s confirm with Python:

ar_process.isstationary

True

We can observe by looking at the PACF that this is an autoregressive of order. We can also observe by looking at the ACF that the value of is approximately 0.5. For an autoregressive model, the PACF is used to identify the number of significant lags to include as the order of the AR, and the ACF is used to determine the values of the coefficients,, included in that order. It is simple to observe the values for an AR(1) using the ACF, but less obvious when p > 1 since ACF does not control for individual lags when compared to the most recent point (lag zero) as the PACF does. Let’s generate the plots with Python:

fig, ax = plt.subplots(1,3, figsize=(20,5))
ax[0].set_title('Realization')
ax[0].plot(y)
plot_acf(y, alpha=0.05, lags=50, ax=ax[1])
ax[1].set_title('ACF')
plot_pacf(y, alpha=0.05, lags=50, ax=ax[2])
ax[2].set_title('PACF')

Figure 11.1 – The AR(1) process

Common for AR(1) processes, we see in Figure 11*.1* a single significant partial autocorrelation in the PACF plot, excluding lag zero. Note there is some significance as we near lag 45, but because of the insignificance between lag 1 and those points, including those lags and constructing something such as an AR(50) would result in extreme overfitting; the coefficients from lag 2 through roughly lag 45 would fall between roughly 0 and. As referenced in Chapter 4, Parametric Tests, the correlation between about and is generally considered a weak correlation.

Let’s look at the following stationary AR(2) process:

Converted to backshift operator notation, we have the following:

We also have this:

Since we’re focusing on Python in this book, we won’t walk through the steps, but it may be useful to know second-order polynomials – such as AR(2) – follow the quadratic equation, ( for our process). Therefore, we can use the quadratic formula:

This is what we’ll use to find the roots. In Python, we can find the roots of this model using the following:

arparams = np.array([-0.8, -0.48])
ar = np.r_[1, -arparams]
ar_process = sm.tsa.ArmaProcess(ar)
print('AR(2) Roots: ', ar_process.arroots)
print('AR(2) Stationarity: ', ar_process.isstationary)

Here we can see the unit roots identified using the statmodels ArmaProcess function:

AR(2) Roots: [- 0.83333333-1.1785113j -0.83333333+1.1785113j]

AR(2) Stationarity: ``True

We can observe the roots are in complex conjugate form. When a process has roots in complex conjugate form, it is expected the autocorrelations will exhibit an oscillatory pattern, which we can see in the ACF plot in Figure 11*.2*. We can also observe the two significant lags in the PACF, which support the case of order p=2:

Figure 11.2 – AR(2) with complex conjugate roots

To mathematically test that complex conjugate roots are stationary (outside the unit circle), we take the magnitude of the vector of each root’s real and imaginary parts and check if it is greater than 1. The magnitude for complex conjugate roots, z, following form is the following equation:

The magnitude of our roots is this:

Since 1.4433 > 1, we know our AR(2) model is stationary.

Identifying order p for AR models using the PACF

When identifying a lag order p for an autoregressive process, AR(p), based on the PACF plot, we take the maximum lag where significant partial autocorrelation exists as the order for p. In observing Figure 11*.3*, because the PACF dampens after lag 4 and through about lag 30, we will cut off order consideration after lag 4 because using more lags (consider them as features for a time series model) will likely result in overfitting. The order selected using PACF is based on the last significant lag before the partial autocorrelations dampen. While lags 2 and 3 seem to be small and may not be significant, lag 4 is. Therefore, we may get the best model using an AR of order 4. Typically, we test our assumptions using errors with information criteria, such as AIC or BIC.

Figure 11.3 – AR(p) order identification

Let us walk through an end-to-end example of AR(p) modeling in Python. First, we need to generate a dataset produced by an AR(4) process. We will use this data as the process we will attempt to model:

arparams = np.array([1.59, -0.544, -0.511, 0.222])
ar = np.r_[1, -arparams]
ar_process = sm.tsa.ArmaProcess(ar)
y = ar_process.generate_sample(nsample=200)

For the following steps, let us assume data y is the output of a machine about which we know nothing.

We first visualize the original data and its ACF and PACF plots using the code we provided earlier in the chapter:

Figure 11.4 – Step 1 in model development: visual inspection

We can see based on the PACF plot we have what appears to be an AR(2), but possibly an AR(4). After lag 4, the partial autocorrelations lose statistical significance at the 5% level of significance. We can see, however, when considering the statistical significance of lag 4 in the PACF, however slight, lag 4 in the ACF is significant. While the value at lag 4 is not the value of the coefficient, its significance is useful in helping determine order p. Nonetheless, an AR(4) may overfit and fail to generalize as well as an AR(2). Next, we will use Aikake Information Criterion (AIC) and Bayesian Information Criterion (BIC) to help make our determination.

Based on the constant mean and the fact we do not have an exponentially dampening (which would also need to be significant) ACF, there does not appear to be a trend.

Since we are uncertain based on the visual inspection of the order we should use for the AR(p) model, we will use AIC and BIC to help our decision. The AIC and BIC process will fit models using order zero up to the max_ar value provided in the upcoming code. The models will fit the entire dataset. The order with the lowest error is generally the best. Their error calculations are as follows:

This is where k is the number of lags – up to the maximum order tested – for the data, is the maximum likelihood estimate, and n is the sample size (or length of the dataset being tested). For both tests, the lower error is better.

We will import arma_order_select_ic from Statsmodels and test it using up to a maximum of 4 lags based on our observation in the PACF plot in Figure 11*.4*. As noted, based on our visual inspection, we do not appear to have a trend. However, we can verify this statistically with an OLS-based unit root test called the Dickey-Fuller test. The null hypothesis of the Dickey-Fuller test is that a unit root (and therefore, trend) is present at some point in the maximum number of lags tested (maxlag). The alternative hypothesis is that there is no unit root (no trend) in the data. For reference, the alternative hypothesis states that the data is an order zero - I(0) - integrated process while the null hypothesis states that the data is an order one - I(1) - integrated process. If the absolute value of the test statistic is greater than the critical value or the p-value is significant, we can conclude there is no trend present (no unit root).

The Dickey-Fuller test considers each data point out to the number of lags included in the regression test. We will need to analyze the ACF plot for this; because we want to consider as far out as a trend could be possible, we must choose the longest lag that has significance. The idea is that if we have a strong trend in our data, such as growth, for the most part, each sequential value will lead to another increasing subsequent value for as long as the trend exists. In our case, the maximum significant lag in the ACF plot is approximately 25. The Dickey-Fuller test has relatively low statistical power (prone to Type II error or failing to reject the null when the null should be rejected) so a high order of lags is not concerning so long as it is practical; the risk is failing to include enough lags.

Dickey-Fuller unit roots

The Dickey-Fuller tests only if there is a trend unit root, but not if there is a seasonal unit root. We discuss the difference between trend and seasonal unit roots in the ARIMA section of this chapter.

In the upcoming code block, we add maxlag=25 for our 25 lags from the ACF plot in Figure 11*.4*. We will also include regression='c', which adds a constant (or intercept) into the OLS it performs; we will not need to manually add the constant in that case:

from statsmodels.tsa.stattools import adfuller
dicky_fuller = adfuller(y, maxlag=25, regression='c')
print('Dickey-Fuller p-value: ', dicky_fuller[1])
print('Dickey-Fuller test statistic: ', dicky_fuller[0])
print('Dickey-Fuller critical value: ', dicky_fuller[4].get('5%'))

We can see based on the Dickey-Fuller test that we should reject the null hypothesis and conclude the process is order-zero integrated and therefore does not have trend:

Dickey-Fuller p-value: ``1.6668842047161513e-06

Dickey-Fuller test statistic: - 5.545206445371327

Dickey-Fuller critical value: - 2.8765564361715534

We can therefore insert into our arma_order_select_ic function that trend='n' (otherwise, we may want to difference the data, which we will show in the ARIMA section of the chapter):

from statsmodels.tsa.stattools import arma_order_select_ic
model_ar = arma_order_select_ic(y=y, max_ar=4, max_ma=0,
ic=['aic','bic'], trend='n')
print('AIC Order Selection: ', model_ar.aic_min_order)
print('AIC Error: ', round(model_ar.aic.min()[0], 3))
print('BIC Order Selection: ', model_ar.bic_min_order)
print('BIC Error: ', round(model_ar.bic.min()[0], 3))

Here we can see the AR and MA orders identified to produce a fit with the lowest overall error according to our AIC and BIC tests:

AIC Order Selection: (``4, 0)

AIC Error: ``586.341

BIC Order Selection: (``2, 0)

BIC Error: ``597.642

We can see AIC selected an AR(4) and BIC selected an AR(2). It is preferable that both tests select the same term orders. However, as we noted already, the AR(2) may be less likely to overfit. Since the best order isn’t completely clear, we will proceed to test both models (using AR(2) and AR(4)) by comparing their errors and log-likelihood estimates.

In this step, we can add our arguments to the statsmodels’ ARIMA function and fit it to the data with our prescribed AR(4). To be clear, an AR(4) is the same as an ARIMA(4,0,0). We want to include enforce_stationarity=True to ensure our model will produce useful results. If not, we will receive a warning and need to address the issue by either differencing, using a different model – such as SARIMA, changing our sampling method, changing our time binning (from days to weeks, for example), or abandoning time series modeling for the data altogether:

from statsmodels.tsa.arima.model import ARIMA
ar_aic = ARIMA(y, order=(4,0,0),
enforce_stationarity=True).fit()
print(ar_aic.summary())

In our model output, we can see the SARIMAX Results title and Model: ARIMA(4,0,0). This can be disregarded. A SARIMAX with no seasonal component and no exogenous variables (in our case) is simply an ARIMA. Further, an ARIMA of order (4,0,0) is an AR(4):

Figure 11.5 – AR(4) model results

The AR(4) process we modeled (the simulated process we built prior to step 1 is

and the AR(4) model we produced using the data from the input process is the following:

In backshift operator notation, we have the following equation:

Notably, the term for lag 4 is not significant and the confidence interval contains 0. Therefore, including this term is a known risk for overfitting and something worth weighing if considering alternative models. It would be prudent to compare an AR(2) and even an AR(3) to our AR(4) based on AIC and BIC and choose a different model if the results are much improved, but we will skip this process for the sake of time.

Regarding the model summary metrics, we discussed the Ljung-Box test in the last chapter so will not cover the details here, but the high p-value (Prob(Q)) for that test indicates there is not correlated error at lag 1. Typically, if there is serial correlation in the residuals of a model fit, the residuals will have lag 1 autocorrelation. The Jarque-Bera test assumes the errors are normally distributed under the null hypothesis and not normally distributed under the alternative hypothesis. The high p-value (Prob(JB)) for that test suggests the error is normally distributed. The test for heteroskedasticity tests the null that the residuals are constant (homoscedastic) with the alternative hypothesis being that they are non-constant, which is an issue for a time series regression fit. Here, our Heteroskedasticity p-value (Prob(H)) is high so we can assume our model’s residuals have constant variance. A skew score between [-0.5, 0.5] is considered not skewed, whereas between [-1, -0.5] or [0.5, 1] is moderately skewed and > ±2 is high. A perfect score for kurtosis is 3. Kurtosis > ±7 is high. Because our skew is 0.04 and our kurtosis score is 2.58, we can assume our residuals are normally distributed.

Another method for validating a model is to forecast existing points using data leading up to those points. Here, we use the model to forecast the last 5 points using the full dataset excluding those last 5 points. We then compare to get an idea of model performance. Note that we generated 200 samples and the index for those samples starts at 0. Therefore, our 200th sample is at positional index 199:

df_pred = ar_aic.get_prediction(start=195, end=199).summary_frame(alpha=0.05)
df_pred.index=[195,196,197,198,199] # reindexing for 0 index

In the following table, the mean column is the forecast. We manually appended the actuals column with the last 5 values in our data to compare to the forecast. mean_se is our mean squared error for our estimates compared to actuals. y is our index and the ci columns are for our 95% forecast confidence interval since we used alpha=0.05 in the previous code.

ymeanmean_semean_ci_lowermean_ci_upperactuals
19524.703910.9990622.7457926.66203525.5264
19619.364530.9990617.406421.32265218.8797
1977.5259040.999065.5677799.4840287.4586
198-5.87440.99906-7.83252-3.916274-7.1316
199-19.57850.99906-21.5366-17.620356-17.9268

Figure 11.6 – AR(4) model outputs versus actuals

We can see based on our mean squared error (0.999062) that our model provides a reasonable fit across a forecast horizon of 5 points on test data. Using the following code, we plot our test forecast against the corresponding actuals:

fig, ax = plt.subplots(1,1,figsize=(20,5))
ax.plot(y, marker='o', markersize=5)
ax.plot(df_pred['mean'], marker='o', markersize=4)
ax.plot(df_pred['mean_ci_lower'], color='g')
ax.plot(df_pred['mean_ci_upper'], color='g')
ax.fill_between(df_pred.index, df_pred['mean_ci_lower'], df_pred['mean_ci_upper'], color='g', alpha=0.1)
ax.set_title('Test Forecast for AR(4)')

Figure 11.7 – The AR(4) test forecast

Determining a reasonable forecast horizon is highly dependent on at least the data and the process it represents, and the lag used for modeling, in addition to model error. The time series practitioner should weigh all factors of model performance and business needs versus risks before providing forecasting to stakeholders. Adding the following code, we re-run the plot to see our true forecast with a 5-point horizon:

df_forecast = ar_aic.get_prediction(start=200, end=204).summary_frame(alpha=0.05)
df_forecast.index=[200, 201, 202, 203, 204]
forecast = np.hstack([np.repeat(np.nan, len(y)), df_pred['mean']])

Figure 11.8 – The AR(4) forecast horizon = 5

We will cover additional steps in the model evaluation section of this chapter.

Whereas the AR(p) model is a direct function of the correlation between lag zero and specific individual lags of order p over time, the moving average model of order q, MA(q), is a function of autocorrelation between lag zero and all previous lags included in order q. It acts as a low-pass filter that models errors to provide a useful fit to data.

Let us take a process,, that has a mean of zero and a random, normally distributed white noise component,, where. If we can write this process as

and are real constants and, then we can call this a moving average process having order q, or MA(q). In backshift operator notation, we have the following:

We can define the autocorrelations () for the MA(q) model thusly:

For all lags k in Where, we have

When discussing the AR(p) models, we explained how the roots of the AR model must be outside the unit circle. When considering MA(q) models, we have the concept of invertibility. Invertibility essentially ensures a logical and stable correlation with the past. Typically, this means the current point in time is more closely related to nearby points in the past than those more distant. The inability to model a process using invertible roots means we cannot ensure our model provides a unique solution for the set of model autocorrelations. If points in the distant past are more relevant to the current point than those nearby, we have a randomness in the process that cannot be reliably modeled or forecasted.

Identifying MA(q) model invertibility

For a moving average model to be invertible, all roots must be outside the unit circle and non-imaginary; all roots must be greater than 1. For an MA(1) process, it is invertible when |ϴ 1| < 1. An invertible MA(q) process is equivalent to an infinite-order, converging AR(p). An AR(p) model converges if its coefficients converge to zero as lags k approach p. If an MA(q) is invertible, we can say and [1].

For an MA(q) model of order 1, we have the following process:

For a MA(q) model with zero autocorrelation, the pattern of whose process we are attempting to model is random, normally distributed white noise variance, which can – at best – only be modeled by its mean. It is important to note that as, and for an MA(1) process, this means the process can be approximated by white noise.

Let us consider the following MA(1) zero-mean model following the form:

In backshift notation we have the following:

We know this process is invertible because. Let us confirm this with Python using the ArmaProcess function from the statsmodels tsa module:

from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
import matplotlib.pyplot as plt
import statsmodels.api as sm
import numpy as np
maparams = np.array([0.8])
ma = np.r_[1, -maparams]
ma_process = sm.tsa.ArmaProcess(ma=ma)
print('MA(1) Roots: ', ma_process.maroots)
print('MA(1) Invertibility: ', ma_process.isinvertible)

MA(1) Roots: [``1.25]

MA(1) Invertibility: ``True

Contrary to the AR(p) model, the MA(q) model’s order is identified using the ACF plot. Because the ACF does not control for lags and is a composite autocorrelation measure across all lags up to the lag whose autocorrelation measure is considered, the function is used to identify the relevant lag order for the moving average component. In Figure 11*.9*, we can see the significant correlation at lag 1 for our MA(1) process. There are two additional significant correlations at lags 6 and 7, but using lags this far out typically results in overfitting, especially when taken alongside the fact that lags 2 through 5 are not significant at the 5% level of significance:

Figure 11.9 – MA(1) plots

Dampening ACFs and PACFs

For an invertible moving average model, we can observe that the ACF will cut off at the order of significance, but the PACF will typically continue and dampen overall to statistical zero over time. It is not necessarily expected to happen smoothly and all at once as all data sets are different, but it is expected that over time, more and more lags will dampen to zero. We explain the reason for this behavior from the ACFs and PACFs in the ARMA section of this chapter, but it is worth noting this is to be expected for invertible processes. Conversely, stationary autoregressive processes are expected to cut off at the order of significance in the PACF plots while the ACFs dampen to zero over time.

For an MA(q) model of order 2, we have this:

The following is an MA(2) example we will look at:

Using the model’s polynomial in the quadratic equation form, we can find the approximate roots using the quadratic formula:

Because we have two complex conjugate roots, we can take the same we did for the AR(p) process, using the form of:

Because 1.054 is greater than 1, we can confirm the MA(2) has invertible roots and is thus capable of producing a unique solution and a model whose values are logically serially correlated to past values. Let us perform the same analysis in Python:

maparams = np.array([1.6, -0.9])
ma = np.r_[1, -maparams]
ma_process = sm.tsa.ArmaProcess(ma=ma)
print('MA(2) Roots: ', ma_process.maroots)
print('MA(2) Invertibility: ', ma_process.isinvertible)

The output we see highlighted in green confirms our calculated findings and the fact that since the magnitude of the complex conjugate roots is greater than 0, we have an invertible MA(2) process:

MA(2) Roots: [``0.88888889-0.56655772j 0.88888889+0.56655772j]

MA(2) Invertibility: ``True

We can see in the ACF in Figure 11*.10* that this is a second-order moving average process:

Figure 11.10 – MA(2) plots

The process and code for identifying model ordering, building the model, and generating a forecast are the same for the MA(q) model as it is for the AR(p) model. We have discussed that the order selection based on visual inspection for the MA(q) is performed using the ACF, whereas for the AR(p) this is done using the PACF, and that it is the only major difference in the process between the two models. Aside from that, enforce_invertibility should be set to equal True for MA(q) models in place of enforce_stationarity=True. Providing a max_ar or max_ma order higher or lower than useful in the arma_order_select_ic function may result in a convergence warning or an invertibility warning. One reason for these warnings is there was a higher order provided than possible to fit (such as when there is no order possible). Another reason is the presence of a unit root. If there is an apparent trend in the data, it must be removed before modeling. If there is no trend, it is possible to receive this error due to seasonality in the data, which presents a different order of unit root. We will discuss modeling in the case of unit roots associated with trend and seasonality in the ARIMA and seasonal ARIMA section of this chapter. It is also worth specifying that the Dickey-Fuller test can be used for moving average data since moving average processes can be influenced by trends.

Autoregressive moving average (ARMA) models

Section titled “Autoregressive moving average (ARMA) models”

In the autoregressive model section, we discussed how an AR(p) model is used to model process output values using autocorrelation controlling for individual lags. The goal of the AR(p) model is to estimate exact values for points corresponding to lags in the future using the values for the same specific lags in the context of a past horizon. For example, the value at two points in the future is strongly correlated with the value at two points in the past. In the moving average model section, we discussed how MA(q) models act as low-pass filters that help a model explain noise in a process. Rather than seeking to model exact points, we use the MA(q) to model variance around the process.

Consider an example of a four-cylinder car engine that produces constant output. Let us assume we have a worn-down motor mount near the fourth cylinder. We can expect consistent output vibration related to each cylinder firing, but the vibration will increase slightly for each stroke that is closer to the worn motor mount. Using an AR-only model would assume each cylinder vibrates a certain amount and be able to account for that, but we would be missing information. Adding a MA component would be able to model the fact that starting at cylinder one, each subsequent stroke up through cylinder four will have additional vibration related to the worn motor mount and thus explain much more of the overall process. This would reasonably be an ARMA(4,4) model. Suppose we replace the worn-down motor mount with a mount of equal wear compared to the other mounts; we would then have an ARMA(4,0) (or AR(4)) process.

In many cases, we find we have significant peaks in both autocorrelation and partial autocorrelation. Rather than using only MA(q) or AR(p) modeling, respectively, we can combine the two. This combination, represented as an ARMA(p,q), enables us to model the process as well as any noise component around the process that may correlate to specific lags. Because an ARMA(p,q) typically has fewer parameters (lower order) for each AR and MA component than AR or MA models do, the ARMA is considered a parsimonious model, which is a model that uses as few explanatory variables (in this case, time lags) as possible to achieve the desired level of performance. When is an invertible and stationary process, we can define it as an ARMA(p,q):

Where and, we can re-write the equation for ARMA(p,q) in backshift operator notation:

Practically speaking, we can expect that for an invertible moving average process, we see significant lags in the ACF up to the magnitude of the order q, but then the PACF will taper off thereafter, typically in lags beyond the order of the moving average process identified in the ACF. This is because a finite moving average process can be represented as an infinite-order autoregressive process. Conversely, because the moving average process that has this behavior is invertible, the inverse must also be true; that a finite autoregressive process can be represented as an infinite-order moving average process. Therefore, the PACF will dampen to zero for an invertible moving average process, and for a stationary autoregressive process, the ACF will dampen to zero. Because invertibility is a requirement of an ARMA process, it allows us to re-write the equation as an infinite-order MA process in general linear form:

It also allows us to do so as an infinite-order AR process:

Let us walk through an example in Python. First, using the same imports we did before in this chapter, let us generate an invertible and stationary ARMA(2,1) process dummy dataset that satisfies the following equation:

arparams = np.array([1.2, -0.6])
ar = np.r_[1, -arparams]
maparams = np.array([0.5])
ma = np.r_[1, -maparams]
arma_process = sm.tsa.ArmaProcess(ar=ar, ma=ma)

Let us confirm stationary and invertibility:

print('AR(2) Roots: ', arma_process.arroots)
print('AR(2) Invertibility: ', arma_process.isstationary)
print('MA(1) Roots: ', arma_process.maroots)
print('MA(1) Invertibility: ', arma_process.isinvertible)

We can use the quadratic formula to test, but we can trust the code to confirm:

AR(2) Roots: [``1.-0.81649658j 1.+0.81649658j]

AR(2) Stationarity: ``True

MA(1) Roots: [``2.]

MA(1) Invertibility: ``True

Now that we have a stationary and invertible process, let us generate 200 samples from it:

y = arma_process.generate_sample(nsample=200)

Let us take a look at the plots we have been using to build intuition about the process that generated the data:

Figure 11.11 – ARMA(p,q) process sample data

We can see using the ACF that we have what appears to be an MA(1) component. Based on the PACF, it looks as if we could have either an AR(2) or an AR(4). The realization appears to be a process that satisfies stationarity.

Before we decide on an order for our ARMA model, let us use the Dickey-Fuller test to check if our data has any trend:

from statsmodels.tsa.stattools import adfuller
dicky_fuller = adfuller(y, maxlag=25, regression='c')
print('Dickey-Fuller p-value: ', dicky_fuller[1])
print('Dickey-Fuller test statistic: ', dicky_fuller[0])
print('Dickey-Fuller critical value: ', dicky_fuller[4].get('5%'))

We can see the statistical significance that confirms we do not have a unit root in the lags provided with maxlag (remember, the data has a unit root and the data does not have a unit root). Therefore, we can use the ARMA model without any first-order differencing, which would require at least an ARIMA:

Dickey-Fuller p-value: ``6.090665062133195e-16

Dickey-Fuller test statistic: - 9.40370671340928

Dickey-Fuller critical value: - 2.876401960790147

Now let us use statmodels arma_order_select_ic to see what AIC and BIC select for the ARMA(p,q) order. We know the maximum order for an MA(q) is one, but since we are not sure if this is an AR(2) or an AR(4), we can use max_ar=4:

from statsmodels.tsa.stattools import arma_order_select_ic
model_arma = arma_order_select_ic(y=y, max_ar=4, max_ma=1, ic=['aic','bic'], trend='n')
print('AIC Order Selection: ', model_arma.aic_min_order)
print('AIC Error: ', round(model_arma.aic.min()[0], 3))
print('BIC Order Selection: ', model_arma.bic_min_order)
print('BIC Error: ', round(model_arma.bic.min()[0], 3))

We can see that AIC selected an ARMA(4,1) and BIC selected an ARMA(2,1):

AIC Order Selection: (``4, 1)

AIC Error: ``548.527

BIC Order Selection: (``2, 1)

BIC Error: ``565.019

The ARMA(4,1) has a lower error, but we know from this and previous chapters in the book that models with lower error on training data may be more likely to have more variance and thus be more likely to overfit. However, let us use ARMA(4,1).

Now let us build our ARMA(4,1) model. Note the 0 is for the integrated first-order difference for an ARIMA(p,d,q) model. Since we do not have a trend-based unit root, we do not need to difference to remove any trend. Thus, d=0:

from statsmodels.tsa.arima.model import ARIMA
arma_aic = ARIMA(y, order=(4,0,1),
enforce_stationarity=True, enforce_invertibility=True).fit()
print(arma_aic.summary())

Here, we can see the model provides a reasonable fit based on the model metrics. However, there is one issue; our first three AR coefficients have no statistical significance (high p-values and confidence intervals containing zero). This is a big problem and confirms our model is overfitted. Our model includes terms it is not getting benefit from. Therefore, our model would most certainly fail to generalize well on unseen data and should be reconstructed:

Figure 11.12 – ARIMA(4,0,1) model results

Let us re-run this as an ARMA(2,1), which is the same as an ARIMA(2,0,1) since there is no differencing to be integrated. This is what we visually identified, and BIC selected the following code:

from statsmodels.tsa.arima.model import ARIMA
arma_aic = ARIMA(y, order=(2,0,1),
enforce_stationarity=True, enforce_invertibility=True).fit()
print(arma_aic.summary())

We can see now a much better fit for our variables. All coefficients are significant, and the model metrics remain sufficient. The model we have identified corresponds to the following equation:

We can compare that to our dummy process:

Figure 11.13 – ARIMA(2,0,1) model results

Now, let us cross-validate our model by training the model on data up through the last five points, then forecasting the last five points so that we can compare them to the actuals. Recall that our indexing starts at 0 so our dataset ends at index 199:

df_pred = arma_aic.get_prediction(start=195, end=199).summary_frame(alpha=0.05)
df_pred.index=[195,196,197,198,199]

We can see our predicted values in the mean column in the following table:

ymeanmean_semean_ci_lowermean_ci_upperactuals
195-0.019110.932933-1.847621.809406310.559875
1960.584460.932933-1.244062.4129752420.778127
1970.4793640.932933-1.349152.3078790571.695218
1980.9140090.932933-0.914512.742524652.041826
1990.809130.932933-1.019392.6376452060.578695

Figure 11.14 – AR(4) model outputs versus actuals

Let’s print out our model’s Average Squared Error (ASE):

print('Average Squared Error: ', np.mean((df_pred['mean'] - y[195:])**2))

Here we see the ASE:

Average Squared Error: ``0.6352208223437921

Our test forecast plot is shown in Figure 11*.15*. Note that our estimate appears conservative. Using ARMA(4,1) may have produced a closer, but less generalizable fit. One method for improving forecasting would be to build the model using only recent points (relative to subject matter knowledge of the process). Including a larger set of data will produce a fit that generalizes more to the overall process rather than to a possibly more relevant timeframe:

Figure 11.15 – ARMA(2,1) test forecast

Now, let us forecast five ahead:

df_forecast = arma_aic.get_prediction(start=200, end=204).summary_frame(alpha=0.05)
df_forecast.index=[200, 201, 202, 203, 204]
forecast = np.hstack([np.repeat(np.nan, len(y)), df_pred['mean']])

Figure 11.16 – ARMA(2,1) forecast horizon = 5

On a final note, regarding ARMA models, we always assume process stationarity. If stationarity cannot be assumed, neither autoregressive nor moving average models can be used. In the next section of this chapter, we will discuss integrating into ARMA models first-order differencing as a method for conditionally stationarizing a process to overcome limitations of non-stationarity.

In the previous section, we discussed ARMA models for stationary time series data. In this section, we will look at non-stationary time series data and extend our model to work with non-stationary data. Let us start by taking a look at some sample data (shown in Figure 11*.17*). There are two series: US GDP (left) and airline passenger volume (right).

Figure 11.17 – US GDP (left) and airline passenger (right) time series

The US GDP series appears to exhibit an upward trend with some variations in the series. The airline passenger volume series also exhibits an upward trend, but there also appears to be a repeated pattern in the series. The repeated pattern in the airline series is called seasonality. Both series are non-stationary because of the apparent trend. Additionally, the airline passenger volume series appears to exhibit non-constant variance. We will model the GDP series with ARIMA, and we will model the seasonal ARIMA. Let’s take a look at these models.

ARIMA is an acronym for AutoRegressive Integrated Moving Average. This model is a generalization of the ARMA model that can be applied to non-stationary time series data. The new part added to this model is “integrated,” which is a differencing operation applied to the time series to stationarize (to make stationary) the time series. After the time series is stationarized, we can fit an ARMA model to the differenced data. Let’s take a look at the mathematics of this model. We will start with understanding how differencing works, and then put the whole model ARIMA model together.

Differencing data is computing the difference between consecutive data points. The resulting data from differencing represents the change between each data point. We can write the difference as such:

This equation is the first-order difference, meaning it is the first difference between the data points. It may be necessary to make additional differences between the data points to stationarize the series. The second difference represents the change of changes between the data points. The second-order difference can be written thusly:

The “order” is simply the number of times a difference operation is applied.

As mentioned earlier, the ARIMA model is ARMA with the addition of differencing to make the time series stationary (stationarize the time series). Then we can express an ARIMA model mathematically as follows, where is the differenced series, differenced times until it is stationary:

The ARIMA model has three orders, which are denoted ARIMA(p,d,q):

  • p – the autoregressive order
  • d – the differencing order
  • q – the moving average order

With more complicated models such as ARIMA, we will tend to describe them with backshift notation since it is easier to express these models with backshift notation. An ARIMA model will take the following form using backshift notation:

Notice the term for the differences in the equation: In the previous section, we discussed roots as related to stationary models. In that context, the roots were always outside of the unit circle. With an ARIMA model, we add unit roots to the model. To understand the impact of a unit root, let’s simulate an AR(1) model and see what happens as the root of the model is moved toward one. These simulations are shown in Figure 11*.18*.

Figure 11.18 – AR(1) simulations with root approaching 1

We can make two observations from the simulations shown in Figure 11*.18*. The first observation is that the time series appear to exhibit more wandering behavior as the root increases toward one. For instance, the middle-time series shows more wandering from the mean than the top-time series. The bottom time series (with a root of one), does not appear to regress toward a mean such as the other two simulations. The second observation is about the autocorrelations. As the root of the AR(1) approaches 1, the autocorrelations get stronger and decrease slower over the lags. These two observations are characteristic of a series with a root near or at one. Additionally, the presence of unit roots will dominate the time series behavior, making it easy to recognize from the autocorrelation plot.

There are two steps to fit an ARIMA model: (1) stationarize the series from differencing to determine the difference order and (2) fit an ARMA model to the resulting series. In the previous section, we discussed how to fit an ARMA model so in this section, we will focus on the first step.

At the beginning of this section, we showed a time series of US GDP values. We will use that time series as a case study for fitting an ARIMA model. First, let’s take a look at the series and its autocorrelations again. The series and autocorrelations are shown in Figure 11*.19*.

Figure 11.19 – US GDP time series and autocorrelations

From the plots shown in Figure 11*.19*, it appears that the time series of US GPD data is non-stationary time series. The time series exhibits wandering behavior, and the autocorrelations are strong and decrease slowly. As we discussed, this is characteristic behavior of unit roots. For secondary evidence, we can use the Dickey-Fuller test for unit root. The null hypothesis of the Dickey-Fuller test is that a unit root is present in the time series. The following code shows how to use the Dickey-Fuller test from pmdarima. The test returns a p-value of 0.74 indicating we cannot reject the null hypothesis, meaning that the time series should be differenced:

Import pmdarima as pm
from sktime import datasets
y_macro_economic = datasets.load_macroeconomic()
adf_test = pm.arima.ADFTest()
adf_test.should_diff(y_macro_economic.realgdp.values)
# (0.7423236714537164, True)

We can take the first difference of time series using the diff function from numpy:

first_diff = np.diff(y_macro_economic.realgdp.values, n=1)

Taking the first difference, we arrive at a new time series as shown in Figure 11*.20*:

Figure 11.20 – The first difference of US GDP time series

The first difference of the US GDP time series shown in Figure 11*.20* appears to be stationary. In fact, it appears to be consistent with an AR(2) model. We double-check whether we need to take an additional difference using the Dickey-Fuller test on the first differenced data:

first_diff = np.diff(y_macro_economic.realgdp.values, n=1)
adf_test.should_diff(first_diff)
# (0.01, False)

The Dickey-Fuller test returns a p-value of 0.01 for the first differenced data, which means we can reject the null hypothesis and we can stop differencing the data. That means that our ARIMA model for this data will have a difference order of 1 ().

After finding the difference order, we can fit an ARMA model to the differenced data. Since we have already discussed fitting ARMA models, we will use an automated fitting method provided by pmdarima. pm.auto_arima is a function for automatically fitting an ARIMA model to data, however, in this case, we will use it to fit the ARMA portion from the differenced series. The output of pm.auto_arima for the first difference data is shown in the following code block:

pm.auto_arima(
first_diff, error_action='ignore', trace=True,
suppress_warnings=True, maxiter=5, seasonal=False,
test='adf'
)
Performing stepwise search to minimize aic
ARIMA(2,0,2)(0,0,0)[0] : AIC=2207.388, Time=0.03 sec
ARIMA(0,0,0)(0,0,0)[0] : AIC=2338.346, Time=0.01 sec
ARIMA(1,0,0)(0,0,0)[0] : AIC=2226.760, Time=0.02 sec
ARIMA(0,0,1)(0,0,0)[0] : AIC=2284.220, Time=0.01 sec
ARIMA(1,0,2)(0,0,0)[0] : AIC=2206.365, Time=0.02 sec
ARIMA(0,0,2)(0,0,0)[0] : AIC=2253.267, Time=0.02 sec
ARIMA(1,0,1)(0,0,0)[0] : AIC=2203.917, Time=0.01 sec
ARIMA(2,0,1)(0,0,0)[0] : AIC=2208.521, Time=0.02 sec
ARIMA(2,0,0)(0,0,0)[0] : AIC=2208.726, Time=0.02 sec
ARIMA(1,0,1)(0,0,0)[0] intercept : AIC=2193.482, Time=0.04 sec
ARIMA(0,0,1)(0,0,0)[0] intercept : AIC=2208.669, Time=0.03 sec
ARIMA(1,0,0)(0,0,0)[0] intercept : AIC=2195.212, Time=0.02 sec
ARIMA(2,0,1)(0,0,0)[0] intercept : AIC=2191.810, Time=0.03 sec
ARIMA(2,0,0)(0,0,0)[0] intercept : AIC=2190.196, Time=0.02 sec
ARIMA(3,0,0)(0,0,0)[0] intercept : AIC=2191.589, Time=0.03 sec
ARIMA(3,0,1)(0,0,0)[0] intercept : AIC=2193.567, Time=0.03 sec
Best model: ARIMA(2,0,0)(0,0,0)[0] intercept
Total fit time: 0.349 seconds

Since the ARMA fit for the differenced data is ARMA(2,0), the ARIMA orders for the original time series would be ARIMA(2,1,0). Next, we will look at forecasting from an ARIMA model.

Once we have a fit model, we can forecast with that model. As mentioned in previous chapters, when making predictions we should create a train-test split, so we have data to compare with the predictions. The model should only fit the training data to avoid data leakage. We can use the train_test_split function from pmdarima to split the data. Then we proceed with the usual steps: split, train, and predict. The code for this is shown in the following code block:

from pmdarima.model_selection import train_test_split
train, test =
train_test_split(y_macro_economic.realgdp.values,
train_size=0.9
)
arima = pm.auto_arima(
train, out_of_sample_size=10,
suppress_warnings=True, error_action='ignore',
test='adf'
)
preds, conf_int = arima.predict(
n_periods=test.shape[0], return_conf_int=True
)

The preceding code fits an ARIMA model with auto_arima and then forecasts the size of the test set using the predict method of the ARIMA object. The forecasts for the series generated by the code are shown in Figure 11*.21*:

Figure 11.21 – US GDP ARIMA forecast over test split

The forecast of the US GDP in Figure 11*.21* appears to follow the trend of the data but does not capture the small variations in the series. However, the variation is captured in the prediction interval (labeled as “interval”). This model appears to provide a reasonably good prediction of the test data. Note that the interval increases over time. This is because predictions become more uncertain farther in the future. Generally, shorter forecasts are more likely to be accurate.

In this section, we built on the ARMA model and extended it to non-stationary data using differencing, which formed the ARIMA model. In the next section, we will look at non-stationary time series that include seasonal effects and make a further extension to the ARIMA model.

Let’s look at another characteristic of time series called seasonality. Seasonality is the presence of a pattern in a time series that repeats at regular intervals. Seasonal time series are common in nature. For example, yearly weather patterns and daily sunshine patterns are seasonal patterns. Back at the start of the non-stationary section, we showed an example of a non-stationary time series with seasonality. This time series is shown again in Figure 11*.22* along with its ACF plot.

Figure 11.22 – Airline volume data and ACF plot

The time series shown in Figure 11*.22* is the monthly total of international airline passengers from 1949 to 1960 [3]. There is a definite repeated pattern in this time series. To model this type of data, we will need to an additional term to the ARIMA model to account for seasonality.

We will use a similar approach for modeling this type of time series as we did with ARIMA. We will start by using differencing to stationarize the data, then fit an ARMA model to the differenced data. With seasonal time series, we will need to use seasonal differencing to remove the seasonal effects, which we can show mathematically:

Where is the period of the season. For example, the time series in Figure 11*.22* exhibits monthly seasonality and each data point represents one month; therefore, the for the airline volume data. Then, for the airline data, we would use the following difference equation to remove seasonality:

We can also identify the seasonality by observing where peaks occur in the ACF plot. The ACF plot in Figure 11*.22* shows a peak at 12, indicating a seasonal period of 12, which is consistent with our knowledge of the time series.

We will see how to apply seasonal differences later in this section using pmdarima. Let’s take a look at how seasonality is included in the model.

As mentioned in the ARIMA section, we will be differencing the original series, then fitting a stationary model to the differenced data. Then our time series would be described by the following equation where is the differenced series (including seasonal and sequential differences):

We can express the whole model with backshift notation:

We have a new term in the equation that accounts for seasonality:. We are adding a new order parameter to the model:. This model is typically denoted ARUMA(p,d,q,s).

SARIMA models

In this section, we are only covering seasonal differencing. There are more complex models that allow for moving average seasonality and autoregressive seasonality called SARIMA and denoted SARIMA(p,d,q)(P,D,Q)[m]. These models are beyond the scope of this chapter. However, we would encourage the reader to explore these models further after mastering the topics found in this chapter and the next chapter. The ARIMA model covered in this chapter is a subset of the SARIMA model, which accounts for seasonal differencing, which is the “D” order of SARIMA(p,d,q)(P,D,Q)[m].

Just as the term we added for ARIMA, the term adds roots to the unit circle. However, unlike the roots from, the roots from are distributed uniformly around the unit circle. These roots can be calculated and plotted programmatically with numpy and matplotlib or automatically with computational intelligence tools such as Wolfram Alpha (https://www.wolframalpha.com/).

We will take the following steps to fit an ARIMA model with seasonality:

  • Remove seasonality with differencing.
  • Remove additional non-stationarity with differencing.
  • Fit a stationary model to the resulting series.

This is essentially the same process we used to fit an ARIMA model, but there is an additional step to handle the seasonal component. Let us walk through an example with the airline data.

We will start with using differencing to remove the seasonal component of the time series. Recall that the seasonal period of the airline time series is 12, meaning that we need to perform differencing at lag 12 as shown with this equation:

We can perform this difference using the diff function from pmdarima. The following code shows how to perform the 12th lagged difference on the airline data:

import pmdarima as pm
from sktime import datasets
y_airline = datasets.load_airline()
series = pm.utils.diff( y_airline.values, lag=12)

After performing the seasonal difference, we get the differenced series shown in Figure 11*.23* along with the ACF plot. The seasonal portion of the time series appears to be completely removed. The differenced series does not appear to exhibit any repeating patterns. Additionally, the ACF plot does not show the seasonal peak that was present in the ACF plot of the original data:

Figure 11.23 – Airline data after seasonal difference

With the seasonal portion of the time series removed, we need to determine whether we need to take any additional differences to stationarize the new time series. The differenced series in Figure 11*.23* appears to exhibit a trend. The original data also exhibited a trend. As before, we can use the Dickey-Fuller test to get additional evidence on whether we should apply additional differences. Running the Dickey-Fuller test on this series will result in a p-value of 0.099, which suggests that we should take a difference in the series to account for a unit root:

adf_test = pm.arima.ADFTest()
adf_test.should_diff(series)
# (0.09898694171553156, True)

Taking the first difference of the series will result in the series shown in Figure 11*.24*. After taking these two differences the series appears to be sufficiently stationarized.

Figure 11.24 – Airline data after seasonal and first difference

The series in Figure 11*.24* shows the stationarized version of the airline data. Based on the ACF plot, we should be able to fit a relatively simple ARMA model to the stationarized series. We will use auto_arima function to make an automatic fit as we did in the ARIMA section:

pm.auto_arima(
series, error_action='ignore', trace=False,
suppress_warnings=True, maxiter=5, seasonal=False,
test='adf'
)
# ARIMA(1,0,0)(0,0,0)[0]

Fitting the differenced data with auto_arima returns an AR(1) model. A simple model as we expected.

Putting this all together our resulting model is an ARUMA(1,1,0,12). As with the previous ARIMA example, we could have fit this model with auto_arima, but we walked through the differencing steps here to help build intuition for what each difference element does to the series. Let’s take a look at the direct fit from auto_arima now:

pm.auto_arima(
y_airline.values, error_action='ignore', trace=True,
suppress_warnings=True, maxiter=5, seasonal=True, m=12,
test='adf'
)
# Best model: ARIMA(1,1,0)(0,1,0)[12]

We see that auto_arima found the same model that we did using manual differencing. Note the model is denoted in SARIMA format (see earlier callout about SARIMA). The (0,1,0)[12] means seasonality of 12 when one difference for the seasonality. Now that we have a fit model, let’s look at forecasting for our seasonal model.

Once we have a fit model, we can forecast with that model. As mentioned in the section on forecasting with ARIMA, when should we make a train-test split so we have data to compare with the predictions? We will use the same procedure: split the data, train the model, and forecast over the test set size:

train, test = train_test_split(y_airline.values, train_size=0.9)
sarima = pm.auto_arima(
train, error_action='ignore', trace=True,
suppress_warnings=True, maxiter=5, seasonal=True, m=12,
test='adf'
)
preds, conf_int = sarima.predict(n_periods=test.shape[0], return_conf_int=True)

The preceding code fits a full SARIMA model with auto_arima and then forecasts the size of the test set using the predict method. The forecasts for the series generated by the code are shown in Figure 11*.25*.

Figure 11.25 – SARIMA forecast of the airline data

The forecast of the airline data in Figure 11*.25* appears to capture the variation of the data very well. This is likely due to the strength of the seasonality component in the time series. Note that the prediction intervals increase over time just as with the ARIMA prediction intervals, but the intervals follow the general pattern of the series. This is an impact of the additional knowledge of seasonality in the series.

In this section, we discussed ARIMA models with seasonality and showed how to remove seasonal components. We also looked at forecasting a model with seasonality. In the next section, we will take a closer look at validating time series models.

In the previous sections, we discussed other methods to prepare data, test and validate models. In this section, we will discuss how to validate time series models and introduce several methods for validating time series models. We will cover the following methods for model evaluation: resampling, shifting, optimized persistence forecasting, and rolling window forecasting.

The real-world dataset considered in this section is Coca Cola stock data collected from Yahoo Finance databases from 01/19/1962 to 12/19/2021 for stock price prediction. This is a time series analysis to forecast the future stock value of a given stock. The reader can download the dataset from the Kaggle platform for this analysis. To motivate the study, we first go to explore the Coco Cola stock dataset:

data = pd.read_csv("COCO COLA.csv", parse_dates=["Date"], index_col="Date")

Figure 11.26 – Coco Cola dataset

The Date index is related to 15096 trading days from 01/19/1962 to 12/19/2021. The High and Low columns here refer to the maximum and minimum prices on each trading day. Open and Close refer to the stock prices when the market was open and closed on the same trading day. The total amount of trading stocks in each day refers to the Volume column and the last column (Adj Close) refers to adjusted values (combining with stock splits, dividends, etc.). To illustrate how resampling, shifting, rolling windows, and expanding windows perform, we narrow down to use only the Open column from the year 2016:

data= data[data.index>='2016-01-01'][['Open']]

The data was collected by trading dates. However, we will perform the study monthly. The resampling technique is used to aggregate data from days to months. This idea motivates us to introduce this technique.

Resampling is a method to deal with time frequency. We use this method to change time series data frequency by a new time frequency. There are upsampling and downsampling. In upsampling, the frequency of the samples is increased using interpolation, for instance, from day frequency to minute or second frequency. On the other hand, downsampling is used to decrease the sample time frequency using summary statistics to aggregate the current time frequency in a dataset to a new time frequency. Resampling can be used in feature engineering and also used for problem framing when time frequency in the dataset is not available for our analysis purposes. In Python, we can use the resample() function to change time frequencies. The following code illustrates the resampling technique in Python:

fig, ax = plt.subplots(4,1, figsize=(12,8))
ax[0].set_title('Original stock price from 2016')
ax[0].plot(data)
ax[1].plot(data.resample('7D').mean())
ax[1].set_title('7 days - Downsampling stock price from 2016')
ax[2].plot(data.resample('M').mean())
ax[2].set_title('Monthly Downsampling stock price from 2016')
ax[3].plot(data.resample('Y').mean())
ax[3].set_title('Yearly Downsampling stock price from 2016')
fig.tight_layout(pad=5.0)
plt.show()

Here is the output of the previous code:

Figure 11.27 – Resampling for Coco Cola dataset

We observe that the plots become smoother when time frequencies decrease. Next, we discuss the shifting method used in time series.

In time series analysis, it is not uncommon to shift data points to compare lagging and leading futures. We demonstrated using the cross-correlation function in Chapter 10 as a method to help identify lagging and leading. We use the Coco Cola stock prices from 2016 to the month with the shift() function to create new features:

data["price_lag_1"] = data["Open"].shift(1)
data.head()

Figure 11.28 – First five rows of Coco Cola stock data with price shifted once

Observe that the first row of the price_lag_1 column is filled with a NaN value. We can replace the missing value with the fill_value parameter:

data["price_lag_1"] = data["Open"].shift(1, fill_value = data['Open'].mean())

Finally, we discuss the forecasting methods such as optimized persistence and rolling window forecasting. Another resource related to these methods can be found in [3].

We will convert the Coco Cola stock price time frequency to monthly frequency from 2016 using resampling and then we apply an optimized persistence forecasting technique to predict the future value using the previous observation. RMSE scores are considered to evaluate persistence models:

from sklearn.metrics import mean_squared_error
import math
train, test = data.resample('M').mean()['Open'][0:-24], data.resample('M').mean()['Open'][-24:]
persistence = range(1, 25)
RMSE_scores = []
for p in persistence:
history = [x for x in train]
pred = []
for i in range(len(test)):
# Prediction on test set
yhat = history[-p]
pred.append(yhat)
history.append(test[i])
# RMSE score performance
rmse = math.sqrt(mean_squared_error(test, pred))
RMSE_scores.append(rmse)
print(f'p={p} RMSE={rmse}')

The output is as follows:

Figure 11.29 – RMSE scores for Optimized persistence forecasting

We observe that when p=6, the RMSE score is the smallest:

Figure 11.30 – Optimized Persistence Forecasting, test versus prediction

Running the persistence test again with p=6, we can see the following:

history = [x for x in train]
pred = []
for i in range(len(test)):
# Prediction
yhat = history[-6]
pred.append(yhat)
history.append(test[i])
# Plots
plt.plot(list(test))
plt.plot(pred)
plt.show()

Then, we can produce a visualization:

Figure 11.31 – Optimized Persistence Forecasting

The blue curve is the test value, and the orange curve is for the prediction.

This technique creates a rolling window with a specified window size and then performs a statistic calculation in this window, using it for forecasting which rolls through the data used in a study. We conduct a similar study as in the last part on the Coco Cola stock price dataset from 2016 using a monthly resampling dataset:

from numpy import mean
train, test = data.resample('M').mean()['Open'][0:-24], data.resample('M').mean()['Open'][-24:]
window = range(1, 25)
RMSE_scores = []
for w in window:
history = [x for x in train]
pred = []
for i in range(len(test)):
# Prediction on test set
yhat = mean(history[-w:])
pred.append(yhat)
history.append(test[i])
# RMSE score performance
rmse = math.sqrt(mean_squared_error(test, pred))
RMSE_scores.append(rmse)
print(f'w={w} RMSE={rmse}')
plt.plot(window, RMSE_scores)
plt.title('Rolling Forecasting')
plt.xlabel('Windows sizes')
plt.ylabel('RMSE scores')
plt.show()

Figure 11.32 – Rolling window forecasting

With window size = 9, the RMSE of 3.808 is the smallest. Run the Python code again with window size = 9 we produce a similar visualization as with the Optimized Persistence Forecast.

In this chapter, we discussed various methods for modeling univariate time series data from stationary time series models such as ARMA to non-stationary models such as ARIMA. We started with stationary models and discussed how to identify modeling approaches based on the characteristics of time series. Then we built on the stationary models by adding a term in the model to stationarize time series. Finally, we talked about seasonality and how to account for seasonality in an ARIMA model. While these methods are powerful for forecasting, they do not incorporate potential information from other external variables. As in the previous chapter, we will see that external variables can help improve forecasts. In the next chapter, we will look at multivariate methods for time series data to take advantage of other explanatory variables.

Please refer to the final word file for how the references should look.

  1. APPLIED TIME SERIES ANALYSIS WITH R, W. Woodward, H. Gray, A. Elliott. Taylor & Francis Group, LLC. 2017.
  2. Box, G. E. P., Jenkins, G. M. and Reinsel, G. C. (1976) Time Series Analysis, Forecasting and Control. Third Edition. Holden-Day. Series G.
  3. Brownlee, J, (2017) Simple Time Series Forecasting Models to Test So That You Don’t Fool Yourself (https://machinelearningmastery.com/simple-time-series-forecasting-models/).