{ "cells": [ { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "# Forecasting with Exogenous Regressors\n", "\n", "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\n", "\n", "$$ Y_t = \\phi_0 + \\phi_1 Y_{t-1} + \\beta_0 X_{0,t} + \\beta_1 X_{1,t} + \\epsilon_t. $$\n", "\n", "The $h$-step forecast, $E_{T}[Y_{t+h}]$, depends on the conditional expectation of $X_{0,T+h}$ and $X_{1,T+h}$,\n", "\n", "$$ 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}] $$\n", "\n", "where $E_{T}[Y_{T+h-1}]$ has been recursively computed.\n", "\n", "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.\n", "\n", "There are two general purpose data structures that can be used for any number of exogenous variables and any number steps ahead:\n", "\n", "* `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.\n", "* `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.\n", "\n", "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.\n", "\n", "In the special case where a model contains a single regressor _and_ the horizon is 1, then a 1-d array or pandas Series can be used." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import pandas as pd\n", "import seaborn\n", "\n", "seaborn.set_style(\"darkgrid\")\n", "plt.rc(\"figure\", figsize=(16, 6))\n", "plt.rc(\"savefig\", dpi=90)\n", "plt.rc(\"font\", family=\"sans-serif\")\n", "plt.rc(\"font\", size=14)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "## Simulating data\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "from arch.univariate import ARX, GARCH, ZeroMean, arch_model\n", "\n", "burn = 250\n", "\n", "x_mod = ARX(None, lags=1)\n", "x0 = x_mod.simulate([1, 0.8, 1], nobs=1000 + burn).data\n", "x1 = x_mod.simulate([2.5, 0.5, 1], nobs=1000 + burn).data\n", "\n", "resid_mod = ZeroMean(volatility=GARCH())\n", "resids = resid_mod.simulate([0.1, 0.1, 0.8], nobs=1000 + burn).data\n", "\n", "phi1 = 0.7\n", "phi0 = 3\n", "y = 10 + resids.copy()\n", "for i in range(1, y.shape[0]):\n", " y[i] = phi0 + phi1 * y[i - 1] + 2 * x0[i] - 2 * x1[i] + resids[i]\n", "\n", "x0 = x0.iloc[-1000:]\n", "x1 = x1.iloc[-1000:]\n", "y = y.iloc[-1000:]\n", "y.index = x0.index = x1.index = np.arange(1000)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "## Plotting the data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "ax = pd.DataFrame({\"ARX\": y}).plot(legend=False)\n", "ax.legend(frameon=False)\n", "_ = ax.set_xlim(0, 999)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "## Forecasting the X values\n", "\n", "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`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "x0_oos = np.empty((1000, 10))\n", "x1_oos = np.empty((1000, 10))\n", "for i in range(10):\n", " if i == 0:\n", " last = x0\n", " else:\n", " last = x0_oos[:, i - 1]\n", " x0_oos[:, i] = 1 + 0.8 * last\n", " if i == 0:\n", " last = x1\n", " else:\n", " last = x1_oos[:, i - 1]\n", " x1_oos[:, i] = 2.5 + 0.5 * last\n", "\n", "x1_oos[-1]" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "## Fitting the model\n", "\n", "Next, the model is fit. The parameters are precisely estimated." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "exog = pd.DataFrame({\"x0\": x0, \"x1\": x1})\n", "mod = arch_model(y, x=exog, mean=\"ARX\", lags=1)\n", "res = mod.fit(disp=\"off\")\n", "print(res.summary())" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "## Using a `dict`\n", "\n", "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.\n", "\n", "### Using `DataFrame`\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "exog_fcast = {\"x0\": x0_oos[-1:], \"x1\": x1_oos[-1:]}\n", "forecasts = res.forecast(horizon=10, x=exog_fcast)\n", "forecasts.mean.T.plot()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using an `array`\n", "\n", "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)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "exog_fcast = np.array([x0_oos[-1:], x1_oos[-1:]])\n", "print(f\"The shape is {exog_fcast.shape}\")\n", "array_forecasts = res.forecast(horizon=10, x=exog_fcast)\n", "print(array_forecasts.mean - forecasts.mean)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Producing multiple forecasts\n", "\n", "`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.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "res = mod.fit(disp=\"off\", last_obs=500)\n", "exog_fcast = {\"x0\": x0_oos[-500:], \"x1\": x1_oos[-500:]}\n", "multi_forecasts = res.forecast(start=500, horizon=10, x=exog_fcast)\n", "multi_forecasts.mean.tail(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The plot of the final 5 forecast paths shows the the mean reversion of the process." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "_ = multi_forecasts.mean.tail().T.plot()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "exog_fcast = np.array([x0_oos[-500:], x1_oos[-500:]])\n", "print(exog_fcast.shape)\n", "array_multi_forecasts = res.forecast(start=500, horizon=10, x=exog_fcast)\n", "np.max(np.abs(array_multi_forecasts.mean - multi_forecasts.mean))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `x` input array sizes\n", "\n", "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. \n", "\n", "
\n", "

WARNING

\n", " 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.\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "exog_fcast = np.array([x0_oos, x1_oos])\n", "print(exog_fcast.shape)\n", "array_multi_forecasts = res.forecast(start=500, horizon=10, x=exog_fcast)\n", "np.max(np.abs(array_multi_forecasts.mean - multi_forecasts.mean))" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "## Special Cases with a single `x` variable\n", "\n", "When a model consists of a single exogenous regressor, then `x` can be a 1-d or 2-d array (or `Series` or `DataFrame`)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "mod = arch_model(y, x=exog.iloc[:, :1], mean=\"ARX\", lags=1)\n", "res = mod.fit(disp=\"off\")\n", "print(res.summary())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These two examples show that both formats can be used." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "forecast_1d = res.forecast(horizon=10, x=x0_oos[-1])\n", "forecast_2d = res.forecast(horizon=10, x=x0_oos[-1:])\n", "print(forecast_1d.mean - forecast_2d.mean)\n", "\n", "## Simulation-forecasting\n", "\n", "mod = arch_model(y, x=exog, mean=\"ARX\", lags=1, power=1.0)\n", "res = mod.fit(disp=\"off\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simulation\n", "\n", "`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. \n", "\n", "### Static out-of-sample `x`\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "x = {\"x0\": x0_oos[-1], \"x1\": x1_oos[-1]}\n", "sim_fixedx = res.forecast(horizon=10, x=x, method=\"simulation\", simulations=100)\n", "sim_fixedx.simulations.values.std(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simulating the out-of-sample `x`\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "from numpy.random import RandomState\n", "\n", "\n", "def sim_ar1(params: np.ndarray, initial: float, horizon: int, rng: RandomState):\n", " out = np.zeros(horizon)\n", " shocks = rng.standard_normal(horizon)\n", " out[0] = params[0] + params[1] * initial + shocks[0]\n", " for i in range(1, horizon):\n", " out[i] = params[0] + params[1] * out[i - 1] + shocks[i]\n", " return out\n", "\n", "\n", "simulations = []\n", "rng = RandomState(20210301)\n", "for i in range(100):\n", " x0_sim = sim_ar1(np.array([1, 0.8]), x0.iloc[-1], 10, rng)\n", " x1_sim = sim_ar1(np.array([2.5, 0.5]), x1.iloc[-1], 10, rng)\n", " x = {\"x0\": x0_sim, \"x1\": x1_sim}\n", " fcast = res.forecast(horizon=10, x=x, method=\"simulation\", simulations=1)\n", " simulations.append(fcast.simulations.values)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "joined = np.concatenate(simulations, 1)\n", "joined.std(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditional Mean Alignment vs. Forecast Alignment\n", "\n", "When fitting a model with exogenous variables, the data are aligned so that the values in ``x[j]`` are used to compute the conditional mean of ``y[j]``. For example, in the case of an AR(1)-X, the model is \n", "\n", "$$\n", "Y_t = \\phi_0 + \\phi_1 Y_{t-1} + \\beta X_{t} + \\epsilon_t. \n", "$$\n", "\n", "We can recover the conditional mean by subtracting the residuals from the original data. When we do this we see that the conditional mean of observation 0 is missing since we need one lag of $Y$ to fit the model.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mod = arch_model(y, x=exog, mean=\"ARX\", lags=1)\n", "res = mod.fit(disp=\"off\")\n", "y - res.resid" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conditional Mean uses target alignment\n", "When modeling the conditional mean in an AR-X, HAR-X, or LS model, the $X$ data is target-aligned. This requires that when modeling the mean of ``y[t]``, the correct values of $X$ must appear in ``x[t]``. Mathematically, the $X$ matrix used when estimating a model should have the structure (using the Python indexing convention of a T-element data set having indices 0, 1, ..., T-1):\n", "\n", "$$\n", "\\left[\\begin{array}{c}\n", "X_{0}\\\\\n", "X_{1}\\\\\n", "\\vdots\\\\\n", "X_{T-1}\n", "\\end{array}\\right]\n", "$$\n", "\n", "\n", "\n", "\n", "### ``forecast`` uses origin alignment\n", "\n", "Forecasting with $X$ values aligns them differently. When producing a 1-step-ahead forecast for $Y_{t+1}$ using information available at time $t$, the $X$ values used for this forecast must appear in for ``t``. This is needed since when once wants to produce true out-of-sample forecasts (see below), it must be the case that the final row of ``x`` passed ``forecast`` must all occur after the final time stamp of the most recent $Y$ value. Mathematically, the $X$ matrix used in forecasting should have the following structure (using Python indexing convention so that a $T$ observation dataset will have indices 0, 1, ..., T-1).\n", "\n", "$$\n", "\\left[\\begin{array}{cccc}\n", "E\\left[X_{1}|\\mathcal{F}_0\\right] & E\\left[X_{2}|\\mathcal{F}_0\\right] & \\ldots & E\\left[X_{h|\\mathcal{F}_0}\\right]\\\\\n", "E\\left[X_{2}|\\mathcal{F}_1\\right] & E\\left[X_{3}|\\mathcal{F}_0\\right] & \\ldots & E\\left[X_{h+1}|\\mathcal{F}_1\\right]\\\\\n", "\\vdots & \\vdots & \\vdots & \\vdots\\\\\n", "E\\left[X_{T}|\\mathcal{F}_{T-1}\\right] & E\\left[X_{T+1}|\\mathcal{F}_{T-1}\\right] & \\ldots & E\\left[X_{T+h-1}|\\mathcal{F}_{T-1}\\right]\n", "\\end{array}\\right]\n", "$$\n", "\n", "where $|\\mathcal{F}_{s}$ is the time-$s$ information set.\n", "\n", "If you use the same ``x`` value in the model when forecasting, you will see different values due to this alignment difference. Naively using the same ``x`` values ie equivalent to setting\n", "\n", "$$ E\\left[X_{s}|\\mathcal{F}_{s-1} \\right] = X_{s-1} $$\n", "\n", "In general this would not be correct when forecasting, and will always produce forecasts that differ from the conditional mean. In order to recover the conditional mean using the forecast function, it is necessary to ``shift`` the $X$ values by -1, so that once shifted, the ``x`` values will have the relationship\n", "\n", "$$ E\\left[X_{s}|\\mathcal{F}_{s-1} \\right] = X_{s} .$$\n", "\n", "Here we shift the $X$ data by ``-1`` so ``x[s]`` is treated as being in the information set for ``y[s-1]``. Also, note that the final forecast is ``NaN``. Conceptually this must be the case because the value of $X$ at 999 should be ahead of 999 (i.e., at observation 1,000), and we do not have this value. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "exog_dict = {col: exog[[col]].shift(-1) for col in exog}\n", "fcast = res.forecast(horizon=1, x=exog_dict, start=0)\n", "fcast.mean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### (Nearly) out-of-sample forecasts\n", "\n", "These \"in-sample\" forecasts are not really forecasts at all but are just fitted values with a different alignment. If you want real (nearly) out-of-sample forecasts$\\dagger$, it is necessary to replace the actual values of $X$ with their conditional expectation. This can be done by taking the fitted values from AR(1) models of the $X$ variables. \n", "\n", "$\\dagger$ These are not true out-of-sample since the parameters were estimated using data from that same range of indices where these forecasts target. True out-of-sample requires both using forecast $X$ values and parameters estimated without the period being forecasted." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "res0 = ARX(exog[\"x0\"], lags=1).fit()\n", "res1 = ARX(exog[\"x1\"], lags=1).fit()\n", "forecast_x = pd.concat(\n", " [res0.forecast(start=0).mean, res1.forecast(start=0).mean], axis=1\n", ")\n", "forecast_x.columns = [\"x0f\", \"x1f\"]\n", "in_samp_forcast_exog = {\"x0\": forecast_x[[\"x0f\"]], \"x1\": forecast_x[[\"x1f\"]].shift(-1)}\n", "fcast = res.forecast(horizon=1, x=in_samp_forcast_exog, start=0)\n", "fcast.mean" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### True out-of-sample forecasts\n", "\n", "In order to make a true out-of-sample prediction, we need the expected values of ``X`` from the end of the data we have. These can be constructed by forecasting the two $X$ variables and then passing these values as ``x`` to ``forecast``." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mod = arch_model(y, x=exog, mean=\"ARX\", lags=1)\n", "res = mod.fit(disp=\"off\")\n", "\n", "actual_x_oos = {\n", " \"x0\": res0.forecast(horizon=10).mean,\n", " \"x1\": res1.forecast(horizon=10).mean,\n", "}\n", "fcasts = res.forecast(horizon=10, x=actual_x_oos)\n", "fcasts.mean" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 4 }