Skip to content
ImagineWorld

Multivariate Time Series

node_idnode-book_building-statistical-models-in-python_chapter-12-multivariate-time-series
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleMultivariate Time Series
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

The models we discussed in the previous chapter only depended on the previous values of the single variable of interest. Those models are appropriate when we only have a single variable in our time series. However, it is common to have multiple variables in time-series data. Often, these other variables in the series can improve forecasting of the variable of interest. We will discuss models for time series with multiple variables in this chapter. We will first discuss the correlation relationship between time-series variables, then discuss how we can model multivariate time series. While there are many models for multivariate time-series data, we will discuss two models that are both powerful and widely used: autoregressive integrated moving average with exogenous variables (ARIMAX) and vector autoregressive (VAR). Understanding these two models will extend the reader’s model toolbox and provide building blocks for the reader to learn more about multivariate time-series models.

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

  • Multivariate time series
  • ARIMAX
  • VAR modeling

In the previous chapter, we discussed models for univariate time series or a time series of one variable. However, in many modeling situations, it is common to have multiple time-varying variables that are measured together. A time series consisting of multiple time-varying variables is called a multivariate time series. Each variable in the time series is called a covariate. For example, a time series of weather data might include temperature, rain amount, wind speed, and relative humidity. Each of these variables, in the weather dataset, is a univariate time series, and together, a multivariate time series and each pair of variables are covariates.

Mathematically, we typically represent a multivariate time-series as a vector-valued series, as follows:

Here, each instance consists of multiple values at each time step, and there are steps in the series. The first index in the preceding equation represents the time step (0 through ), and the second index represents the individual series (0 through variables). For example, if were a time series of stock prices, at each time step of, there would be a value of each stock price. In that case, might look like the following equation if the first two stock symbols in the series were AAPL and GOOGL:

When we have a multivariate time series, a question arises: What can we do with this additional information? To answer that question, we need to understand whether these time-series variables are related. We can determine how time series are related by looking at their cross-correlation. Let’s discuss cross-correlation next.

We need to understand how time series can be related in order to determine whether covariate time series may be useful for forecasting a time series of interest. In a previous chapter, we discussed how to understand the relationship between two variables using plots and correlation coefficients; we will take a similar approach for the time-series data. Recall the following cross-correlation function (CCF) discussed in Chapter 10*, Introduction to* Time Series:

Here, is a univariate time series and is a univariate time series. This function tells us how and are related at lags. In this equation, is time steps behind. In this situation, we say that is leading by steps or is lagging by steps. We will use this CCF to help us determine whether two time series are related and at which time steps they are related. Notice that if, then the CCF reduces to the autocorrelation function (ACF).

Cross-correlation significance

Just as with the ACF, cross-correlations have a threshold for statistical significance. We consider any cross-correlation value with an absolute value greater than (where is the sample size of the time series) to be significantly different from zero.

Let’s take a look at cross-correlations with some data. This data [1] comes from the UCI Machine Learning Repository [2]. The data is weather data that was collected as part of a pollution study conducted in China. This data was sampled hourly over several years. We will subset the data to the first 1,000 data points. The weather data contained in this set consists of temperature (TEMP), pressure (PRES), dew point temperature (DEWP), rain precipitation (RAIN), and wind speed (WSPM). We will look at cross-correlations from the perspective of trying to forecast wind speed, meaning we will look at the cross-correlations of wind speed and the other variables. This may be an important problem for someone who wants to forecast power generation from windmills. The wind speed data and the ACF of the wind speed data are plotted in Figure 12*.1*:

Figure 12.1 – Plot of wind speed time series and its ACF

We can see from the plot in Figure 12*.1* that the wind speed could potentially be modeled by a stationary univariate model, which we discussed in the previous chapter. While there does not appear to be evidence of autoregressive integrated moving average (ARIMA) behavior, there does appear to be evidence of seasonality at lag 24. Since the data is sampled hourly, the seasonality is likely a daily pattern. We have plotted the time series of the other variables in Figure 12*.2*. These are the other variables we may want to use to help predict the value of wind speed:

Figure 12.2 – Plot of wind speed time series and three other weather variables

While we have not plotted the ACF for all the time series shown in Figure 12*.2*, these time series have characteristics that suggest they may be stationary. However, it is not clear from the time series alone whether these time series are related. This is where the cross-correlation of time series comes in. We can use a cross-correlation plot to determine whether any of the other time series are related to wind speed. We have plotted the cross-correlation of wind speed and the other variables in Figure 12*.3*. The CCFs are plotted up to 48 lags. Since the data was sampled hourly, this gives us 2 days’ worth of lags to see the cross-correlations:

Figure 12.3 – CCF plots of wind speed and three other variables

The plots in Figure 12*.3* show that there are cross-correlations between wind speed and the other variables. While we are not too interested in the shapes of the cross-correlations, the patterns may provide some depth to how the variables are related. For example, the cross-correlation of wind speed and temperature shows an oscillating pattern with a period of about 12 hours; this may correspond to the effect of sunlight on wind speed. The primary finding is that these other variables share a relationship with wind speed and may help us forecast the values of wind speed. Let’s take a look at how we can use the additional variables for modeling.

In the previous chapter, we discussed the ARIMA family of models and demonstrated how to model univariate time-series data. However, as we mentioned in the previous section, many time series are multivariate, such as stock data, weather data, or economic data. In this section, we will discuss how we can incorporate information from covariate variables when modeling time-series data.

When we model a multivariate time series, we typically have a variable we are interested in forecasting. This variable is commonly called the endogenous variable. The other covariates in the multivariate time series are called exogenous variables. Recall from Chapter 11*, ARIMA Models,* the equation representing the ARIMA model:

Here, is the differenced series, differenced times until it is stationary. In this model, is the variable we are interested in forecasting; it is the endogenous variable. Let us rewrite this equation in a more compact form. We collect the terms related to into one summation and the terms related to into another summation. Let us start with the terms:

Then, we will also collect the terms into different summations:

Putting these summations together, we get the following more compact version of our ARIMA equation:

Now, let’s add the exogenous variables to the model. We will add the exogenous variables by adding a summation term to the model:

Here, there are exogenous variables contained in the vector-valued variable. Recall from earlier in the chapter, we can represent the vector-valued variable, as shown next, where the first index represents the time step, and the second index represents an individual series within the vector-valued variable:

This is how we will incorporate the exogenous variables into the ARIMA model. Now, let’s talk about how we would pick the exogenous variables. In Chapter 11*, ARIMA Models*, using an ACF plot, we saw that certain lags of a time series are more influential than others for modeling a univariate time series. We will make similar judgments about exogenous variables using CCF plots. Let’s take a look at example CCF plots and discuss how to make these judgments.

The CCF plot for wind speed and temperature is shown in Figure 12*.4*. We have marked where the most significant cross-correlations occur within a lag period of 48 hours. Recall this data is sampled hourly; thus, each lagged time step corresponds to a lag of 1 hour. The plot shows that the most significant cross-correlations occur at approximately lag 13, lag 24, and lag 37:

Figure 12.4 – CCF plot of wind speed and temperature variables

Based on the observation of the cross-correlation plot in Figure 12*.4*, we would expect that temperature lags at 13, 24, and 37 could provide useful information for the current predicting wind speed. That is, the variables,, and may be useful for predicting. We can perform the same CCF analysis with the other two exogenous variables to determine which lags to use in the model. We found that pressure (PRES) had significant cross-correlations at lags 14 and 37, and dew point (DEWP) had significant cross-correlations at lags 2 and 20. Now that we have assessed which lags of the exogenous variables we want to use in the model, let us go ahead and preprocess the data and fit the model.

Before we fit the model, we need to preprocess the data to make the exogenous variables we mentioned previously. We need to create lagged versions of the time-series variables we described previously. We can lag a time series using the shift() method of a pandas DataFrame. Let’s take a look at a code example.

The following code sample shows how to use the shift() method to lag the pressure variable by 14. The first several lines of code import the library and load the data. The last line in the code sample shifts the PRES variable backward in time by 14 time steps:

import pandas as pd
# code to download the data
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00501/PRSA2017_Data_20130301-20170228.zip'
file_name = url.split('/')[-1]
r = requests.get(url)
with open(file_name, 'wb') as fout:
fout.write(r.content)
with zipfile.ZipFile(file_name, 'r') as zip_file:
zip_file.extractall('./')
df = pd.read_csv(
'./PRSA_Data_20130301-20170228/PRSA_Data_Aotizhongxin_20130301-20170228.csv'
, sep=','
)
pres_lag_14 = df.PRES.shift(-14)

The shift() method can be used to shift a series forward or backward in time. In this case, we want our exogenous variables to lag the variable we want to predict. So, we need to provide a negative shift value to move the series backward in time. We will use a similar preprocessing step for the other exogenous variables to create the other lagged variables. This is shown in the following code sample. All of these lagged variables created with the shift() method are collected into a new DataFrame called X, which we will use in the fit step:

temp_lag_13 = df.TEMP.shift(-13)
temp_lag_24 = df.TEMP.shift(-24)
temp_lag_37 = df.TEMP.shift(-37)
pres_lag_14 = df.PRES.shift(-14)
pres_lag_24 = df.PRES.shift(-37)
dewp_lag_13 = df.DEWP.shift(-2)
dewp_lag_24 = df.DEWP.shift(-20)
X = pd.DataFrame({
"temp_lag_13": temp_lag_13[:1000],
"temp_lag_24": temp_lag_24[:1000],
"temp_lag_37": temp_lag_37[:1000],
"pres_lag_14": pres_lag_14[:1000],
"pres_lag_24": pres_lag_24[:1000],
"dewp_lag_2": dewp_lag_13[:1000],
"dewp_lag_20": dewp_lag_24[:1000],
})

In the preceding code sample, we are taking a subset of the lagged variables (the first 1,000 data points) to limit the computation time of the model. With the variables collected in the new X DataFrame, the preprocessing is complete, and we can move on to fitting and assessing the model.

As in the previous chapter, we will use auto_arima to fit our ARIMA model. The main difference, in this case, is that we will need to provide the auto_arima function with the exogenous variables we created. The code to fit an ARIMA model with exogenous variables is shown in the following code sample:

y = df.WSPM[:1000]
arima = pm.auto_arima(
y, X,
error_action='ignore',
trace=True,
suppress_warnings=True,
maxiter=5,
seasonal=False,
test='adf'
)

This code should look very similar to the code shown in Chapter 11*, ARIMA Models*. In fact, the only difference is the addition is the X variable in the auto_arima function. Running this code will produce the following output:

Performing stepwise search to minimize aic
ARIMA(2,0,2)(0,0,0)[0] : AIC=2689.456, Time=0.24 sec
ARIMA(0,0,0)(0,0,0)[0] : AIC=8635.103, Time=0.16 sec
ARIMA(1,0,0)(0,0,0)[0] : AIC=2742.728, Time=0.29 sec
ARIMA(0,0,1)(0,0,0)[0] : AIC=2923.324, Time=0.32 sec
ARIMA(1,0,2)(0,0,0)[0] : AIC=2685.581, Time=0.23 sec
ARIMA(0,0,2)(0,0,0)[0] : AIC=2810.239, Time=0.37 sec
ARIMA(1,0,1)(0,0,0)[0] : AIC=2683.888, Time=0.23 sec
ARIMA(2,0,1)(0,0,0)[0] : AIC=2682.988, Time=0.28 sec
ARIMA(2,0,0)(0,0,0)[0] : AIC=2681.309, Time=0.26 sec
ARIMA(3,0,0)(0,0,0)[0] : AIC=2682.416, Time=0.32 sec
ARIMA(3,0,1)(0,0,0)[0] : AIC=2684.608, Time=0.32 sec
ARIMA(2,0,0)(0,0,0)[0] intercept : AIC=2683.328, Time=0.30 sec
Best model: ARIMA(2,0,0)(0,0,0)[0]
Total fit time: 3.347 seconds

Again, this output should look very similar to the output we saw from auto_arima in Chapter 11*, ARIMA Models*. It indicates we should use an AR(2) model based on the fit using the Akaike Information Criteria (AIC). Interestingly, there doesn’t appear to be any information regarding the exogenous variables. This is because auto_arima only needs to fit a single coefficient for each exogenous variable in the model. It does not need to fit an autoregressive moving average (ARMA) model for each exogenous variable. We can use the summary() method on the object returned from auto_arima to see the coefficients and significance tests for the exogenous variables. Running the summary() method will output the following seasonal autoregressive integrated moving average with eXogenous factors (SARIMAX) results:

Figure 12.5 – SARIMAX summary for AR(2) model

The output from the summary() method shown in the preceding snippet shows a lot of information. Let’s focus on the middle section of the output. The middle section shows the coefficients and significance tests for each exogenous variable and each ARIMA coefficient. The coefficients and test p-values are labeled coef and P>|z|, respectively. The significance test can help us determine whether variables should be included in the model.

Recall back in Chapter 7*, Multiple Linear Regression*, we discussed the idea of multicollinearity, which essentially means two or more predictor variables are highly correlated. We could encounter a similar situation here. For example, consider the temp_lag_13, temp_lag_24, and temp_lag_37 variables. Since the temperature time series exhibits autocorrelation, it is possible, even likely, that these lagged versions of the temperature time series could be highly correlated. When we observe multicollinearity, it is a sign that we can remove variables from the model. We would recommend using one of the feature selection methods described in Chapter 7, such as recursive feature selection, performance-based selection, or selection by statistical significance.

The preceding output shows only three of the exogenous variables in the current model, which are highlighted. This means we should consider reducing the variable in this model. We can do this with multiple methods; for this example, we will choose to eliminate features based on p-values. We will iteratively remove the feature with the highest p-value until all features have a p-value below 0.05. The code for this selection process is shown here:

# initial model
arima = pm.auto_arima(
y, X,
error_action='ignore',
trace=False,
suppress_warnings=True,
maxiter=5,
seasonal=False,
test='adf'
)
pvalues = arima.pvalues()
iterations = 0
while (pvalues > 0.05).any():
# get the variable name with the largest p-value
variable_with_max_pval = pvalues.idxmax()
# drop that variable from the exogenous variables
X = X.drop(variable_with_max_pval, axis=1)
arima = pm.auto_arima(
y, X,
error_action='ignore',
trace=False,
suppress_warnings=True,
maxiter=5,
seasonal=False,
test='adf'
)
pvalues = arima.pvalues()
print(f"fit iteration {iterations}")
iterations += 1

Performing this selection process will result in a model only containing the temp_lag_24, temp_lag_37, pres_lag_24, and dewp_lag_2 exogenous variables. The ARIMA portion of the model is still an AR(2) model. With a model selection taken, let’s assess the model’s performance.

We will assess the performance of the model by plotting the forecast versus the actual data points and calculating an error estimate. Let us start by looking at the forecasts from the ARIMAX model for the next 200 observations. The forecasts and test data points are plotted in Figure 12*.6*:

Figure 12.6 – Forecast of wind speed using an ARIMAX model

We can see the forecast for wind speed using the ARIMAX model we created in Figure 12*.6*. Two observations stand out from the plotted forecast:

  • The forecast captures the oscillation of the windspeed variable
  • The forecast fails to capture the high spikes in windspeed

To understand whether the exogenous variables provided material value in the model, we should compare the forecasts of the ARIMAX model, shown in Figure 12*.6*, to forecasts from a univariate model. The forecasts from a univariate model are shown i n Figure 12*.7*:

Figure 12.7 – Forecast of wind speed using an ARIMA model

The forecasts of the ARIMA model, shown in Figure 12*.7*, do not appear to capture much variation in the time series as the forecast length grows. This is actually a property of ARMA models. It should be evident from the two plots that the ARIMAX model provides a better forecast than the ARIMA model. Finally, let us compare the mean squared error (MSE) of the forecasts of the two models. The MSE from the ARIMAX model is approximately 1.5, while the MSE from the ARIMA model is about 1.7. The MSE value confirms what we saw in the plots—namely, the ARIMAX model provides a better forecast for this multivariate time series.

In this section, we discussed an extension to the ARIMA model that allows us to incorporate information from covariates in a multivariate time series. This is only one of many methods for multivariate time series. In the next section, we will discuss another method for working with multivariate time-series data.

The AR(p), MA(q), ARMA(p,q), ARIMA(p,d,q)m, and SARIMA(p,d,q) models we looked at in the last chapter form the basis of multivariate VAR modeling. In this chapter, we have discussed ARIMA with exogenous variables (ARIMAX). We will now begin discussion on the VAR model. First, it is important to understand that while ARIMAX requires leading (future) values of the exogenous variables, no future values of these variables are required for the VAR model as they are all autoregressive to each other – hence the name vector autoregressive – and by definition not exogenous. To start, let us consider the two-variable, or bivariate, case. Consider a process that is the output of two different input variables, and. Note that in matrix form, we are discussing the case of an matrix () where n corresponds to the point in time and m corresponds to the variables involved (variables ). We exclude the comma from notation going forward, but it is important to understand when we discuss multivariate autoregressive processes that we are discussing data within a multidimensional matrix rather than only the single-dimensional vector form we used for univariate time-series analysis. We can write our process,, in vector notation as follows:

We can expand on the input variables’ definitions as a VAR(1) process, here, for the two variables in shown previously:

The terms and are our model constants (β coefficients).

We can reduce the previous processes (using a zero-mean form) into the matrix-reduced form, like so:

Here, we have the following:

Our forecast for a VAR(1) model is shown here:

It also includes this:

Here, l represents the forward lag (), represents the forecasted value at time t for variable m, and corresponds to the most recent point in time (often, the length of the data). It is also important to note the covariance matrix is this:

Here, each covariance,, with k corresponding to the lag, is calculated as follows:

Our estimated cross-correlation between each variable and is therefore calculated as follows:

Understanding the calculations for cross-correlation and, especially, covariance helps with understanding the relationships between the variables and their impact on model fit. The method for combining the two models to generate one overall process forecast,, is through weighting the two input means and their correlations into one response. As we can see in our VAR(1) forecast, shown previously, the correlations between each given variable and the other variables across different points in time are able to be modeled using a VAR model. Notably, there are no truly independent and dependent variables in a VAR model; there is simply an interaction between each variable. It is important to note that all processes modeled with a VAR model should be stationary.

Using the United States Macroeconomic dataset found at https://www.statsmodels.org/dev/datasets/generated/macrodata.html, we can observe the relationship between real gross private domestic investment (realinv), real personal consumption expenditures (realcons), and real private disposable income (realdpi) with a zero-mean form in the context of VAR modeling, as follows:

Let us look at an example using this data in the VAR process in Python with the statsmodels VARMAX model. First, let’s load the data:

import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.tsa.api import VAR
data=sm.datasets.macrodata.load_pandas().data
data.sort_values(by=['year', 'quarter'], inplace=True)
data['yr_qtr'] = data['year'].astype(str) + data['quarter'].astype(str)
print('{}% of yearly quarters are unique'.format(round(100*(data['yr_qtr'].nunique() / len(data)), 1)))

We can see here from the output that 100% of our yearly quarters are unique and thus, no timestamp duplication exists:

100.0% of yearly quarters are unique

One of the first things we always need to do when performing regression-based time-series modeling is to ensure stationarity. In VAR modeling, this means all variables must be stationary. The first step is to visualize the process realizations through line plotting by index. If data points are aggregated at an interval desired to be modeled, then we can leave the index as is, but if a different time indexing is desired, we need to specify this. Here, we are going to build a model to determine how real consumption and real disposable income impact real investment. In the following code sample, we change quarter to the length of the data since that is the smallest denomination of time and there is one yearly quarter per index, as we checked previously. We then set the index to quarter (this is why quarter appears twice; once as the index and once as the column name):

data['quarter'] = range(1, len(data)+1)
data.drop('yr_qtr', axis=1, inplace=True)
data.index = data['quarter']

Note the updated index and quarter values:

quarteryearquarterrealconsrealinvrealdpi
1195911707.4286.8981886.9
2195921733.7310.8591919.7
3195931751.8289.2261916.4
4195941753.7299.3561931.3
5196051770.5331.7221955.5

Figure 12.8 – First five rows of macrodata data set for VAR modeling

Here, we will walk through six steps to produce a VAR model using the dataset we imported and prepared, shown partially in Figure 12*.8*.

In the line plot of the data in Figure 12*.9*, we can see what appears to be a strong linear trend. We need to check the ACF plots to assess this. After, we will run a Dickey-Fuller test to confirm:

Figure 12.9 – Line plots of realcons, realdpi, and realinv

The ACF plots in Figure 12*.10* show a strong indication of a linear trend and at least one unit root, which likely gives us that trend:

Figure 12.10 – ACF plots for VARMAX input variables

After running a Dickey-Fuller test, we can see that each variable contains a unit root and is thus trended. Therefore, we need to apply a first-order difference to all three variables so that we can work toward stationarizing the data. Recall that the null hypothesis for the Dickey-Fuller is that a unit root exists, and the alternative hypothesis is that one does not. We’ll execute the following code:

from statsmodels.tsa.stattools import adfuller
for col in ['realcons','realinv','realdpi']:
adfuller_test = adfuller(data[col], autolag='AIC')
print('ADF p-value for {}: {}'.format(col, adfuller_test[1]))

Here we can see the Dickey-Fuller results for each variable. Recall the null hypothesis is the presence of a single unit root. Therefore, since the p-values are not low, we will not reject the null hypothesis. This gives us statistical evidence to assume the presence of trend:

ADF p-value for realcons: 0.9976992503412904

ADF p-value for realinv: 0.6484956579101141

ADF p-value for realdpi: 1.0

Let’s difference the data here with a loop:

import numpy as np
data_1d = pd.DataFrame()
for col in ['realcons','realinv','realdpi']:
data_1d[col] = np.diff(data[col], n=1)

Now, we can rerun the ACF plots to check whether we still see trending autocorrelation. Because the original line plots did not appear to have seasonality, we will go ahead and plot the partial ACFs (PACFs) to get an idea of what kind of AR(p) ordering might be useful. Had we suspected seasonality, it might have been useful to check the spectral density of the sample autocorrelations to quantify seasonal periodicity, a process we demonstrated in Chapter 11*, ARIMA Models*. When checking the PACF plots, we will use the Yule-Walker method.

We can see in the ACF plots there is no apparent seasonality. When using a VAR model, all terms are used to estimate all other terms as the estimates for a forecast of any term are developed. In other words, to forecast one, we must forecast all. The reason this matters is that when looking at the PACFs in Figure 12*.11*, we can see one variable could arguably be fit with an AR(1) (real investment) model, one with an AR(2) (real disposable income) model, and another with an AR(3) (real consumption) model. Using orders that are significant for each variable is one important aspect of making VAR modeling work.

Another important aspect of selecting ordering in a VAR model is cross-correlation. For example, we may have a model of variables whose highest order is order 3, but if the cross-correlation between the target variable and the input variable is at lag 5, we would most likely need to use lag 5. However, a model using lag 3 or 4 may also be useful. As with any regression model, however, we will always want to check the significance of coefficient terms following model training:

Figure 12.11 – Differenced VARMAX variables; ACFs and PACFs

For a VAR model, cross-correlation is most important between the variables we consider as inputs and the variable(s) we consider our target. This can be done using multiple lags or with the most significant lag if multiple iterations of the same variable using different shifts are a concern for overfitting. We must confirm cross-correlation analysis used in a forecasting model is done with respect to each input variable and the dependent variable. A cross-correlation that shows the input variable as a leading indicator for the target variable is not of major concern; it means historical values of the input are used to predict the target. However, if we have a scenario where the input is a lagging indicator—meaning the target predicts the input—and we want to use the input to predict the target, we will need to shift the input forward so that the correlation is at lag 0 and trim the data by the amount shifted.

In many cases, there is significant leading and lagging cross-correlation; this may indicate seasonality. In the case of seasonality with a VAR model, an indicator variable should be included with the data that provides a value of 1 associated with the peak in spectral density and a 0 value otherwise. Another special case with cross-correlation is that the input variable has prominent statistical significance but only at a lag far back in time. In this case, it may be appropriate to shift the data forward so that the model does not include terms (autocorrelations) that are not significant at the risk of overfitting. To demonstrate shifting based on the CCF, we will incorporate this into our process, next.

We observe in Figure 12*.12* that the strongest correlation between realdpi and realinv is at lag 0, but there are at least two other similarly correlated lags at x=-27 and x=-37 in the plot. As we saw in the ARIMAX section, we can include multiple shifted versions of the same variables as new variables to improve the predictive power of the model. This would enable us to take advantage of multiple correlations. However, for the purpose of model demonstration, we will not include that as the output from the VAR summary can become large. Also, as we mentioned, including too many lags of the same variable can result in overfitting. It is up to the practitioner to ultimately decide how many lags to use. This must be done by assessing model fit and bias/variance trade-offs. The function code given here is also in Chapter 10*, Introduction to* Time Series:

# code imported from chapter 10
def plot_ccf(data_a, data_b, lag_lookback, percentile, ax, title=None):
n = len(data_a)
ccf = correlate(data_a - np.mean(data_a), data_b - np.mean(data_b), method='direct') / (np.std(data_a) * np.std(data_b) * n)
_min = (len(ccf)-1)//2 - lag_lookback
_max = (len(ccf)-1)//2 + (lag_lookback-1)
zscore_vals={90:1.645,
95:1.96,
99:2.576}
markers, stems, baseline = ax.stem(np.arange(-lag_lookback,(lag_lookback-1)), ccf[_min:_max], markerfmt='o', use_line_collection = True)
z_score_95pct = zscore_vals.get(percentile)/np.sqrt(n) #1.645 for 90%, 1.96 for 95%, and 2.576 for 99%
ax.set_title(title)
ax.set_xlabel('Lag')
ax.set_ylabel('Correlation')
ax.axhline(y=-z_score_95pct, color='b', ls='--')# Z-statistic for 95% CL LL
ax.axhline(y=z_score_95pct, color='b', ls='--')# Z-statistic for 95% CL UL
ax.axvline(x=0, color='black', ls='-');
plot = plot_ccf(data_a=data_1d['realdpi'], data_b=data_1d['realinv'], lag_lookback=50, percentile=95)

Figure 12.12 – Cross-correlation for realdpi and realinv

In Figure 12*.13*, we can see realcons is a leading indicator for realinv with a positive correlation. This means an increase in consumption results in an increase in investment. Nonetheless, we could still use a downshifted version of realinv to predict realcons —if this were our objective—since both variables are expected to continue indefinitely:

plot = plot_ccf(data_a=data_1d['realcons'], data_b=data_1d['realinv'], lag_lookback=50, percentile=95)

Figure 12.13 – Cross-correlation for realcons and realinv

To address the one-lag lead realcons has on realinv, let us shift realcons forward one index so that the strongest correlation is at lag 0. This is not required for a VAR model but can be useful in scenarios where the most significant lag is much farther back in time and could result in including an unreasonably high order for our model to include the necessary variable relationships.

Note on shifting data

When shifting data, null values will be included in the dataset. Consequently, the dataset must be trimmed by the length of the shift. This may come at the cost of model performance, so it is worth assessing the need to shift by comparing model errors.

After applying a forward shift to realcons in the following code snippet and rerunning the CCF, we can see in Figure 12*.14* the variables’ strongest correlation is now at lag 0:

data_1d['realcons'] = data_1d['realcons'].shift(1)
data_1d = data_1d.iloc[1:]
plot = plot_ccf(data_a=data_1d['realcons'], data_b=data_1d['realinv'], lag_lookback=50, percentile=95)

Figure 12.14 – Cross-correlation for realinv and forward-shifted realcons

Next, we want to run a function to append possible values of p and q (AR(p) and MA(q)):

from statsmodels.tsa.statespace.varmax import VARMAX
import warnings
warnings.simplefilter('error')
results_aic=[]
x_axis_list=[]
for p in range(1,6):
for q in range(0,6):
try:
model = VARMAX(data_1d,
order=(p,q),
trend='c',
enforce_stationarity=True,
enforce_invertibility=True)
results = model.fit()
results_aic.append(results.aic)
# x_axis_list.append(p,q,results.aic)
print('(p,q): ({},{}), AIC: {}'.format(p,q,results.aic))
except Exception as e:
# print('(p,q): ({},{}), error: {}'.format(p,q,e))
Pass

Here we can see the AIC error for VAR(1,0) and VAR(2,0) models:

(p,q): (1,0), ``AIC: 6092.740258665657

(p,q): (2,0), ``AIC: 6050.444583720871

We have two possible models through the AIC selection method. First, we built a model with p=2 and q=0, but after running, we observed that of seven coefficients predicting for realinv, only two were significant (even at the 0.10 level of significance), which is not good. After rerunning using a selection of p=1 and q=0, two of the four coefficients were found significant at the 0.05 level of significance and all at the 0.10 level of significance. Therefore, we can conclude the VAR(1,0) model is much better for predicting realinv.

We will skip the model validation steps we walked through in the last chapter as the process would be the same here. What we will do here is re-order the columns so that when we run the get_prediction() function, the results are for the first column. The model will stay the same since all variables are used to predict all other variables. After re-indexing, we will run the VARMAX model with order (1,0) using once-differenced data, with realcons shifted up one, and predict realinv. For our model, we used AR(1) and MA(0). Note that we use trend='c' for constant as we removed trend when performing differencing; the trend argument is for trend determinism. Trend differencing should be handled outside of the model since not all variables may have unit root trends. Handling trends outside of the model also helps us identify components such as seasonality or significance of the true autocorrelation structure following the removal of trend. It is worthwhile to note that seasonality is not addressed directly with the VAR (and VARMAX) model; indicator (dummy) variables for seasonality should be included.

Regarding model fit, we can refer to Chapter 11*, ARIMA Models,* for information on Ljung-Box, Jarque-Bera, heteroskedasticity, skew, and kurtosis values, so will not repeat that here. The order of values corresponds to the order of variables listed in the Dep. Variable list, shown next. Each model variable has listed the coefficients of the other variables’ terms used for predicting each variable. For example, we can observe in Results for equation realcons that realinv does not contribute much predictive capability to realcons, but realdpi does. We can also observe that realcons is significant for predicting realinv. We can also see based on the p-value and confidence interval in the error covariance matrix (ECM) that there is not much cross-covariance between the residuals of realinv and realdpi. We can expect to see larger coefficient values if we have variance in one feature explained by variance in the other:

model = VARMAX(data_1d.reindex(columns=['realinv','realcons','realdpi']), order=(1,0), trend='c',
enforce_stationarity=True,enforce_invertibility=True)
results = model.fit()
print(results.summary())

Figure 12.15 – VAR(1) model output

It is important to note that the prediction for the VAR model is actually quite stable compared to the long-running historical performance. The reason we see such extreme differences at the end of the forecast is that this time period corresponds to the Great Recession, which lasted from 2007 to 2009. The last five points in our test forecast correspond to the last two quarters of 2008 and the first three quarters of 2009:

df_pred = results.get_prediction(start=195, end=200).summary_frame(alpha=0.05)
fig, ax = plt.subplots(1,1,figsize=(20,5))
ax.plot(data_1d['realinv'], 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 VAR(1)')

Figure 12.16 – Test forecast for VARMAX with p=1

We can compare our forecast (mean) to actuals (realinv) for the investment variable, as follows:

pd.concat([df_pred,data_1d['realinv'].iloc[195:]], axis=1)

Here in Figure 12*.17*, we can see the VAR (from the VARMAX function) model test forecast:

meanmean_semean_ci_lowermean_ci_upperrealinv
196-12.434840.79603-92.393567.52398-56.368
197-6.2615440.79603-86.220373.69722-35.825
198-33.540640.79603-113.49946.41821-133.032
199-53.648140.79603-133.60726.31066-299.167
200-81.51440.79603-161.473-1.55526-101.816
201-10.103940.79603-90.062769.8548329.72

Figure 12.17 – VAR(1) model test forecast

We can observe that because this is a model with an autoregressive order p=1, the forecast tends very quickly toward the mean. Including a higher order would likely result in more model variance, which we could see as a more confident, yet risky forecast. The multivariate AR(1) model produces more bias, which we can observe in Figure 12*.18* as the tendency to the mean we mentioned. We can run the following code to generate the data and plot for the forecast:

df_forecast = results.get_prediction(start=201, end=207).summary_frame(alpha=0.05)
forecast = np.hstack([np.repeat(np.nan, len(data_1d)+1), df_forecast['mean']])
fig, ax = plt.subplots(1,1,figsize=(20,5))
ax.plot(data_1d['realinv'], marker='o', markersize=5)
ax.plot(forecast, marker='o', markersize=4)
ax.plot(df_forecast['mean_ci_lower'], color='g')
ax.plot(df_forecast['mean_ci_upper'], color='g')
ax.fill_between(df_forecast.index, df_forecast['mean_ci_lower'], df_forecast['mean_ci_upper'], color='g', alpha=0.1)
ax.set_title('Forecast for VAR(1)');

Figure 12.18 – VAR(1) model forecast, h=7

Here, we can see the forecasted points and the confidence interval for the forecast:

df_forecast
meanmean_semean_ci_lowermean_ci_upper
202-16.344240.79603-96.302963.6146
203-10.957143.69828-96.604174.68998
204-3.2466844.4028-90.274683.7812
2051.30149544.56735-86.048988.65189
2063.57661944.60344-83.844590.99775
2074.65097344.61108-82.785192.08709
2085.14708544.61268-82.292292.58633

Figure 12.19 – VAR(1) model output data

Note that our results are based on the differenced data. This model tells us the level of statistical significance between variables regarding their respective signals but does not give us forecast values in terms of the original data. To reverse differenced data, we need to estimate a constant of integration and then reverse-difference the data according to that constant or use a different transformation method that allows us to back-transform, such as a logarithmic transformation that can be exponentiated to reverse. Often, the VAR model is used for identifying potential causation between variables identified as highly correlated in a cross-correlation analysis as well as in economic shock analysis.

It can be argued that depending on the level of detail needed in the forecast, differencing and shifting of variables may not be required. However, because this is a fully endogenous model with no exogenous variables, it is important that if we apply differencing to any variables, we must also apply differencing to all variables containing non-stationary behavior. With respect to shifting, it may be more useful to simply apply a higher autoregressive lag order than to apply a shift; the drawback of shifting is we lose samples early on in the process. However, the drawback of using a higher lag order is the inclusion of more variables in the time dimension, which can increase the likelihood of overfitting. Logically, as more variables are included in the model, we must also increase sample size. As with any model, we must apply rigorous cross-validation to ensure performance stability and minimize risk.

In this chapter, we provided an overview of multivariate time-series and how they differ from the univariate case. We then covered the math and intuition behind two popular approaches to solving problems using multivariate time-series models—ARIMAX and the VAR model framework. We walked through examples for each model using a step-by-step approach. This chapter concludes our discussions on time-series analysis and forecasting. At this point, you should be able to identify and assess the statistical properties of time series, transform them as needed, and construct models that are useful for fitting and forecasting both univariate and multivariate cases.

In the next chapter, we will begin our discussion on survival analysis with an introduction to time-to-event (TTE) variables.

[1] Liang, X., Zou, T., Guo, B., Li, S., Zhang, H., Zhang, S., Huang, H. and Chen, S. X. (2015). Assessing Beijing’s PM2.5 pollution: severity, weather impact, APEC and winter heating. Proceedings of the Royal Society A, 471, 20150257.

[2] Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California, School of Information and Computer Science.