Get Started

Forecasting weekly data

With weekly data, it is difficult to handle seasonality using ETS or ARIMA models as the seasonal length is too large (approximately 52). Instead, you can use harmonic regression which uses sines and cosines to model the seasonality.

The fourier() function makes it easy to generate the required harmonics. The higher the order (\(K\)), the more "wiggly" the seasonal pattern is allowed to be. With \(K=1\), it is a simple sine curve. You can select the value of \(K\) by minimizing the AICc value. As you saw in the video, fourier() takes in a required time series, required number of Fourier terms to generate, and optional number of rows it needs to forecast:

> # fourier(x, K, h = NULL)

> fit <- auto.arima(cafe, xreg = fourier(cafe, K = 6),
                    seasonal = FALSE, lambda = 0)
> fit %>%
    forecast(xreg = fourier(cafe, K = 6, h = 24)) %>%
    autoplot() + ylim(1.6, 5.1)

The pre-loaded gasoline data comprises weekly data on US finished motor gasoline products. In this exercise, you will fit a harmonic regression to this data set and forecast the next 3 years.

This is a part of the course

“Forecasting in R”

View Course

Exercise instructions

  • Set up an xreg matrix called harmonics using the fourier() method on gasoline with order \(K=13\) which has been chosen to minimize the AICc.
  • Fit a dynamic regression model to fit. Set xreg equal to harmonics and seasonal to FALSE because seasonality is handled by the regressors.
  • Set up a new xreg matrix called newharmonics in a similar fashion, and then compute forecasts for the next three years as fc.
  • Finally, plot the forecasts fc.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Set up harmonic regressors of order 13
harmonics <- fourier(___, K = ___)

# Fit regression model with ARIMA errors
fit <- auto.arima(___, xreg = ___, seasonal = ___)

# Forecasts next 3 years
newharmonics <- fourier(___, K = ___, h = ___)
fc <- forecast(___, xreg = ___)

# Plot forecasts fc
___
Edit and Run Code