Skip to main content
In this example, we’ll forecast the volatility of the S&P 500 and several publicly traded companies using GARCH and ARCH models
Prerequisites This tutorial assumes basic familiarity with StatsForecast. For a minimal example visit the Quick Start

Introduction

The Generalized Autoregressive Conditional Heteroskedasticity (GARCH) model is used for time series that exhibit non-constant volatility over time. Here volatility refers to the conditional standard deviation. The GARCH(p,q) model is given by where vtv_t is independent and identically distributed with zero mean and unit variance, and σt\sigma_t evolves according to The coefficients in the equation above must satisfy the following conditions:
  1. w>0w>0, αi0\alpha_i \geq 0 for all ii, and βj0\beta_j \geq 0 for all jj
  2. k=1max(p,q)αk+βk<1\sum_{k=1}^{max(p,q)} \alpha_k + \beta_k < 1. Here it is assumed that αi=0\alpha_i=0 for i>pi>p and βj=0\beta_j=0 for j>qj>q.
A particular case of the GARCH model is the ARCH model, in which q=0q=0. Both models are commonly used in finance to model the volatility of stock prices, exchange rates, interest rates, and other financial instruments. They’re also used in risk management to estimate the probability of large variations in the price of financial assets. By the end of this tutorial, you’ll have a good understanding of how to implement a GARCH or an ARCH model in StatsForecast and how they can be used to analyze and predict financial time series data. Outline:
  1. Install libraries
  2. Load and explore the data
  3. Train models
  4. Perform time series cross-validation
  5. Evaluate results
  6. Forecast volatility
Tip You can use Colab to run this Notebook interactively Open In Colab

Install libraries

We assume that you have StatsForecast already installed. If not, check this guide for instructions on how to install StatsForecast Install the necessary packages using pip install statsforecast

Load and explore the data

In this tutorial, we’ll use the last 5 years of prices from the S&P 500 and several publicly traded companies. The data can be downloaded from Yahoo! Finance using yfinance. To install it, use pip install yfinance.
We’ll also need pandas to deal with the dataframes.
The data downloaded includes different prices. We’ll use the adjusted closing price, which is the closing price after accounting for any corporate actions like stock splits or dividend distributions. It is also the price that is used to examine historical returns. Notice that the dataframe that yfinance returns has a MultiIndex, so we need to select both the adjusted price and the tickers.
The input to StatsForecast is a dataframe in long format with three columns: unique_id, ds and y:
  • unique_id: (string, int or category) A unique identifier for the series.
  • ds: (datestamp or int) A datestamp in format YYYY-MM-DD or YYYY-MM-DD HH:MM:SS or an integer indexing time.
  • y: (numeric) The measurement we wish to forecast.
Hence, we need to reshape the data. We’ll do this by creating a new dataframe called price.
We can plot this series using the plot method of the StatsForecast class.
With the prices, we can compute the logarithmic returns of the S&P 500 and the publicly traded companies. This is the variable we’re interested in since it’s likely to work well with the GARCH framework. The logarithmic return is given by returnt=log(pricetpricet1)return_t = log \big( \frac{price_t}{price_{t-1}} \big) We’ll compute the returns on the price dataframe and then we’ll create a return dataframe with StatsForecast’s format. To do this, we’ll need numpy.
Warning If the order of the data is very small (say <1e5<1e-5), scipy.optimize.minimize might not terminate successfully. In this case, rescale the data and then generate the GARCH or ARCH model.
From this plot, we can see that the returns seem suited for the GARCH framework, since large shocks tend to be followed by other large shocks. This doesn’t mean that after every large shock we should expect another one; merely that the probability of a large variance is greater than the probability of a small one.

Train models

We first need to import the GARCH and the ARCH models from statsforecast.models, and then we need to fit them by instantiating a new StatsForecast object. Notice that we’ll be using different values of pp and qq. In the next section, we’ll determine which ones produce the most accurate model using cross-validation. We’ll also import the Naive model since we’ll use it as a baseline.
To instantiate a new StatsForecast object, we need the following parameters:
  • df: The dataframe with the training data.
  • models: The list of models defined in the previous step.
  • freq: A string indicating the frequency of the data. Here we’ll use MS, which correspond to the start of the month. You can see the list of panda’s available frequencies here.
  • n_jobs: An integer that indicates the number of jobs used in parallel processing. Use -1 to select all cores.

Perform time series cross-validation

Time series cross-validation is a method for evaluating how a model would have performed in the past. It works by defining a sliding window across the historical data and predicting the period following it. Here we’ll use StatsForecast’s cross-validation method to determine the most accurate model for the S&P 500 and the companies selected. This method takes the following arguments:
  • df: The dataframe with the training data.
  • h (int): represents the h steps into the future that will be forecasted.
  • step_size (int): step size between each window, meaning how often do you want to run the forecasting process.
  • n_windows (int): number of windows used for cross-validation, meaning the number of forecasting processes in the past you want to evaluate.
For this particular example, we’ll use 4 windows of 3 months, or all the quarters in a year.
The cv_df object is a dataframe with the following columns:
  • unique_id: series identifier.
  • ds: datestamp or temporal index
  • cutoff: the last datestamp or temporal index for the n_windows.
  • y: true value
  • "model": columns with the model’s name and fitted value.
A tutorial on cross-validation can be found here

Evaluate results

To compute the accuracy of the forecasts, we’ll use the mean average error (mae), which is the sum of the absolute errors divided by the number of forecasts.
The MAE needs to be computed for every window and then it needs to be averaged across all of them. To do this, we’ll create the following function.
Hence, the most accurate model to describe the logarithmic returns of Apple’s stock is a GARCH(2, 1), for Amazon’s stock is a GARCH(2,2), and so on.

Forecast volatility

We can now generate a forecast for the next quarter. To do this, we’ll use the forecast method, which requires the following arguments:
  • h: (int) The forecasting horizon.
  • level: (list[float]) The confidence levels of the prediction intervals
  • fitted : (bool = False) Returns insample predictions.
With the results of the previous section, we can choose the best model for the S&P 500 and the companies selected. Some of the plots are shown below. Notice that we’re using some additional arguments in the plot method:
  • level: (list[int]) The confidence levels for the prediction intervals (this was already defined).
  • unique_ids: (list[str, int or category]) The ids to plot.
  • models: (list(str)). The model to plot. In this case, is the model selected by cross-validation.

References