Search

Search papers and lessons

Time Series Forecasting

Level 2 · 11 min read

Time series forecasting predicts the next values of a sequence recorded over time, using its own past as input, and is judged only on data the model has not seen.

On this page

  • Colour = topic mix
  • Probability
  • Discrete math
  • Calculus
  • Linear algebra
  • Losses & regularization
  • Stochastic processes
  • ReadReady to readNot yet

TL;DR

Time series forecasting is the job of predicting the next values of a sequence that is recorded over time, such as daily sales or hourly electricity use. The simplest useful method takes recent values as input and learns a rule that maps them to the value that comes next. Many decisions, from stocking shelves to scheduling power plants, depend on that prediction.

Builds on: Linear Regression, Mean and Variance, Loss Function · Leads to: N-BEATS: Neural Basis Expansion for Interpretable Forecasting, DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks

Where it's used

Electricity demand. A grid operator has to have generators running before people switch on their kettles. It forecasts demand hour by hour for the next day, using the recent load and the load at the same hour on earlier days. An error of a few percent can mean buying expensive last-minute power or leaving capacity idle.

Store restocking. A supermarket chain forecasts how many units of each product each store will sell next week. The inputs are recent weekly sales, the season and planned promotions. The forecast sets the order sent to the warehouse, so a bad forecast shows up as empty shelves or spoiled stock.

Forecasting many series at once. DeepAR (DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks) trains one neural network across many related series, such as the sales of thousands of products, and returns a range of likely values instead of a single number. This lets a company forecast every product with one model rather than one model per product.

How it works

Take one tiny instance from start to finish. The series is six monthly sales figures, in thousands: 10, 12, 11, 13, 14, 16. The goal is to forecast month 7. The method uses last month to predict this month. A previous value used as input is called a lag, so this is a lag-1 model: next = w₀ + w₁ × last.

  1. Turn the series into input-output pairs. Each month is an input, and the month after it is the target. The pairs are (10, 12), (12, 11), (11, 13), (13, 14), (14, 16). Check: six numbers give five pairs, because the last month has no next month to learn from.
  2. Fit a line through the pairs. Linear regression finds the intercept w₀ and slope w₁ that make the predicted targets as close as possible to the real ones. Here w₁ = 0.9 and w₀ = 2.4. Check: for input 10 the prediction is 2.4 + 0.9 × 10 = 11.4, near the true 12.
  3. Measure the errors. The residuals (true value minus prediction) are 0.6, −2.2, 0.7, −0.1 and 1.0. Check: they add to 0, as they must when the line includes an intercept.
  4. Forecast forward. Feed the latest value, 16, into the rule: 2.4 + 0.9 × 16 = 16.8. Check: the forecast for month 7 is 16.8 thousand.
  5. Feed forecasts back for longer horizons. To forecast month 8 we use the forecast we just made as the input: 2.4 + 0.9 × 16.8 = 17.52. Check: each step builds on the previous guess, so errors can grow with the horizon.
01234567881012141618monthsales (thousands)
  • observed sales
Six observed months, and the forecast for month 7 as the marker at 16.8.

The whole procedure is a pipeline:

flowchart LR
  A["Past values y1 to yT"] --> B["Build lagged input-output pairs"]
  B --> C["Fit a rule by least squares"]
  C --> D["Forecast the next value"]
  D --> E["Score on data not used to fit"]

The math

Definition: Time series forecasting
Given observations y1,…,yTy_1, \dots, y_T recorded at equally spaced times, choose a function ff so that the forecast y^T+h=f(y1,…,yT)\hat{y}_{T+h} = f(y_1, \dots, y_T) is close to the true future value yT+hy_{T+h}, for a horizon h≥1h \ge 1. Here y^\hat{y} (read "y hat") is the predicted value, and hh is how many steps ahead we forecast.

The lag-1 model of the walkthrough is the special case y^t+1=w0+w1yt\hat{y}_{t+1} = w_0 + w_1 y_t, where yty_t is the value at time tt, w0w_0 is the intercept and w1w_1 is the slope. A general autoregressive model of order pp uses the last pp values, as in Autoregressive Model.

Step 1 in symbols

Form the pairs (xi,zi)=(yt,yt+1)(x_i, z_i) = (y_t, y_{t+1}) for t=1,…,T−1t = 1, \dots, T-1. The inputs are xix_i, the targets are ziz_i, and there are n=T−1n = T - 1 pairs. In the walkthrough, n=5n = 5.

Step 2 in symbols

Least squares chooses w0w_0 and w1w_1 to make the sum of squared errors as small as possible:

L(w0,w1)=∑i=1n(zi−w0−w1xi)2L(w_0, w_1) = \sum_{i=1}^{n} \bigl(z_i - w_0 - w_1 x_i\bigr)^2

Setting the derivatives of LL to zero gives

w1=SxzSxx,w0=zˉ−w1xˉ,w_1 = \frac{S_{xz}}{S_{xx}}, \qquad w_0 = \bar{z} - w_1 \bar{x},

where xˉ\bar{x} and zˉ\bar{z} are the means of the inputs and targets, Sxz=∑i(xi−xˉ)(zi−zˉ)S_{xz} = \sum_i (x_i - \bar{x})(z_i - \bar{z}) and Sxx=∑i(xi−xˉ)2S_{xx} = \sum_i (x_i - \bar{x})^2. The loss LL is nn times the Mean Squared Error, so this is the same fit that Linear Regression computes.

For the walkthrough: xˉ=12\bar{x} = 12, zˉ=13.2\bar{z} = 13.2, Sxz=9.0S_{xz} = 9.0 and Sxx=10S_{xx} = 10. So w1=9.0/10=0.9w_1 = 9.0 / 10 = 0.9 and w0=13.2−0.9×12=2.4w_0 = 13.2 - 0.9 \times 12 = 2.4.

Step 4 in symbols

y^7=2.4+0.9×16=16.8\hat{y}_7 = 2.4 + 0.9 \times 16 = 16.8

Step 5 in symbols

The forecast is fed back as an input: y^8=2.4+0.9 y^7=17.52\hat{y}_8 = 2.4 + 0.9\,\hat{y}_7 = 17.52. This recursion is only as good as the rule, and the rule is assumed to hold in the future. That assumption is valid when the process is Stationary Process, meaning its statistical behaviour does not drift.

Worked examples

Example
1. A perfect straight line (tiny)
  1. Series: 5, 7, 9, 11.
  2. Pairs (input to target): (5 to 7), (7 to 9), (9 to 11).
  3. Mean of the inputs: (5 + 7 + 9) / 3 = 7. Mean of the targets: (7 + 9 + 11) / 3 = 9.
  4. Deviations of the inputs from 7: −2, 0, 2. Deviations of the targets from 9: −2, 0, 2.
  5. Sxz=(−2)(−2)+0⋅0+2⋅2=8S_{xz} = (-2)(-2) + 0 \cdot 0 + 2 \cdot 2 = 8 and Sxx=4+0+4=8S_{xx} = 4 + 0 + 4 = 8.
  6. w1=8/8=1w_1 = 8 / 8 = 1 and w0=9−1×7=2w_0 = 9 - 1 \times 7 = 2.
  7. Check each pair: 2+5=72 + 5 = 7, 2+7=92 + 7 = 9, 2+9=112 + 9 = 11. All residuals are zero.
  8. Forecast after 11: 2+1×11=132 + 1 \times 11 = 13.

Interpretation: the series rises by 2 each step, and the fitted rule has learned exactly that. Real data is never this clean, but the arithmetic is the same.

Example
2. A falling series (standard)
  1. Series: 20, 18, 19, 17, 16.
  2. Pairs: (20 to 18), (18 to 19), (19 to 17), (17 to 16).
  3. Inputs 20, 18, 19, 17 have mean 18.5. Targets 18, 19, 17, 16 have mean 17.5.
  4. Input deviations: 1.5, −0.5, 0.5, −1.5. Target deviations: 0.5, 1.5, −0.5, −1.5.
  5. Products of deviations: 0.75, −0.75, −0.25, 2.25. Their sum is Sxz=2.0S_{xz} = 2.0. Squared input deviations: 2.25, 0.25, 0.25, 2.25, so Sxx=5.0S_{xx} = 5.0.
  6. w1=2.0/5.0=0.4w_1 = 2.0 / 5.0 = 0.4 and w0=17.5−0.4×18.5=17.5−7.4=10.1w_0 = 17.5 - 0.4 \times 18.5 = 17.5 - 7.4 = 10.1.
  7. Forecast after 16: 10.1+0.4×16=10.1+6.4=16.510.1 + 0.4 \times 16 = 10.1 + 6.4 = 16.5.
  8. Interpretation: a slope of 0.4 pulls the series toward the level 10.1/(1−0.4)≈16.810.1 / (1 - 0.4) \approx 16.8. The forecast of 16.5 is a small rise from 16 toward that level, not a jump.
Example
3. Hourly electricity demand (realistic, illustrative)

These numbers are made up to show the arithmetic. They are not measured data. An operator forecasts demand for the next hour, in megawatts (MW), from two inputs: the load in the last hour, and the load at the same hour yesterday. Suppose the fitted rule is forecast = 0.6 × last hour + 0.4 × same hour yesterday.

  1. Last hour: 500 MW. Same hour yesterday: 480 MW.
  2. Weighted parts: 0.6 × 500 = 300 and 0.4 × 480 = 192.
  3. Add them: 300 + 192 = 492 MW.
  4. Interpretation: the forecast sits between the two inputs and closer to the recent hour, because that input has the larger weight. The day-earlier input carries the daily pattern that the last hour alone would miss.

Try it: the operator changes the weights to 0.5 and 0.5, and the inputs stay at 500 and 480 MW. What is the forecast? Answer: 0.5 × 500 + 0.5 × 480 = 250 + 240 = 490 MW. Equal weights put the forecast halfway between the two inputs.

Common mistakes and tradeoffs

It is tempting to think you should shuffle time series data and split it at random, as with ordinary data. In fact the test data must come after the training data. A random split lets the model learn from the future, so its score looks better than it really is. Keep the time order, and use Train, Validation and Test Sets with a cut-off date. When you need more than one test period, roll the origin forward, as in Cross-Validation adapted to time.

It is tempting to think the rule learned from the past will hold forever. In fact it holds only while the process is roughly stationary (Stationary Process). A trend, a shift in level or a seasonal cycle can break a rule that was fitted on different conditions.

It is tempting to think a more complex model always wins. In fact the naive forecast, which repeats the last observed value, is a strong baseline. If a model cannot beat it on data it has not seen, the model is not earning its complexity.

It is tempting to think a forecast far ahead is as reliable as one step ahead. In fact errors compound, because each step feeds a guess into the next guess, as step 5 of the walkthrough showed.

SituationReasonable choice
Short horizon, one series, few inputsLag model or Autoregressive Model
Noisy series where the level matters mostExponential Moving Average or ARMA Model
Many related series, many inputsA neural forecaster such as DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks
Outside events drive the series (holidays, promotions)Add those events as inputs; a lag model alone misses them

History

In 1927 the statistician G. Udny Yule used autoregressive models to study disturbances in sunspot counts, which is one of the first uses of the idea of predicting a series from its own past. In the 1950s and 1960s, exponential smoothing methods were developed for business forecasting, because they are cheap to run on many series. In 1970 George Box and Gwilym Jenkins published Time Series Analysis: Forecasting and Control. It gave a practical cycle of identifying, estimating and checking models, and it made the autoregressive and moving-average family the standard toolkit. Neural networks were applied to forecasting from the 1990s on, and in recent years large deep models trained across many series, such as DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks and Chronos: Learning the Language of Time Series, have been compared against these classical methods.

Recap

  • A time series is ordered in time, and forecasting predicts its future from its past.
  • Turn the past into input-output pairs, using lags as inputs.
  • Fit a rule, here a line, by least squares, which minimises the squared error.
  • Forecast by applying the rule, and feed forecasts back for longer horizons, accepting that errors grow.
  • Evaluate in time order, on data the model has not seen, and always against a naive baseline.

Read next: Autoregressive Model for the general lag model, then N-BEATS: Neural Basis Expansion for Interpretable Forecasting and DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks for deep forecasters.

Check yourself

QuestionRecall: what is a lag, and what is a lag-1 model?Show answer
A lag is a value from k steps earlier in the series. A lag-1 model uses only the previous value as input, so the forecast for time t+1 depends on yty_t.
QuestionComputation: the series is 4, 6, 8. Fit the lag-1 line to the pairs (4 to 6) and (6 to 8). What is the forecast after 8?Show answer
The inputs 4, 6 have mean 5 and the targets 6, 8 have mean 7. Input deviations are −1 and 1, target deviations are −1 and 1, so Sxz=2S_{xz} = 2 and Sxx=2S_{xx} = 2. Then w1=1w_1 = 1 and w0=7−1×5=2w_0 = 7 - 1 \times 5 = 2. The forecast after 8 is 2+1×8=102 + 1 \times 8 = 10.
QuestionWhy: why must the test data come after the training data in a time series?Show answer
Because the model must be scored on the kind of prediction it will face in use, which is the future. A random split lets the model train on values that occur after some test values, so it learns information it would not have when forecasting, and the test score is too optimistic.
QuestionApplied: a store expects sales to jump 40% next week for a public holiday. Its model was trained only on past sales, with no holiday input, and forecasts an ordinary week. What is wrong, and what would you change?Show answer
The model predicts only from its own past values, and the holiday is an outside driver that does not appear in that history, so the forecast misses the jump. Add a holiday indicator as an input, and check the model on past holiday weeks, not only on ordinary ones.

Sources