gasoline |> stlf() |> autoplot()
In this final chapter, we address many practical issues that arise in forecasting, and discuss some possible solutions. Several of these sections are adapted from Hyndsight blog posts.
Weekly, daily and sub-daily data can be challenging for forecasting, although for different reasons.
Weekly data is difficult to work with because the seasonal period (the number of weeks in a year) is both large and non-integer. The average number of weeks in a year is 52.18. Most of the methods we have considered require the seasonal period to be an integer. Even if we approximate it by 52, most of the methods will not handle such a large seasonal period efficiently.
The simplest approach is to use an STL decomposition along with a non-seasonal method applied to the seasonally adjusted data (as discussed in Chapter 6). Here is an example using weekly data on US finished motor gasoline products supplied (in millions of barrels per day) from February 1991 to May 2005.
gasoline |> stlf() |> autoplot()
An alternative approach is to use a dynamic harmonic regression model, as discussed in Section 9.5. In the following example, the number of Fourier terms was selected by minimising the AICc. The order of the ARIMA model is also selected by minimising the AICc, although that is done within the auto.arima() function.
bestfit <- list(aicc = Inf)
for (K in seq(25)) {
fit <- auto.arima(gasoline, xreg = fourier(gasoline, K = K), seasonal = FALSE)
if (fit[["aicc"]] < bestfit[["aicc"]]) {
bestfit <- fit
bestK <- K
}
}fc <- forecast(bestfit, xreg = fourier(gasoline, K = bestK, h = 104))
autoplot(fc)
The fitted model has 18 pairs of Fourier terms and can be written as y_t = bt + \sum_{j=1}^{18} \left[ \alpha_j\sin\left( \frac{2\pi j t}{52.18} \right) + \beta_j\cos\left( \frac{2\pi j t}{52.18} \right) \right] + \eta_t where \eta_t is an ARIMA(4,1,1) process. Because n_t is non-stationary, the model is actually estimated on the differences of the variables on both sides of this equation. There are 36 parameters to capture the seasonality which is rather a lot, but apparently required according to the AICc selection. The total number of degrees of freedom is 42 (the other six coming from the 4 AR parameters, 1 MA parameter, and the drift parameter).
A third approach is the TBATS model introduced in Section 11.1. This was the subject of Exercise 2 in Section 11.5. In this example, the forecasts are almost identical to the previous two methods.
The STL approach or TBATS model is preferable when the seasonality changes over time. The dynamic harmonic regression approach is preferable if there are covariates that are useful predictors as these can be added as additional regressors.
Daily and sub-daily data are challenging for a different reason — they often involve multiple seasonal patterns, and so we need to use a method that handles such complex seasonality.
Of course, if the time series is relatively short so that only one type of seasonality is present, then it will be possible to use one of the single-seasonal methods we have discussed in previous chapters (e.g., ETS or a seasonal ARIMA model). But when the time series is long enough so that some of the longer seasonal periods become apparent, it will be necessary to use STL, dynamic harmonic regression or TBATS, as discussed in Section 11.1.
However, note that even these models only allow for regular seasonality. Capturing seasonality associated with moving events such as Easter, Id, or the Chinese New Year is more difficult. Even with monthly data, this can be tricky as the festivals can fall in either March or April (for Easter), in January or February (for the Chinese New Year), or at any time of the year (for Id).
The best way to deal with moving holiday effects is to use dummy variables. However, neither STL, ETS nor TBATS models allow for covariates. Amongst the models discussed in this book (and implemented in the forecast package for R), the only choice is a dynamic regression model, where the predictors include any dummy holiday effects (and possibly also the seasonality using Fourier terms).
All of the methods discussed in this book assume that the data have a continuous sample space. But often data comes in the form of counts. For example, we may wish to forecast the number of customers who enter a store each day. We could have 0, 1, 2, , customers, but we cannot have 3.45693 customers.
In practice, this rarely matters provided our counts are sufficiently large. If the minimum number of customers is at least 100, then the difference between a continuous sample space [100,\infty) and the discrete sample space \{100,101,102,\dots\} has no perceivable effect on our forecasts. However, if our data contains small counts (0, 1, 2, \dots), then we need to use forecasting methods that are more appropriate for a sample space of non-negative integers.
Such models are beyond the scope of this book. However, there is one simple method which gets used in this context, that we would like to mention. It is “Croston’s method”, named after its British inventor, John Croston, and first described in Croston (1972). Actually, this method does not properly deal with the count nature of the data either, but it is used so often, that it is worth knowing about it.
With Croston’s method, we construct two new series from our original time series by noting which time periods contain zero values, and which periods contain non-zero values. Let q_i be the ith non-zero quantity, and let a_i be the time between q_{i-1} and q_i. Croston’s method involves separate simple exponential smoothing forecasts on the two new series a and q. Because the method is usually applied to time series of demand for items, q is often called the “demand” and a the “inter-arrival time”.
If \hat{q}_{i+1|i} and \hat{a}_{i+1|i} are the one-step forecasts of the (i + 1)th demand and inter-arrival time respectively, based on data up to demand i, then Croston’s method gives \begin{align} \hat{q}_{i+1|i} & = (1 - \alpha)\hat{q}_{i|i-1} + \alpha q_i, \\ \hat{a}_{i+1|i} & = (1 - \alpha)\hat{a}_{i|i-1} + \alpha a_i. \end{align} The smoothing parameter \alpha takes values between 0 and 1 and is assumed to be the same for both equations. Let j be the time for the last observed positive observation. Then the h-step ahead forecast for the demand at time T + h, is given by the ratio \hat{y}_{T+h|T} = \hat{q}_{j+1|j}/\hat{a}_{j+1|j}. There are no algebraic results allowing us to compute prediction intervals for this method, because the method does not correspond to any statistical model (Shenstone & Hyndman, 2005). Forecasts obtained from Croston’s method are also known to be biased (Syntetos & Boylan, 2001).
The croston() function produces forecasts using Croston’s method. It simply uses \alpha = 0.1 by default, and the initial values \hat{q}_{1|0} and \hat{a}_{1|0} are set equal to q_1 and a_1, the first observation in each of the series. This is consistent with the way Croston envisaged the method being used.
Several years ago, we assisted an oil company with forecasts of monthly lubricant sales. One of the time series is shown in the table below. The data contain small counts, with many months registering no sales at all, and only small numbers of items sold in other months.
| Year | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 0 | 2 | 0 | 1 | 0 | 11 | 0 | 0 | 0 | 0 | 2 | 0 |
| 2 | 6 | 3 | 0 | 0 | 0 | 0 | 0 | 7 | 0 | 0 | 0 | 0 |
| 3 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 |
There are 11 non-zero demand values in the series, denoted by q. The corresponding arrival series a are also shown in the following table.
| i | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| q | 2 | 1 | 11 | 2 | 6 | 3 | 7 | 3 | 1 | 1 | 1 |
| a | 2 | 2 | 2 | 5 | 2 | 1 | 6 | 8 | 1 | 3 | 2 |
Applying Croston’s method gives the demand forecast 2.750 and the arrival forecast 2.793. So the forecast of the original series is \hat{y}_{T+h|T} = 2.750 / 2.793 = 0.985. In practice, R does these calculations for you:
productC |> croston() |> autoplot()
An implementation of Croston’s method with more facilities (including parameter estimation) is available in the tsintermittent package for R.
Forecasting models that deal more directly with the count nature of the data are described in Christou & Fokianos (2015).
It is common to want forecasts to be positive, or to require them to be within some specified range [a,b]. Both of these situations are relatively easy to handle using transformations.
To impose a positivity constraint, simply work on the log scale, by specifying the Box-Cox parameter \lambda = 0. For example, consider the real price of a dozen eggs (1900-1993; in cents):
eggs |>
ets(model = "AAN", damped = FALSE, lambda = 0) |>
forecast(h = 50, biasadj = TRUE) |>
autoplot()
Because we set biasadj=TRUE, the forecasts are the means of the forecast distributions.
To see how to handle data constrained to an interval, imagine that the egg prices were constrained to lie within a = 50 and b = 400. Then we can transform the data using a scaled logit transform which maps (a,b) to the whole real line: y = \log\left( \frac{x - a}{b - x} \right), where x is on the original scale and y is the transformed data. To reverse the transformation, we will use x = \frac{(b - a)e^y}{1 + e^y} + a. This is not a built-in transformation, so we will need to do more work.
# Bounds
a <- 50
b <- 400
# Transform data and fit model
fit <- log((eggs - a) / (b - eggs)) |>
ets(model = "AAN", damped = FALSE)
fc <- forecast(fit, h = 50)
# Back-transform forecasts
fc[["mean"]] <- (b - a) * exp(fc[["mean"]]) / (1 + exp(fc[["mean"]])) + a
fc[["lower"]] <- (b - a) * exp(fc[["lower"]]) / (1 + exp(fc[["lower"]])) + a
fc[["upper"]] <- (b - a) * exp(fc[["upper"]]) / (1 + exp(fc[["upper"]])) + a
fc[["x"]] <- eggs
# Plot result on original scale
autoplot(fc)
No bias-adjustment has been used here, so the forecasts are the medians of the future distributions. The prediction intervals from these transformations have the same coverage probability as on the transformed scale, because quantiles are preserved under monotonically increasing transformations.
The prediction intervals lie above 50 due to the transformation. As a result of this artificial (and unrealistic) constraint, the forecast distributions have become extremely skewed.
An easy way to improve forecast accuracy is to use several different methods on the same time series, and to average the resulting forecasts. Nearly 50 years ago, John Bates and Clive Granger wrote a famous paper (Bates & Granger, 1969), showing that combining forecasts often leads to better forecast accuracy. Twenty years later, Clemen (1989) wrote
The results have been virtually unanimous: combining multiple forecasts leads to increased forecast accuracy. In many cases one can make dramatic performance improvements by simply averaging the forecasts.
While there has been considerable research on using weighted averages, or some other more complicated combination approach, using a simple average has proven hard to beat.
Here is an example using monthly expenditure on eating out in Australia, from April 1982 to September 2017. We use forecasts from the following models: ETS, ARIMA, STL-ETS, NNAR, and TBATS; and we compare the results using the last 5 years (60 months) of observations.
train <- window(auscafe, end = c(2012, 9))
h <- length(auscafe) - length(train)
ETS <- forecast(ets(train), h = h)
ARIMA <- forecast(auto.arima(train, lambda = 0, biasadj = TRUE), h = h)
STL <- stlf(train, lambda = 0, h = h, biasadj = TRUE)
NNAR <- forecast(nnetar(train), h = h)
TBATS <- forecast(tbats(train, biasadj = TRUE), h = h)
Combination <- (ETS[["mean"]] +
ARIMA[["mean"]] +
STL[["mean"]] +
NNAR[["mean"]] +
TBATS[["mean"]]) /
5autoplot(auscafe) +
autolayer(ETS, series = "ETS", PI = FALSE) +
autolayer(ARIMA, series = "ARIMA", PI = FALSE) +
autolayer(STL, series = "STL", PI = FALSE) +
autolayer(NNAR, series = "NNAR", PI = FALSE) +
autolayer(TBATS, series = "TBATS", PI = FALSE) +
autolayer(Combination, series = "Combination") +
xlab("Year") +
ylab("$ billion") +
ggtitle("Australian monthly expenditure on eating out")
c(
ETS = accuracy(ETS, auscafe)["Test set", "RMSE"],
ARIMA = accuracy(ARIMA, auscafe)["Test set", "RMSE"],
`STL-ETS` = accuracy(STL, auscafe)["Test set", "RMSE"],
NNAR = accuracy(NNAR, auscafe)["Test set", "RMSE"],
TBATS = accuracy(TBATS, auscafe)["Test set", "RMSE"],
Combination = accuracy(Combination, auscafe)["Test set", "RMSE"]
) ETS ARIMA STL-ETS NNAR TBATS Combination
0.13700 0.15920 0.19310 0.31769 0.09406 0.07161
TBATS does particularly well with this series, but the combination approach is even better. For other data, TBATS may be quite poor, while the combination approach is almost always close to, or better than, the best component method.
A common problem is to forecast the aggregate of several time periods of data, using a model fitted to the disaggregated data. For example, we may have monthly data but wish to forecast the total for the next year. Or we may have weekly data, and want to forecast the total for the next four weeks.
If the point forecasts are means, then adding them up will give a good estimate of the total. But prediction intervals are more tricky due to the correlations between forecast errors.
A general solution is to use simulations. Here is an example using ETS models applied to Australian monthly gas production data, assuming we wish to forecast the aggregate gas demand in the next six months.
# First fit a model to the data
fit <- ets(gas / 1000)
# Forecast six months ahead
fc <- forecast(fit, h = 6)
# Simulate 10000 future sample paths
nsim <- 10000
h <- 6
sim <- numeric(nsim)
for (i in seq_len(nsim)) {
sim[i] <- sum(simulate(fit, future = TRUE, nsim = h))
}
meanagg <- mean(sim)The mean of the simulations is close to the sum of the individual forecasts:
sum(fc[["mean"]][1:6])[1] 281.8
meanagg[1] 281.7
Prediction intervals are also easy to obtain:
#80% interval:
quantile(sim, prob = c(0.1, 0.9))10% 90%
263 301
#95% interval:
quantile(sim, prob = c(0.025, 0.975)) 2.5% 97.5%
254.1 311.4
Sometimes it is useful to “backcast” a time series — that is, forecast in reverse time. Although there are no in-built R functions to do this, it is easy to implement. The following functions reverse a ts object and a forecast object.
# Function to reverse time
reverse_ts <- function(y) {
ts(rev(y), start = tsp(y)[1L], frequency = frequency(y))
}
# Function to reverse a forecast
reverse_forecast <- function(object) {
h <- length(object[["mean"]])
f <- frequency(object[["mean"]])
object[["x"]] <- reverse_ts(object[["x"]])
object[["mean"]] <- ts(
rev(object[["mean"]]),
end = tsp(object[["x"]])[1L] - 1 / f,
frequency = f
)
object[["lower"]] <- object[["lower"]][h:1L, ]
object[["upper"]] <- object[["upper"]][h:1L, ]
return(object)
}Then we can apply these functions to backcast any time series. Here is an example applied to quarterly retail trade in the Euro area. The data are from 1996 to 2011. We backcast to predict the years 1994-1995.
# Backcast example
euretail |>
reverse_ts() |>
auto.arima() |>
forecast() |>
reverse_forecast() -> bc
autoplot(bc) +
ggtitle(paste("Backcasts from", bc[["method"]]))
We often get asked how few data points can be used to fit a time series model. As with almost all sample size questions, there is no easy answer. It depends on the number of model parameters to be estimated and the amount of randomness in the data. The sample size required increases with the number of parameters to be estimated, and the amount of noise in the data.
Some textbooks provide rules-of-thumb giving minimum sample sizes for various time series models. These are misleading and unsubstantiated in theory or practice. Further, they ignore the underlying variability of the data and often overlook the number of parameters to be estimated as well. There is, for example, no justification whatever for the magic number of 30 often given as a minimum for ARIMA modelling. The only theoretical limit is that we need more observations than there are parameters in our forecasting model. However, in practice, we usually need substantially more observations than that.
Ideally, we would test if our chosen model performs well out-of-sample compared to some simpler approaches. However, with short series, there is not enough data to allow some observations to be withheld for testing purposes, and even time series cross validation can be difficult to apply. The AICc is particularly useful here, because it is a proxy for the one-step forecast out-of-sample MSE. Choosing the model with the minimum AICc value allows both the number of parameters and the amount of noise to be taken into account.
What tends to happen with short series is that the AIC suggests simple models because anything with more than one or two parameters will produce poor forecasts due to the estimation error. We applied the auto.arima() function to all the series from the M-competition with fewer than 20 observations. There were a total of 144 series, of which 54 had models with zero parameters (white noise and random walks), 73 had models with one parameter, 15 had models with two parameters, and 2 series had models with three parameters. Interested readers can carry out the same exercise using the following code.
library(Mcomp)
library(purrr)
n <- map_int(M1, function(x) {
length(x[["x"]])
})
M1[n < 20] |>
map_int(function(u) {
u[["x"]] |>
auto.arima() |>
coefficients() |>
length()
}) |>
table()Most time series models do not work well for very long time series. The problem is that real data do not come from the models we use. When the number of observations is not large (say up to about 200) the models often work well as an approximation to whatever process generated the data. But eventually we will have enough data that the difference between the true process and the model starts to become more obvious. An additional problem is that the optimisation of the parameters becomes more time consuming because of the number of observations involved.
What to do about these issues depends on the purpose of the model. A more flexible and complicated model could be used, but this still assumes that the model structure will work over the whole period of the data. A better approach is usually to allow the model itself to change over time. ETS models are designed to handle this situation by allowing the trend and seasonal terms to evolve over time. ARIMA models with differencing have a similar property. But dynamic regression models do not allow any evolution of model components.
If we are only interested in forecasting the next few observations, one simple approach is to throw away the earliest observations and only fit a model to the most recent observations. Then an inflexible model can work well because there is not enough time for the relationships to change substantially.
For example, we fitted a dynamic harmonic regression model to 26 years of weekly gasoline production in Section 12.1. It is, perhaps, unrealistic to assume that the seasonal pattern remains the same over nearly three decades. So we could simply fit a model to the most recent years instead.
Typically, we compute one-step forecasts on the training data (the “fitted values”) and multi-step forecasts on the test data. However, occasionally we may wish to compute multi-step forecasts on the training data, or one-step forecasts on the test data.
We normally define fitted values to be one-step forecasts on the training set (see Section 3.3), but a similar idea can be used for multi-step forecasts. We will illustrate the method using an ARIMA(2,1,1)(0,1,2)_{12} model for the Australian eating-out expenditure. The last five years are used for a test set, and the forecasts are plotted in Figure 12.7.
training <- subset(auscafe, end = length(auscafe) - 61)
test <- subset(auscafe, start = length(auscafe) - 60)
cafe.train <- Arima(
training,
order = c(2, 1, 1),
seasonal = c(0, 1, 2),
lambda = 0
)
cafe.train |>
forecast(h = 60) |>
autoplot() +
autolayer(test)
The fitted() function has an h argument to allow for h-step “fitted values” on the training set. Figure 12.8 is a plot of 12-step (one year) forecasts on the training set. Because the model involves both seasonal (lag 12) and first (lag 1) differencing, it is not possible to compute these forecasts for the first few observations.
autoplot(training, series = "Training data") +
autolayer(fitted(cafe.train, h = 12), series = "12-step fitted values")
It is common practice to fit a model using training data, and then to evaluate its performance on a test data set. The way this is usually done means the comparisons on the test data use different forecast horizons. In the above example, we have used the last sixty observations for the test data, and estimated our forecasting model on the training data. Then the forecast errors will be for 1-step, 2-steps, …, 60-steps ahead. The forecast variance usually increases with the forecast horizon, so if we are simply averaging the absolute or squared errors from the test set, we are combining results with different variances.
One solution to this issue is to obtain 1-step errors on the test data. That is, we still use the training data to estimate any parameters, but when we compute forecasts on the test data, we use all of the data preceding each observation (both training and test data). So our training data are for times 1,2,\dots,T - 60. We estimate the model on these data, but then compute \hat{y}_{T-60+h|T-61+h}, for h = 1,\dots,T - 1. Because the test data are not used to estimate the parameters, this still gives us a “fair” forecast. For the ets(), Arima(), tbats() and nnetar() functions, these calculations are easily carried out using the model argument.
Using the same ARIMA model used above, we now apply the model to the test data.
cafe.test <- Arima(test, model = cafe.train)
accuracy(cafe.test) ME RMSE MAE MPE MAPE MASE ACF1
Training set -0.002622 0.04591 0.03413 -0.07301 1.002 0.1899 -0.05704
Note that Arima() does not re-estimate in this case. Instead, the model obtained previously (and stored as cafe.train) is applied to the test data. Because the model was not re-estimated, the “residuals” obtained here are actually one-step forecast errors. Consequently, the results produced from the accuracy() command are actually on the test set (despite the output saying “Training set”).
Real data often contains missing values, outlying observations, and other messy features. Dealing with them can sometimes be troublesome.
Missing data can arise for many reasons, and it is worth considering whether the missingness will induce bias in the forecasting model. For example, suppose we are studying sales data for a store, and missing values occur on public holidays when the store is closed. The following day may have increased sales as a result. If we fail to allow for this in our forecasting model, we will most likely under-estimate sales on the first day after the public holiday, but over-estimate sales on the days after that. One way to deal with this kind of situation is to use a dynamic regression model, with dummy variables indicating if the day is a public holiday or the day after a public holiday. No automated method can handle such effects as they depend on the specific forecasting context.
In other situations, the missingness may be essentially random. For example, someone may have forgotten to record the sales figures, or the data recording device may have malfunctioned. If the timing of the missing data is not informative for the forecasting problem, then the missing values can be handled more easily.
Some methods allow for missing values without any problems. For example, the naïve forecasting method continues to work, with the most recent non-missing value providing the forecast for the future time periods. Similarly, the other benchmark methods introduced in Section 3.1 will all produce forecasts when there are missing values present in the historical data. The R functions for ARIMA models, dynamic regression models and NNAR models will also work correctly without causing errors. However, other modelling functions do not handle missing values including ets(), stlf(), and tbats().
When missing values cause errors, there are at least two ways to handle the problem. First, we could just take the section of data after the last missing value, assuming there is a long enough series of observations to produce meaningful forecasts. Alternatively, we could replace the missing values with estimates. The na.interp() function is designed for this purpose.
The gold data contains daily morning gold prices from 1 January 1985 to 31 March 1989. This series was provided to us as part of a consulting project; it contains 34 missing values as well as one apparently incorrect value. Figure 12.9 shows estimates of the missing observations in red.
gold2 <- na.interp(gold)
autoplot(gold2, series = "Interpolated") +
autolayer(gold, series = "Original") +
scale_colour_manual(
values = c(`Interpolated` = "red", `Original` = "gray")
)
For non-seasonal data like this, simple linear interpolation is used to fill in the missing sections. For seasonal data, an STL decomposition is used to estimate the seasonal component, and the seasonally adjusted series are linear interpolated. More sophisticated missing value interpolation is provided in the imputeTS package.
Outliers are observations that are very different from the majority of the observations in the time series. They may be errors, or they may simply be unusual. (See Section 5.3 for a discussion of outliers in a regression context.) All of the methods we have considered in this book will not work well if there are extreme outliers in the data. In this case, we may wish to replace them with missing values, or with an estimate that is more consistent with the majority of the data.
Simply replacing outliers without thinking about why they have occurred is a dangerous practice. They may provide useful information about the process that produced the data, and which should be taken into account when forecasting.
However, if we are willing to assume that the outliers are genuinely errors, or that they won’t occur in the forecasting period, then replacing them can make the forecasting task easier.
The tsoutliers() function is designed to identify outliers, and to suggest potential replacement values. In the gold data shown in Figure 12.9, there is an apparent outlier on day 770:
tsoutliers(gold)$index
[1] 770
$replacements
[1] 494.9
Closer inspection reveals that the neighbouring observations are close to $100 less than the apparent outlier.
gold[768:772][1] 495.00 502.75 593.70 487.05 487.75
Most likely, this was a transcription error, and the correct value should have been $493.70.
Another useful function is tsclean() which identifies and replaces outliers, and also replaces missing values. Obviously this should be used with some caution, but it does allow us to use forecasting models that are sensitive to outliers, or which do not handle missing values. For example, we could use the ets() function on the gold series, after applying tsclean().
gold |>
tsclean() |>
ets() |>
forecast(h = 50) |>
autoplot()
Notice that the outlier and missing values have been replaced with estimates.
So many diverse topics are discussed in this chapter, that it is not possible to point to specific references on all of them. The last chapter in Ord et al. (2017) also covers “Forecasting in practice” and discusses other issues that might be of interest to readers.