Time Series Forecasting

Forecast what comes next: trend and seasonality, benchmarks, exponential smoothing, autoregression on lags, walk-forward testing, MASE and intervals.

Intermediate lesson, about 35 minutes, with interactive demos and a quiz.

What you will learn

When order is the data

How much electricity will the grid need at 6 pm tomorrow? How many nurses should a hospital roster for next week? How many umbrellas should a shop order for October? Every one of these is a forecast: a prediction of a future value from a record of past values taken at regular times.

What is it?

A time series is a sequence of measurements in time order: daily sales, hourly temperature, monthly passengers. Forecasting predicts its next values. Unlike the rows of an ordinary dataset, the observations are not independent: today resembles yesterday, and this July resembles last July. That dependence is what makes forecasting possible, and it is also what breaks several habits from the rest of machine learning.

How does it work?

Most series are a mix of a few recognisable parts:

TrendThe long-run direction: growth in passengers, decline in landline calls.SeasonalityA pattern with a fixed period: higher demand every winter, every weekend, every evening.RemainderIrregular movement left after trend and season: weather, strikes, measurement noise.

The tool for seeing the dependence is autocorrelation: the correlation between the series and a copy of itself shifted k steps back (lag k). A high value at lag 1 means neighbouring values are alike; a high value at lag 12 in monthly data means a yearly cycle. The plot of autocorrelation against lag is the ACF, a central tool in the method Box and Jenkins set out for choosing a forecasting model.

With season alone the ACF is a wave with peaks at 12 and 24. Add a trend (0.3 a month is enough with the default season and noise) and every lag becomes positive, decaying slowly: a rising series is above its average late and below it early, whatever the lag. Turn up the noise and the bars shrink towards the dashed band, which is roughly where the autocorrelations of pure noise would fall. The airline series, Box and Jenkins’ Series G, shows both effects at once.

Why does it matter?

Forecasts feed decisions in supply chains, power grids, hospital rotas and central banks. Autocorrelation is both the opportunity (the past carries information about the future) and the trap: methods that assume independent rows, such as a shuffled train/test split, quietly give wrong answers on time series. This lesson builds forecasting up from the simplest methods that work, following the approach of Hyndman and Athanasopoulos’s free textbook Forecasting: Principles and Practice.

Key takeaways

  • A time series is ordered, and nearby values are correlated; forecasting uses that dependence.
  • Most series combine a trend, a seasonal pattern and an irregular remainder.
  • The autocorrelation function shows the dependence: lag 1 for persistence, the seasonal lag for cycles.

Taking a series apart

Before forecasting a series, split it into the parts you can explain and look at what is left.

What is it?

Decomposition writes a series as a trend, a seasonal component and a remainder. In an additive decomposition they add up; in a multiplicative one they multiply, so the seasonal swing grows and shrinks with the level.

additive: yₜ = Tₜ + Sₜ + Rₜ
multiplicative: yₜ = Tₜ × Sₜ × Rₜ

T is the trend, S the seasonal component, R the remainder, at time t.

How does it work?

  1. Trend. Average each value with its neighbours using a centred moving average. If the window covers exactly one period (for monthly data, a “2×12” average that gives half weight to the two ends) every month of the year counts once, so the season cancels out.
  2. Season. Remove the trend (subtract it, or divide by it) and average what is left for each month of the year. These twelve numbers are the seasonal indices.
  3. Remainder. Whatever trend and season do not explain. If the decomposition suits the series, it looks like patternless noise of roughly constant size.

This is classical decomposition, which dates from the 1920s and is the starting point for most other methods. Modern variants such as STL can be made robust to outliers and let the seasonal pattern change slowly, but they share the same idea (Hyndman and Athanasopoulos, chapter 3).

Try a 7-month window: the trend picks up a ripple, because some months of the year are counted and others are not, and the seasonal component shrinks, because part of the season has gone into the trend. On the synthetic series, whose season really is a fixed size, additive and multiplicative look much alike. Taking logarithms turns a multiplicative series into an additive one (log of a product is a sum), which is why the classic “airline model” for this series is fitted to the logarithm of the passenger numbers.

Why does it matter?

Decomposition is how official statistics agencies produce “seasonally adjusted” unemployment and retail figures, so that a December jump in shop sales is not mistaken for a boom. For forecasting, it tells you which parts the model must capture, and it is a forecasting method in its own right: extend the trend, repeat the season.

Key takeaways

  • Decomposition splits a series into trend, season and remainder, added or multiplied.
  • A centred moving average over exactly one period estimates the trend with the season averaged out.
  • Choose multiplicative (or work on logs) when the seasonal swing grows with the level.

Baselines you must beat

Before building anything clever, ask what the simplest possible forecast would score. A model that cannot beat it is not worth using.

What is it?

Four simple methods are the standard forecasting benchmarks:

MeanEvery future value is the average of the past.NaiveEvery future value is the last observed value. Optimal for a random walk, and works well for many economic and financial series.Seasonal naiveEach future value is the last observed value from the same season: next March = last March.DriftThe last value plus the average change per step so far: a straight line through the first and last points, extended.

How does it work?

They need no fitting beyond an average, so they cannot overfit and they run on anything. They also mark out what a model has to add: a method that cannot beat seasonal naive on seasonal data has learned nothing useful about the season. Hyndman and Athanasopoulos use these four as benchmarks throughout their book.

Each benchmark gets one thing right. Drift gets the growth but not the season; seasonal naive gets the season but not the growth. Combining the two beats all four: repeating 1958 and adding the average yearly growth gives an MAE of about 30. The methods in the next sections combine trend and season with more care.

Why does it matter?

In the M4 competition, with 100,000 series, 12 of the 17 most accurate methods were combinations of mostly statistical methods, and all six pure machine learning entries performed poorly. Always report a benchmark next to any model.

Key takeaways

  • Mean, naive, seasonal naive and drift are the standard forecasting benchmarks.
  • Seasonal naive is a strong baseline for seasonal data; naive is strong for random-walk-like data.
  • A model is only worth using if it beats the right benchmark out of sample.

Moving averages and exponential smoothing

Between “the last value” and “the average of everything” lies a dial: how quickly should a forecast forget the past?

What is it?

A moving average forecast is the mean of the last k values. Simple exponential smoothing (SES) is a weighted average of all past values, with weights that shrink geometrically into the past: the newest value gets weight α, the one before α(1 − α), then α(1 − α)², and so on. It was developed in the 1950s by Robert Brown, who applied it to US Navy spare-parts demand, and independently by Charles Holt, whose 1957 report to the Office of Naval Research also covered trends and seasonal data (reprinted 2004). Winters tested Holt’s methods on real data in 1960, which is why the seasonal version is called Holt-Winters (Gardner, 2006).

ℓₜ = α·yₜ + (1 − α)·ℓₜ₋₁
ŷₜ₊ₕ = ℓₜ

ℓ is the smoothed level. The forecast for every future step is the latest level. 0 < α ≤ 1.

How does it work?

Each new observation nudges the level towards itself by a fraction α of the gap. Small α means a slow, smooth level that ignores noise but lags behind real changes. Large α tracks every change and every bit of noise. A k-step moving average makes the same trade with k instead of α. Holt’s method adds a smoothed slope, and Holt-Winters a smoothed seasonal index for each period; together they handle trend and season.

On this series the error is lowest for α around 0.3 to 0.4 (or a window of about 4 weeks), in the middle of the dial: smooth enough to ignore most noise, quick enough to catch the jump. α = 1 is the naive forecast and does worse; very small α takes months to notice the jump. In practice α is chosen in much the same way: software picks the value that minimises the squared one-step errors on the training data.

Why does it matter?

Exponential smoothing is cheap, needs little data and updates as each new value arrives. Its savings in data storage over moving averages led the US Navy to adopt it throughout its inventory systems in the 1950s (Gardner, 2006). Its modern form, the ETS family of state space models, gives the same forecasts plus prediction intervals, and together with ARIMA it is one of the two most widely used approaches to forecasting.

Key takeaways

  • Exponential smoothing is a weighted average with geometrically decaying weights; α sets how fast it forgets.
  • Small α is smooth but slow; large α reacts fast but chases noise; α = 1 is the naive forecast.
  • Holt adds a trend and Holt-Winters a season, with their own smoothing parameters.

Autoregression: regression on the past

If you know linear regression, you already know an autoregressive model. The features are simply earlier values of the series.

What is it?

An autoregressive model of order p, AR(p), predicts the next value as a weighted sum of the last p values plus a constant. The earlier values are called lag features. AR models are the “AR” in ARIMA, the family of models that Box and Jenkins popularised in their 1970 book.

yₜ = c + φ₁·yₜ₋₁ + φ₂·yₜ₋₂ + … + φₚ·yₜ₋ₚ + εₜ

c and the weights φ₁ … φₚ are fitted by least squares, exactly as in linear regression.

How does it work?

  1. Build a table. Each row is one time step t: the target yₜ, and the features yₜ₋₁ … yₜ₋ₚ. The first p steps have no full history and are dropped.
  2. Fit. Ordinary least squares on that table gives c and the φ weights. Nothing about it is specific to time series.
  3. Forecast. Plug in the latest p values to predict the next one. For further steps, feed each prediction back in as a lag (more on that below).

For monthly data with a yearly cycle, lags 12 and 13 let the model see the same month last year and the month before it. Any other regression model can be used on the same table, which is how gradient-boosted trees are used for forecasting too.

On the synthetic series the walk-forward error stays above 7 for the first seven lags, then falls as the lags reach back towards last year, and is lowest at 13 lags (about 5.0, against 7.6 for one lag). Beyond that, training error goes on falling, give or take small wobbles, while the test error climbs back above 8 at 36 lags: with 96 training months, 37 weights fit the noise. That is overfitting, exactly as in Overfitting and Regularization. On the airline series, which has 24 more months of history, the test error is lowest at 23 lags and changes little after that: how many lags pay off depends on the series and on how much data there is.

Why does it matter?

Seeing forecasting as regression on lag features opens up the whole machine learning toolbox: add calendar features, holidays, prices or weather as extra columns, regularise the weights, or swap in a tree ensemble. The price is that every feature must be available at the moment the forecast is made, which is the subject of the next section.

Key takeaways

  • An AR(p) model is linear regression of each value on its p predecessors, fitted by least squares.
  • Seasonal lags (12 and 13 for monthly data) let it capture yearly cycles.
  • Too many lags overfit: choose p by out-of-sample error in time order, not training error.

Testing without peeking at the future

A forecasting model can score well in testing and still fail in use, because the test let it see the future.

What is it?

A forecast evaluation must only ever use the past to predict the future. Two habits from ordinary machine learning break that rule: shuffling the rows before splitting, and leakage, where a feature quietly contains information from after the forecast time.

How does it work?

Hold out the end of the series, not a random sample. Better still, use rolling-origin (walk-forward) evaluation: pick a forecast origin, train on everything before it, forecast the next step or steps, then move the origin forward and repeat. Averaging over many origins gives a more reliable error than a single holdout (Tashman, 2000). The training window can expand, as here, or slide with a fixed length.

Leakage hides in features too

Even with a proper time split, a feature can carry the future in: a centred moving average (it averages days after the target), a scaler or imputer fitted on the full dataset, a “days until churn” column, or the actual weather on the forecast day instead of the forecast available the evening before. The test is simple: could this number have been known at the moment the forecast was made?

Why does it matter?

A leaky evaluation does not just overstate accuracy; it can also pick the wrong model, because it rewards the methods best at interpolating. Respecting time order is the same principle as keeping a test set unseen in Model Evaluation, applied to data where “unseen” means “later”.

Key takeaways

  • Never shuffle a time series before splitting: hold out the most recent period.
  • Rolling-origin (walk-forward) evaluation repeats the honest test at many origins.
  • Leakage is any feature not known at forecast time; check every column.

Scoring forecasts: MAE, MAPE and MASE

An error measure decides which model wins, so it has to suit the data. MAPE, the most commonly used percentage measure, has a nasty trap.

What is it?

MAE is the average size of the errors, in the series’ own units. RMSE squares before averaging, so it punishes big misses more. MAPE averages the errors as a percentage of the actual values. MASE, proposed by Hyndman and Koehler, divides the MAE by the in-sample MAE of the one-step naive forecast on the training data; for seasonal data the seasonal naive forecast is used instead.

MAE = mean |eₜ|
MAPE = 100 × mean |eₜ / yₜ|
MASE = MAE / mean |yₜ − yₜ₋ₘ| (on training data)

eₜ = yₜ − ŷₜ is the forecast error. The MASE denominator uses the training data, with m = 1 (naive) or the season length (seasonal naive).

How does it work?

  • MAPE’s problems. It is undefined when an actual value is 0 and explodes near 0, which rules it out for intermittent demand. It also depends on where zero is: the same errors in temperatures look very different in °C and kelvin. And it treats over- and under-forecasts differently: forecasting 150 for an actual 100 is a 50% error, forecasting 100 for 150 only 33%. An under-forecast can never cost more than 100%, while an over-forecast can cost any amount.
  • MASE’s fix. Scaling by a benchmark’s in-sample error makes it unit-free, so it compares across series, and it never divides by an individual actual value. Below 1 means smaller errors than the naive method made one step ahead on the training data.

The MASE here is 2.49, above 1, even though seasonal naive was the best benchmark. That is not a contradiction: the denominator is the error of seasonal naive one step ahead on the training years, while the test forecasts reach up to 24 months ahead in a growing series. MASE values are comparable between methods on the same horizon, not a verdict on their own.

Why does it matter?

MAPE is popular because percentages feel intuitive, but because over-forecasts can cost more than under-forecasts, choosing models by MAPE tends to reward forecasts that run low, and it blows up on products with zero-sale days. Choose the measure from the decision: MAE when units matter, RMSE when big misses are costly, a scaled error such as MASE to compare across many series.

Key takeaways

  • MAE and RMSE are in the series’ own units; RMSE weighs big misses more.
  • MAPE breaks near zero, depends on where zero is and is asymmetric.
  • MASE scales errors by a naive benchmark’s in-sample error, so it is unit-free and zero values do not break it.

Forecasting further ahead

A forecast for tomorrow and a forecast for next year are different problems. The further ahead, the wider the honest range.

What is it?

A multi-step forecast predicts several future values from one origin. A prediction interval gives a range that should contain the future value with a stated probability, such as 80% or 95%. Unlike the point forecast, it says how much to trust it.

How does it work?

The recursive strategy uses a one-step model repeatedly, feeding each prediction back in as a lag. The direct strategy trains a separate model for each horizon. Either way, errors compound: each step ahead adds another unknown shock. For the naive method, assuming uncorrelated errors, the forecast standard deviation grows as σ√h after h steps. For other models, a general way to get intervals is to simulate: run the model forward many times, each time adding a randomly drawn past residual at every step, and read off the spread of the simulated futures.

ŷₜ₊ₕ ± 1.96 · σ · √h

Naive method, normal errors with one-step standard deviation σ: the 95% interval h steps ahead.

The 80% band is about 36 thousand passengers wide one month ahead and about 110 wide three years ahead. Of the 36 real months, 29 fall inside the 80% band and 35 inside the 95% band: close to the stated rates. All seven months outside the 80% band fall below it, in 1958, a year in which traffic grew only about 3%, after about 12% the year before. Bands like these hold the fitted model fixed, so they leave out uncertainty about its coefficients and the chance that the pattern itself changes.

Why does it matter?

Decisions depend on the range, not just the middle: how much safety stock to hold, how many spare generators to keep warm. A forecast without an interval invites overconfidence, and for most series an interval that does not widen with the horizon is too narrow. The M4 competition evaluated prediction intervals as well as point forecasts.

Key takeaways

  • Multi-step forecasts are made recursively (feed predictions back) or directly (one model per horizon).
  • Uncertainty compounds, so prediction intervals widen with the horizon.
  • Simulating futures from the model’s own residuals gives intervals for almost any model.

Neural forecasters and foundation models

The neural forecasters in this section learn from many series at once, rather than fitting each series on its own.

What is it?

Recurrent networks read a series step by step and carry a hidden state, so they can learn their own lag features. Transformers attend to any past step directly. Foundation forecasters are large models, usually transformers, pretrained on huge collections of series and then used zero-shot on a series they have never seen.

How does it work?

Global recurrent modelsDeepAR trains one recurrent network on a large number of related series (say, every product in a store) and outputs a forecast distribution (Salinas et al., 2020). The M4 winner was a hybrid of exponential smoothing and LSTM recurrent networks (Smyl, 2020).Language-model styleChronos, from a team at Amazon and several universities, scales and quantises values into tokens, trains an off-the-shelf language-model transformer (T5) on them, and forecasts by sampling one token at a time (Ansari et al., 2024).Patch-based decodersTimesFM, from Google Research, reads the history in patches of 32 values and from each one predicts the next 128, after pretraining on a large corpus of real and synthetic series (Das et al., 2024).

Underneath, DeepAR, Chronos and TimesFM are still autoregressive: predict what comes next from what came before, then feed it back. The difference is that the lags, their weights and their interactions are learned from far more data than one series could provide.

Why does it matter?

For a single short series, the methods earlier in this lesson are often as accurate and far cheaper to run; in M4 none of the six pure machine learning entries beat the benchmark that averages three exponential smoothing methods. Neural and foundation models are most useful with many related series, many covariates, or no time to tune a model for each series. Whatever the model, the same rules apply: beat the benchmarks, test in time order, and report intervals.

See how a recurrent network carries its hidden state step by step through a sequence.How attention lets a model look back at any earlier step directly.

Key takeaways

  • Recurrent networks and transformers learn their own lag features from data.
  • Foundation forecasters such as Chronos and TimesFM are pretrained on many series and used zero-shot.
  • They help most with many related series; benchmarks and time-ordered tests still decide.

Check your understanding

Six forecasting situations. Each asks you to apply an idea from the lesson.

Question 1 of 6

A retailer’s data scientist predicts daily sales with gradient boosting. She shuffles three years of days, holds out 20% at random and reports an error of 4%. In production the error is 15%. What most likely went wrong?

Next, try fitting lines and curves by least squares in the Regression Lab, or see sequence models at work in the RNN lab.

References

The books, papers and data behind the methods and claims in this lesson.

References

  1. [1]

    Time Series Analysis: Forecasting and Control (5th edition)(opens in a new tab)

    George E. P. Box, Gwilym M. Jenkins, Gregory C. Reinsel & Greta M. Ljung, 2015

    Wiley. First published by Box and Jenkins in 1970: autoregressive and moving-average (ARIMA) models, autocorrelation, and Series G, the monthly airline passenger totals used in this lesson.

  2. [2]

    Forecasting: Principles and Practice (3rd edition)(opens in a new tab)

    Rob J. Hyndman & George Athanasopoulos, 2021

    OTexts, free online. The standard practical textbook: decomposition, the simple benchmark methods, exponential smoothing, ARIMA, time series cross-validation, accuracy measures and prediction intervals.

  3. [3]

    AirPassengers: Monthly Airline Passenger Numbers 1949-1960 (R datasets package)(opens in a new tab)

    R Core Team, 2026

    R documentation page, accessed November 2026. The classic Box and Jenkins airline data: monthly totals of international airline passengers, 1949 to 1960, in thousands. The 144 values embedded in this lesson match this series.

  4. [4]

    The M4 Competition: Results, findings, conclusion and way forward(opens in a new tab)

    Spyros Makridakis, Evangelos Spiliotis & Vassilios Assimakopoulos, 2018

    International Journal of Forecasting 34(4), 802–808. The headline findings: 12 of the 17 most accurate methods were combinations of mostly statistical approaches, a hybrid statistical and machine learning method was the most accurate, and the six pure machine learning methods all performed poorly.

  5. [5]

    Forecasting seasonals and trends by exponentially weighted moving averages(opens in a new tab)

    Charles C. Holt, 2004

    International Journal of Forecasting 20(1), 5–10. A reprint of Holt’s 1957 report to the Office of Naval Research (ONR Memorandum 52, Carnegie Institute of Technology), which developed exponential smoothing for series with trends and with seasonality.

  6. [6]

    Forecasting sales by exponentially weighted moving averages(opens in a new tab)

    Peter R. Winters, 1960

    Management Science 6(3), 324–342. Tested Holt’s exponential smoothing methods on real data; the seasonal method became known as Holt-Winters.

  7. [7]

    Exponential smoothing: The state of the art—Part II(opens in a new tab)

    Everette S. Gardner Jr., 2006

    International Journal of Forecasting 22(4), 637–666. A review whose early history covers Brown’s work for US Navy inventory systems, Holt’s unpublished 1957 memorandum, and Winters’ 1960 tests that gave Holt-Winters its name.

  8. [8]

    Out-of-sample tests of forecasting accuracy: an analysis and review(opens in a new tab)

    Leonard J. Tashman, 2000

    International Journal of Forecasting 16(4), 437–450. How to design out-of-sample tests: series-splitting rules, fixed versus rolling origins and windows, single versus multiple test periods. Rolling-origin evaluation with multiple test periods makes the tests more reliable.

  9. [9]

    A note on the validity of cross-validation for evaluating autoregressive time series prediction(opens in a new tab)

    Christoph Bergmeir, Rob J. Hyndman & Bonsoo Koo, 2018

    Computational Statistics & Data Analysis 120, 70–83. For purely autoregressive models of a stationary series, ordinary K-fold cross-validation is valid when the model’s errors are uncorrelated; if a model underfits and leaves correlated errors, it can underestimate the error.

  10. [10]

    Another look at measures of forecast accuracy(opens in a new tab)

    Rob J. Hyndman & Anne B. Koehler, 2006

    International Journal of Forecasting 22(4), 679–688. Compares accuracy measures, shows that many of them (percentage errors among them) break down in common situations such as zero values, and proposes the mean absolute scaled error (MASE): errors scaled by the in-sample MAE of the one-step naive forecast.

  11. [11]

    The M4 Competition: 100,000 time series and 61 forecasting methods(opens in a new tab)

    Spyros Makridakis, Evangelos Spiliotis & Vassilios Assimakopoulos, 2020

    International Journal of Forecasting 36(1), 54–74. The full account of the M4 competition, which evaluated prediction intervals as well as point forecasts on 100,000 series.

  12. [12]

    DeepAR: Probabilistic forecasting with autoregressive recurrent networks(opens in a new tab)

    David Salinas, Valentin Flunkert, Jan Gasthaus & Tim Januschowski, 2020

    International Journal of Forecasting 36(3), 1181–1191. One autoregressive recurrent network trained on a large number of related series, producing a forecast distribution rather than a single number.

  13. [13]

    A hybrid method of exponential smoothing and recurrent neural networks for time series forecasting(opens in a new tab)

    Slawek Smyl, 2020

    International Journal of Forecasting 36(1), 75–85. The winning submission to M4: exponential smoothing and LSTM recurrent networks combined in one hybrid, hierarchical model.

  14. [14]

    Chronos: Learning the Language of Time Series(opens in a new tab)

    Abdul Fatir Ansari et al., 2024

    Transactions on Machine Learning Research (2024); arXiv:2403.07815. From a team at Amazon and several universities: series are scaled and quantised into tokens, T5-family language models are trained on them, and forecasts are sampled token by token. Evaluated on 42 datasets, including zero-shot on datasets not seen in training.

  15. [15]

    A decoder-only foundation model for time-series forecasting(opens in a new tab)

    Abhimanyu Das, Weihao Kong, Rajat Sen & Yichen Zhou, 2024

    Proceedings of the 41st International Conference on Machine Learning (ICML 2024), PMLR 235, 10148–10167. TimesFM, from Google Research: a decoder-only transformer that reads the series in patches, pretrained on real and synthetic series and used zero-shot.

Related