# Forecasting with Exogenous Regressors¶

This notebook provides examples of the accepted data structures for passing the expected value of exogenous variables when these are included in the mean. For example, consider an AR(1) with 2 exogenous variables. The mean dynamics are

$Y_t = \phi_0 + \phi_1 Y_{t-1} + \beta_0 X_{0,t} + \beta_1 X_{1,t} + \epsilon_t.$

The $$h$$-step forecast, $$E_{T}[Y_{t+h}]$$, depends on the conditional expectation of $$X_{0,T+h}$$ and $$X_{1,T+h}$$,

$E_{T}[Y_{T+h}] = \phi_0 + \phi_1 E_{T}[Y_{T+h-1}] + \beta_0 E_{T}[X_{0,T+h}] +\beta_1 E_{T}[X_{1,T+h}]$

where $$E_{T}[Y_{T+h-1}]$$ has been recursively computed.

In order to construct forecasts up to some horizon $$h$$, it is necessary to pass $$2\times h$$ values ($$h$$ for each series). If using the features of forecast that allow many forecast to be specified, it necessary to supply $$n \times 2 \times h$$ values.

There are two general purpose data structures that can be used for any number of exogenous variables and any number steps ahead:

• dict - The values can be pass using a dict where the keys are the variable names and the values are 2-dimensional arrays. This is the most natural generalization of a pandas DataFrame to 3-dimensions.

• array - The vales can alternatively be passed as a 3-d NumPy array where dimension 0 tracks the regressor index, dimension 1 is the time period and dimension 2 is the horizon.

When a model contains a single exogenous regressor it is possible to use a 2-d array or DataFrame where dim0 tracks the time period where the forecast is generated and dimension 1 tracks the horizon.

In the special case where a model contains a single regressor and the horizon is 1, then a 1-d array of pandas Series can be used.

[1]:

# initial setup
%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn

seaborn.set_style("darkgrid")
plt.rc("figure", figsize=(16, 6))
plt.rc("savefig", dpi=90)
plt.rc("font", family="sans-serif")
plt.rc("font", size=14)


## Simulating data¶

Two $$X$$ variables are simulated and are assumed to follow independent AR(1) processes. The data is then assumed to follow an ARX(1) with 2 exogenous regressors and GARCH(1,1) errors.

[2]:

from arch.univariate import ARX, GARCH, ZeroMean, arch_model

burn = 250

x_mod = ARX(None, lags=1)
x0 = x_mod.simulate([1, 0.8, 1], nobs=1000 + burn).data
x1 = x_mod.simulate([2.5, 0.5, 1], nobs=1000 + burn).data

resid_mod = ZeroMean(volatility=GARCH())
resids = resid_mod.simulate([0.1, 0.1, 0.8], nobs=1000 + burn).data

phi1 = 0.7
phi0 = 3
y = 10 + resids.copy()
for i in range(1, y.shape[0]):
y[i] = phi0 + phi1 * y[i - 1] + 2 * x0[i] - 2 * x1[i] + resids[i]

x0 = x0.iloc[-1000:]
x1 = x1.iloc[-1000:]
y = y.iloc[-1000:]
y.index = x0.index = x1.index = np.arange(1000)


## Plotting the data¶

[3]:

ax = pd.DataFrame({"ARX": y}).plot(legend=False)
ax.legend(frameon=False)
_ = ax.set_xlim(0, 999)


## Forecasting the X values¶

The forecasts of $$Y$$ depend on forecasts of $$X_0$$ and $$X_1$$. Both of these follow simple AR(1), and so we can construct the forecasts for all time horizons. Note that the value in position [i,j] is the time-i forecast for horizon j+1.

[4]:

x0_oos = np.empty((1000, 10))
x1_oos = np.empty((1000, 10))
for i in range(10):
if i == 0:
last = x0
else:
last = x0_oos[:, i - 1]
x0_oos[:, i] = 1 + 0.8 * last
if i == 0:
last = x1
else:
last = x1_oos[:, i - 1]
x1_oos[:, i] = 2.5 + 0.5 * last

x1_oos[-1]

[4]:

array([5.65805541, 5.3290277 , 5.16451385, 5.08225693, 5.04112846,
5.02056423, 5.01028212, 5.00514106, 5.00257053, 5.00128526])


## Fitting the model¶

Next, the most is fit. The parameters are accurately estimated.

[5]:

exog = pd.DataFrame({"x0": x0, "x1": x1})
mod = arch_model(y, x=exog, mean="ARX", lags=1)
res = mod.fit(disp="off")
print(res.summary())

                          AR-X - GARCH Model Results
==============================================================================
Dep. Variable:                   data   R-squared:                       0.992
Mean Model:                      AR-X   Adj. R-squared:                  0.992
Vol Model:                      GARCH   Log-Likelihood:               -1391.04
Distribution:                  Normal   AIC:                           2796.08
Method:            Maximum Likelihood   BIC:                           2830.43
No. Observations:                  999
Date:                Tue, May 30 2023   Df Residuals:                      995
Time:                        10:55:41   Df Model:                            4
Mean Model
========================================================================
coef    std err          t      P>|t|  95.0% Conf. Int.
------------------------------------------------------------------------
Const          2.9447      0.151     19.443  3.308e-84 [  2.648,  3.242]
data[1]        0.6947  3.807e-03    182.482      0.000 [  0.687,  0.702]
x0             1.9813  2.175e-02     91.078      0.000 [  1.939,  2.024]
x1            -1.9620  2.564e-02    -76.519      0.000 [ -2.012, -1.912]
Volatility Model
==========================================================================
coef    std err          t      P>|t|    95.0% Conf. Int.
--------------------------------------------------------------------------
omega          0.0946  3.606e-02      2.622  8.733e-03 [2.389e-02,  0.165]
alpha[1]       0.0974  2.496e-02      3.903  9.516e-05 [4.849e-02,  0.146]
beta[1]        0.8083  5.059e-02     15.977  1.839e-57   [  0.709,  0.907]
==========================================================================

Covariance estimator: robust


## Using a dict¶

The first approach uses a dict to pass the two variables. The key consideration here is the the keys of the dictionary must exactly match the variable names (x0 and x1 here). The dictionary here contains only the final row of the forecast values since forecast will only make forecasts beginning from the final in-sample observation by default.

### Using DataFrame¶

While these examples make use of NumPy arrays, these can be DataFrames. This allows the index to be used to track the forecast origination point, which can be a helpful device.

[6]:

exog_fcast = {"x0": x0_oos[-1:], "x1": x1_oos[-1:]}
forecasts = res.forecast(horizon=10, x=exog_fcast)
forecasts.mean.T.plot()

[6]:

<Axes: >


## Using an array¶

An array can alternatively be used. This frees the restriction on matching the variable names although the order must match instead. The forecast values are 2 (variables) by 1 (forecast) by 10 (horizon).

[7]:

exog_fcast = np.array([x0_oos[-1:], x1_oos[-1:]])
print(f"The shape is {exog_fcast.shape}")
array_forecasts = res.forecast(horizon=10, x=exog_fcast)
print(array_forecasts.mean - forecasts.mean)

The shape is (2, 1, 10)
h.01  h.02  h.03  h.04  h.05  h.06  h.07  h.08  h.09  h.10
999   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0


## Producing multiple forecasts¶

forecast can produce multiple forecasts using the same fit model. Here the model is fit to the first 500 observations and then forecasting for the remaining values are produced. It must be the case that the x values passed for forecast have the same number of rows as the table of forecasts produced.

[8]:

res = mod.fit(disp="off", last_obs=500)
exog_fcast = {"x0": x0_oos[-500:], "x1": x1_oos[-500:]}
multi_forecasts = res.forecast(start=500, horizon=10, x=exog_fcast)
multi_forecasts.mean.tail(10)

[8]:

h.01 h.02 h.03 h.04 h.05 h.06 h.07 h.08 h.09 h.10
990 17.638678 19.057943 19.305712 18.876070 18.090794 17.153279 16.187233 15.263806 14.420245 13.672511
991 20.307394 20.095492 19.176459 18.008276 16.816890 15.707369 14.722133 13.871672 13.150830 12.547444
992 18.286380 16.896235 15.586099 14.454254 13.517502 12.759810 12.154606 11.674450 11.294780 10.994971
993 24.177049 22.846561 20.903832 18.944579 17.198290 15.728217 14.527010 13.561360 12.791967 12.181810
994 21.476395 19.945167 18.325031 16.830889 15.536242 14.450638 13.557059 12.829543 12.241130 11.767149
995 13.887372 11.827018 10.504285 9.701208 9.250338 9.029847 8.954356 8.965773 9.025626 9.109140
996 12.091224 10.738291 9.893515 9.402421 9.147641 9.044580 9.034509 9.077894 9.148903 9.231197
997 14.752402 14.165799 13.584948 13.038435 12.542245 12.103274 11.722401 11.396828 11.121754 10.891488
998 15.530046 14.262848 13.244627 12.449407 11.837882 11.371370 11.016716 10.747264 10.542302 10.386034
999 11.481761 10.462828 10.056773 9.917344 9.885242 9.890079 9.902827 9.913039 9.918147 9.918574

The plot of the final 5 forecast paths shows the the mean reversion of the process.

[9]:

_ = multi_forecasts.mean.tail().T.plot()


The previous example made use of dictionaries where each of the values was a 500 (number of forecasts) by 10 (horizon) array. The alternative format can be used where x is a 3-d array with shape 2 (variables) by 500 (forecasts) by 10 (horizon).

[10]:

exog_fcast = np.array([x0_oos[-500:], x1_oos[-500:]])
print(exog_fcast.shape)
array_multi_forecasts = res.forecast(start=500, horizon=10, x=exog_fcast)
np.max(np.abs(array_multi_forecasts.mean - multi_forecasts.mean))

(2, 500, 10)

[10]:

0.0


## x input array sizes¶

While the natural shape of the x data is the number of forecasts, it is also possible to pass an x that has the same shape as the y used to construct the model. The may simplify tracking the origin points of the forecast. Values are are not needed are ignored. In this example, the out-of-sample values are 2 by 1000 (original number of observations) by 10. Only the final 500 are used.

WARNING

Other sizes are not allowed. The size of the out-of-sample data must either match the original data size or the number of forecasts.

[11]:

exog_fcast = np.array([x0_oos, x1_oos])
print(exog_fcast.shape)
array_multi_forecasts = res.forecast(start=500, horizon=10, x=exog_fcast)
np.max(np.abs(array_multi_forecasts.mean - multi_forecasts.mean))

(2, 1000, 10)

[11]:

0.0


## Special Cases with a single x variable¶

When a model consists of a single exogenous regressor, then x can be a 1-d or 2-d array (or Series or DataFrame).

[12]:

mod = arch_model(y, x=exog.iloc[:, :1], mean="ARX", lags=1)
res = mod.fit(disp="off")
print(res.summary())

                          AR-X - GARCH Model Results
==============================================================================
Dep. Variable:                   data   R-squared:                       0.955
Mean Model:                      AR-X   Adj. R-squared:                  0.955
Vol Model:                      GARCH   Log-Likelihood:               -2280.96
Distribution:                  Normal   AIC:                           4573.92
Method:            Maximum Likelihood   BIC:                           4603.36
No. Observations:                  999
Date:                Tue, May 30 2023   Df Residuals:                      996
Time:                        10:55:42   Df Model:                            3
Mean Model
========================================================================
coef    std err          t      P>|t|  95.0% Conf. Int.
------------------------------------------------------------------------
Const         -6.4609      0.226    -28.561 2.064e-179 [ -6.904, -6.018]
data[1]        0.7695  8.995e-03     85.552      0.000 [  0.752,  0.787]
x0             1.7394  5.329e-02     32.643 1.021e-233 [  1.635,  1.844]
Volatility Model
=============================================================================
coef    std err          t      P>|t|       95.0% Conf. Int.
-----------------------------------------------------------------------------
omega          0.1073  7.460e-02      1.438      0.150   [-3.895e-02,  0.253]
alpha[1]   8.6689e-03  1.513e-02      0.573      0.567 [-2.099e-02,3.832e-02]
beta[1]        0.9717  2.616e-02     37.149 4.549e-302      [  0.920,  1.023]
=============================================================================

Covariance estimator: robust


These two examples show that both formats can be used.

[13]:

forecast_1d = res.forecast(horizon=10, x=x0_oos[-1])
forecast_2d = res.forecast(horizon=10, x=x0_oos[-1:])
print(forecast_1d.mean - forecast_2d.mean)

## Simulation-forecasting

mod = arch_model(y, x=exog, mean="ARX", lags=1, power=1.0)
res = mod.fit(disp="off")

     h.01  h.02  h.03  h.04  h.05  h.06  h.07  h.08  h.09  h.10
999   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0   0.0


## Simulation¶

forecast supports simulating paths. When forecasting a model with exogenous variables, the same value is used to in all mean paths. If you wish to also simulate the paths of the x variables, these need to generated and then passed inside a loop.

### Static out-of-sample x¶

This first example shows that variance of the paths when the same x values are used in the forecast. There is a sense the out-of-sample x are treated as deterministic.

[14]:

x = {"x0": x0_oos[-1], "x1": x1_oos[-1]}
sim_fixedx = res.forecast(horizon=10, x=x, method="simulation", simulations=100)
sim_fixedx.simulations.values.std(1)

[14]:

array([[1.04095499, 1.27798546, 1.30149937, 1.53498654, 1.60825322,
1.53831759, 1.55948399, 1.49811376, 1.74794163, 1.54496175]])


### Simulating the out-of-sample x¶

This example simulates distinct paths for the two exogenous variables and then simulates a single path. This is then repeated 100 times. We see that variance is much higher when we account for variation in the x data.

[15]:

from numpy.random import RandomState

def sim_ar1(params: np.ndarray, initial: float, horizon: int, rng: RandomState):
out = np.zeros(horizon)
shocks = rng.standard_normal(horizon)
out[0] = params[0] + params[1] * initial + shocks[0]
for i in range(1, horizon):
out[i] = params[0] + params[1] * out[i - 1] + shocks[i]
return out

simulations = []
rng = RandomState(20210301)
for i in range(100):
x0_sim = sim_ar1(np.array([1, 0.8]), x0.iloc[-1], 10, rng)
x1_sim = sim_ar1(np.array([2.5, 0.5]), x1.iloc[-1], 10, rng)
x = {"x0": x0_sim, "x1": x1_sim}
fcast = res.forecast(horizon=10, x=x, method="simulation", simulations=1)
simulations.append(fcast.simulations.values)


Finally the standard deviation is quite a bit larger. This is a most accurate value fo the long-run variance of the forecast residuals which should account for dynamics in the model and any exogenous regressors.

[16]:

joined = np.concatenate(simulations, 1)
joined.std(1)

[16]:

array([[2.95980851, 4.9043695 , 6.49587772, 7.50716786, 8.27211937,
8.71428305, 8.71321666, 8.67711577, 8.80764753, 9.17554847]])