Guide to AI and Data Courses · Lecture Notes

Chapter 29: Time Series Analysis and Forecasting

A supermarket chain wants to know next week's milk sales. It has daily sales figures going back years, but these are not independent samples drawn at random; they are measurements that follow one another. Monday's sales depend on the weekend, and this summer resembles last summer. Time series analysis is the course about using that order: splitting a series into trend, season and noise, measuring how the past influences the future, and giving a forecast together with its uncertainty. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.

Learning outcomes

Series components
Split a series into trend, seasonality and noise; carry out an additive decomposition by hand on a small series.
Differencing
Show by calculation which component the first difference and the seasonal difference remove.
Autocorrelation
Compute the autocorrelation coefficient of a series and follow how the forecast of an autoregressive (AR) model returns to the mean.
Forecasting and validation
Produce forecasts with exponential smoothing, measure the error with a time-based validation and interpret a prediction interval.
Place of the course
State what separates time series analysis from statistics, signal processing, machine learning and deep learning.

29.1What question does the course ask?

How do we find structure in measurements over time and forecast the future?

Time series analysis studies measurements whose order matters: yesterday's value affects today's. The course teaches how to split a series into trend, seasonality and noise, how to model autocorrelation, and how to forecast the future together with its uncertainty.

In probability and statistics we usually assume that observations are independent of each other: the heights in a sample give the same result in whatever order they were drawn. In a time series this assumption collapses. The order of the measurements is itself information: yesterday's temperature says something about today's, and January's sales affect February's. The course treats this dependence not as a flaw but as a resource to be used for forecasting.

Two consequences follow at once. First, we cannot split the data by shuffling: the model is always trained on the past and tested on the future. Second, a forecast is not a single number; uncertainty grows with the horizon, and a forecast given without it is incomplete. Three questions recur throughout the course: what is in the series (trend, season, noise)? How much does the past determine the future (autocorrelation)? How far can we trust the forecast (validation and intervals)?

29.1.1Four components

The classical view splits a series into four parts: the long-run direction, the trend; the seasonality that repeats at a fixed interval (week, month, year); longer, irregular cycles around the trend; and unexplained noise. If the parts add up, the model is additive; if the seasonal swing grows as the series grows, the parts multiply, and taking logarithms turns the product into a sum. The three core sections below build on this split.

29.1.2At a glance

CriterionTime Series Analysis and Forecasting
Approachtime-dependent statistical models
Inputtimestamped measurements
Outputforecast, trend, seasonality
Success measureforecast error (MAE, RMSE)
Math loadmedium-high
Data needslong history

29.2A short history

YearMilestone
1927Yule explains sunspot numbers with an autoregressive (AR) model.
1960The Kalman filter is published: it estimates a hidden state step by step from noisy measurements.
1970Box and Jenkins's book establishes ARIMA models and how to build them.
1982Engle proposes the ARCH model, in which volatility changes over time.
1997Hochreiter and Schmidhuber introduce the LSTM; long dependencies become learnable.
2017Facebook open-sources Prophet, which separates seasonality and holidays.

29.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Trend and seasonalityLong-run direction and regularly repeating cycles.
StationarityMean and variance do not change over time.
Autocorrelation (ACF)Correlation of a series with its own past.
DifferencingRemoving the trend to make a series stationary.
ARIMAAutoregression, differencing and moving average together.
Exponential smoothingA forecast that weights the recent past more.
Prediction intervalA forecast with its uncertainty, not a single number.
Time-based splitThe test set always comes after training; no shuffling.

29.4Trend, seasonality and differencing

The first step in understanding a series is to take it apart. In an additive decomposition we write yt = Tt + St + et: trend, season and remainder. The trend is estimated by a moving average whose window is one season long; each window contains every phase of the season once, so the wave cancels out. The trend is then subtracted from the series and the remainders are averaged for each season: these are the seasonal indices.

Definition 29.1 (Centered moving average)

When the period is even (4 for quarterly data) the window mean falls between two observations. To fix this, the two ends get half weight: Tt = (½yt−2 + yt−1 + yt + yt+1 + ½yt+2) / 4.

Example 29.1: Decomposing three years of quarterly data

Quarterly sales for three years (the values are illustrative): 12, 18, 14, 8 | 16, 22, 18, 12 | 20, 26, 22, 16.

  1. Trend. T3 = (6 + 18 + 14 + 8 + 8)/4 = 13.5; T4 = (9 + 14 + 8 + 16 + 11)/4 = 14.5. In the same way T3…T10 = 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 19.5, 20.5: the trend rises by 1 per quarter. Two values are missing at each end.
  2. Detrended series. The values y − T for t = 3…10 are 0.5, −6.5, 0.5, 5.5, 0.5, −6.5, 0.5, 5.5.
  3. Seasonal indices. The two values of each quarter agree, so the averages are Q1 = 0.5, Q2 = 5.5, Q3 = 0.5, Q4 = −6.5. They sum to 0.5 + 5.5 + 0.5 − 6.5 = 0, so no further centering is needed. The fourth quarter lies 6.5 below the trend every year.
  4. Forecast. If the trend continues at the same rate, T13 = 23.5 and T14 = 24.5. The first two quarters of year four: 23.5 + 0.5 = 24 and 24.5 + 5.5 = 30.

The noise came out as exactly zero in this illustrative series; in real data the remainders are small but nonzero.

Decomposition is for understanding the series. Before fitting a model we often need to make the series stationary, that is, to obtain a series whose mean does not drift over time. The shortest route is differencing: y′t = yt − yt−1. With seasonality we use the seasonal difference: yt − yt−4 (for quarterly data).

Example 29.2: What does differencing remove?

Apply both differences to the series above.

  • First difference (yt − yt−1): 6, −4, −6, 8, 6, −4, −6, 8, 6, −4, −6. The trend is gone, but the values still repeat every four steps; the season remains.
  • Seasonal difference (yt − yt−4): 4, 4, 4, 4, 4, 4, 4, 4. The season is gone; what is left is the constant 4, the yearly rise of the trend.
Common mistake

Believing the first difference also removes seasonality. In the example above the first difference carries the seasonal shape (6, −4, −6, 8) over unchanged. For a seasonal series, take the seasonal difference first; if a trend remains, apply the first difference after it. Differencing more than necessary is harmful too: it inflates the noise.

29.5Stationarity, autocorrelation and autoregression

A series is stationary if its mean, its variance and its relationship with its own past do not change over time. That is what lets a pattern learned in one period be assumed valid in another; classical models such as the ARIMA family are built on this assumption. A series with trend or seasonality is not stationary; differencing, logarithms and decomposition are used to bring a series closer to it.

The structure of a stationary series is shown by its autocorrelation: the correlation of the series with a lagged copy of itself. For lag k the autocorrelation coefficient is the sum of products of deviations from the mean divided by the sum of squared deviations.

Definition 29.2 (Autocorrelation coefficient)

rk = Σt=k+1…n (yt − ȳ)(yt−k − ȳ) / Σt=1…n (yt − ȳ)2. rk lies between −1 and 1; its plot against the lag is called the ACF. If there is nothing but noise, the coefficients stay within roughly ±2/√n.

Example 29.3: Autocorrelation of eight measurements

Series: 3, 5, 4, 6, 8, 7, 9, 10 (n = 8, the values are illustrative).

  1. Mean. ȳ = 52/8 = 6.5; the deviations are −3.5, −1.5, −2.5, −0.5, 1.5, 0.5, 2.5, 3.5.
  2. Denominator. The sum of squared deviations is 12.25 + 2.25 + 6.25 + 0.25 + 2.25 + 0.25 + 6.25 + 12.25 = 42.
  3. Lag 1. The sum of products of neighboring deviations is 20.25; r1 = 20.25/42 ≈ 0.48.
  4. Lag 2. The sum of products two steps apart is 11; r2 = 11/42 ≈ 0.26.
  5. Interpretation. The band is ±2/√8 ≈ ±0.71. Both coefficients lie inside it: in so short a series we cannot tell the dependence from noise.

The simplest autocorrelated model is the first-order autoregression, AR(1): yt − μ = φ (yt−1 − μ) + et. Here μ is the mean of the series and φ is the share of the past carried into the present. If |φ| < 1 the series is stationary and its ACF decays as φk. For forecasting, the expected value of the noise is taken as 0, so the forecast h steps ahead is μ + φh(yn − μ).

Example 29.4: An AR(1) forecast returns to the mean

Let μ = 50, φ = 0.8 and the last observation yn = 60, 10 above the mean.

  1. h = 1: 50 + 0.8 · 10 = 58.
  2. h = 2: 50 + 0.82 · 10 = 56.4.
  3. h = 3: 50 + 0.83 · 10 = 55.12; h = 4: 54.096.

The forecast approaches the mean at every step: the influence of the past melts away by repeated multiplication with φ. If φ is close to 1 the memory is long; if it is close to 0 the model forecasts nearly the mean. With φ = 1 the series is a random walk and not stationary; it must be differenced. The "I" (integrated) in ARIMA stands for exactly this differencing.

Common mistake

Taking a single bar outside the band of an autocorrelation plot as proof of dependence. With a 95% band, even pure noise puts about one lag in twenty outside it. Look at the pattern rather than at single bars: are the first lags significant and decaying smoothly, or is there a spike at every seasonal lag?

29.6Exponential smoothing and testing a forecast

Whatever the structure of a model, what really sets a forecasting method apart is how much it errs when tested on new data. One of the simplest and, surprisingly, strongest methods is exponential smoothing: the forecast of the future is an average of past values with exponentially decreasing weights. The recent past counts more, the distant past less.

Definition 29.3 (Simple exponential smoothing)

ℓt = α yt + (1 − α) ℓt−1, starting from ℓ1 = y1. ℓt is the level of the series; the forecast of the next value is ŷt+1 = ℓt, and the same for later horizons. α lies between 0 and 1: near 1 the forecast clings to the last observation, near 0 it drifts slowly.

Example 29.5: Smoothing and one-step errors

Series: 20, 24, 22, 26, 30, 28, α = 0.5 (the values are illustrative).

  1. Level. ℓ1 = 20; ℓ2 = 0.5·24 + 0.5·20 = 22; ℓ3 = 22; ℓ4 = 24; ℓ5 = 27; ℓ6 = 27.5.
  2. One-step forecasts. For t = 2…6 the forecast is the previous level: 20, 22, 22, 24, 27. The actual values are 24, 22, 26, 30, 28; the errors are 4, 0, 4, 6, 1.
  3. Mean absolute error. MAE = (4 + 0 + 4 + 6 + 1)/5 = 3.0.
  4. Comparison. The "naive" method (forecast = previous value) gives errors 4, 2, 4, 4, 2 and MAE = 3.2. Smoothing is slightly better; but five points are too few for a conclusion, and the difference may be chance.
  5. The future. The forecast of the next value is 27.5. The mean of the squared errors is (16 + 0 + 16 + 36 + 1)/5 = 13.8 and its square root ≈ 3.71. If the errors are taken as roughly normal, the 95% prediction interval is 27.5 ± 1.96 · 3.71 ≈ 27.5 ± 7.3, that is [20.2, 34.8].

The interval says what the single number does not: the forecast is 27.5, but values between 20 and 35 would not be surprising. Because it rests on only five errors, this interval is rough too.

29.6.1Time-based validation

In machine learning, shuffling examples and splitting them into training and test sets is routine. In a time series it is forbidden: the points of a randomly chosen test set fall between their neighbors in the training set, and the model predicts the past while knowing the future. The right way is rolling-origin validation: train on the first k points, forecast the next one, record the error, move the window one step and repeat. The one-step errors above were computed exactly this way: every forecast used only the data before it.

There is a choice of error measure too: MAE is plain and robust to outliers, root mean squared error (RMSE) penalizes large errors more. To compare across series, percentage errors or errors scaled by the naive method are used. Whichever is chosen, every new method is compared with the naive or seasonal naive forecast: a complicated model that cannot beat it is not needed.

Common mistake

Doing operations such as scaling, or taking the mean of the whole series, before the split. The mean and standard deviation must be computed from the training part only; otherwise values from the test period leak into training and the success on the test is false.

29.7How is the course taught?

29.7.1A typical workflow

Visualizeplots,decompositionTransformdifferencing,logarithmChoose modelACF, PACF,AICRollingvalidationtime-basedsplitForecastpoint andinterval
Figure 29.1: A typical workflow in Time Series Analysis and Forecasting

A power company plots hourly consumption, separates the daily and weekly cycles, builds a model that also takes temperature as input, backtests it on past weeks, and gives the next day's load with a 95% prediction interval.

29.7.2Topics over the semester

  1. Components of a series: trend, seasonality, noise
  2. Visualization and STL decomposition
  3. Stationarity, differencing and unit root tests
  4. Autocorrelation and partial autocorrelation
  5. Exponential smoothing and Holt-Winters
  6. AR, MA and ARMA models
  7. ARIMA and seasonal ARIMA (SARIMA)
  8. Regression with external regressors, dynamic models
  9. Forecast evaluation and rolling-origin validation
  10. Volatility models: ARCH and GARCH
  11. State space models and the Kalman filter
  12. Forecasting with machine learning and deep nets

This is a typical semester; the order and coverage vary between universities.

29.7.3Skills you will gain

  • date-indexed data in pandas
  • fitting ARIMA with statsmodels
  • Prophet and sktime
  • designing rolling-origin validation
  • producing and reading prediction intervals

29.7.4Try it yourself

The Try It: Planning Next Summer's Ice Cream slide in the presentation lets you solve a typical problem of this course yourself: An ice cream maker plans the coming months' production from three years of monthly sales. Pick a method and a horizon; the last year's real sales are held out and the forecast is scored on them.

29.8Are you ready for this course?

29.8.1Prerequisites

CourseWhy it is needed
Probability and Statisticsstationarity, autocorrelation, ARIMA
Calculusseries, derivatives and integrals: the language of models and filters
Programmingreading files, handling dates and plotting in Python

29.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you explain mean, variance and the correlation coefficient?Probability and Statistics
Can you fit a linear regression and interpret its coefficients?Machine Learning
Can you compute the sum of a geometric series?Sequences and series from calculus
Can you read a CSV file with a date column in Python and plot it?An intro programming course, then a short pandas tutorial

29.9Neighboring courses

Remote SensingProbability & StatisticsSignal ProcessingDeep LearningTime Series
subfieldbuilds onshares methodsapplication
Figure 29.2: Neighbors of Time Series Analysis and Forecasting and the kind of relation

29.9.1Where it overlaps

RelationCourseShared ground
builds onThis course builds on Probability and Statisticsstationarity, autocorrelation, ARIMA
shares methodsShares methods with Deep Learningrecurrent networks, attention-based forecasting
shares methodsShares methods with Digital Signal Processingfrequency analysis, filtering
shares methodsShares methods with Remote Sensingmultitemporal image series

29.9.2Where it differs

  • Probability and Statistics: Statistics usually assumes independent observations; this course deals with ordered data whose observations depend on each other.
  • Digital Signal Processing: Signal processing filters a signal and looks at its frequencies; this course uses the same tools to forecast the future.
  • Deep Learning: Deep learning offers a powerful family of forecasting models; this course also teaches when a simple model is enough.
  • Machine Learning: ML shuffles examples and splits them at random; here time order is kept and the model is trained only on the past.

29.10In practice

29.10.1Applications

AreaWhat is done
Demand forecastingPlanning sales, stock and production.
Energy loadPower consumption and renewable output.
FinanceVolatility, risk and return models.
Weather and climateTemperature, rainfall and CO₂ series.
Anomaly detectionDeviations in server and sensor metrics.
EconomicsForecasting inflation, unemployment and growth.

29.10.2Risks and ethics

RiskExplanation
Leaking the futureA random split, or scaling with statistics of the whole series, carries future values into training; test scores become fake.
Structural breaksIn the 2020 pandemic, demand and traffic series changed overnight; models that fit the past well were wrong for weeks.
Forecasts without intervalsA single number suggests certainty; stock or energy decisions get made without knowing the uncertainty.
Forecasts that change behaviorWhen everyone acts on the same price or demand forecast, the series moves; a forecast can fulfill or defeat itself.

These issues are discussed in depth in Explainable AI and AI Ethics.

29.10.3Tools and datasets

Tools: pandas, statsmodels, Prophet, sktime, Darts, R forecast / fable.

Well-known datasets: Airline passengers (Box-Jenkins), Sunspot numbers, M4 and M5 competitions, UCI Electricity Load Diagrams, Mauna Loa CO₂ measurements, Jena climate data.

29.11Common misconceptions

Common mistake

Time series data can be tested with a random split.

Future values leak into training; testing always follows time order.

Common mistake

Deep networks beat classic models on every series.

In the M competitions, simple and statistical methods have often been very strong.

Common mistake

A good model gives one correct number.

Forecasts are uncertain; for decisions the prediction interval matters at least as much as the point forecast.

Common mistake

A model that worked in the past always works.

Structural breaks (a pandemic, a crisis) change the series; models must be monitored and refreshed.

29.12Summary

  • In a time series the order of observations is itself information; a series is split into trend, seasonality and noise, and the forecast carries that structure forward.
  • The moving average gives the trend and the seasonal indices give the repeating wave; the first difference removes the trend, the seasonal difference removes the season.
  • In a stationary series autocorrelation measures the influence of the past; an AR(1) forecast returns to the mean at rate φh, and ARIMA adds differencing to this idea.
  • Exponential smoothing gives exponentially decreasing weights to the past; it is simple but strong, and the bar every new method must clear.
  • Testing respects time order (rolling-origin validation); forecasts come with a prediction interval and are compared with the naive forecast.

29.13Test Yourself

  1. A quarterly sales series has trend 44 and seasonal indices +5, +10, −3, −12 in order. What is the additive forecast for the third quarter? Why do the indices sum to 0?

    Answer

    44 + (−3) = 41. The indices describe the wave around the trend; the mean deviation must be zero, otherwise the difference belongs to the trend (here 5 + 10 − 3 − 12 = 0).

  2. Series 5, 8, 12, 17, 23. Find the first and second differences. What kind of trend is it?

    Answer

    First difference 3, 4, 5, 6; second difference 1, 1, 1. Because the first difference grows linearly, the trend is quadratic; because the second difference is constant, differencing twice makes the series stationary.

  3. Series 2, 4, 6, 8. Compute the lag-1 autocorrelation coefficient.

    Answer

    ȳ = 5; deviations −3, −1, 1, 3. Denominator 9 + 1 + 1 + 9 = 20. Numerator (−1)(−3) + (1)(−1) + (3)(1) = 3 − 1 + 3 = 5. r1 = 5/20 = 0.25.

  4. In an AR(1) model μ = 10, φ = 0.5 and the last observation is 14. What are the forecasts for the next three values?

    Answer

    The deviation is 4. h = 1: 10 + 0.5·4 = 12; h = 2: 10 + 0.25·4 = 11; h = 3: 10 + 0.125·4 = 10.5. The forecast approaches the mean, 10.

  5. Simple exponential smoothing with α = 0.3 on the series 10, 20, 10. Find the level after the third observation and the forecast of the fourth value.

    Answer

    ℓ1 = 10; ℓ2 = 0.3·20 + 0.7·10 = 13; ℓ3 = 0.3·10 + 0.7·13 = 12.1. The forecast is 12.1. The low α reacted slowly to the jump of the two observations.

  6. An analyst splits a monthly sales series at random into 80% training and 20% test and finds a very low error. Why is it unreliable, and what is the right way?

    Answer

    The test months fall between neighboring months in the training set; the model knows the values around them (information from the future leaks) and sees an optimistic error. The right way is a time-based split or rolling-origin validation: training always comes before the test. The result should also be compared with the naive or seasonal naive forecast.

29.14After this course

After this course you can move on to frequency analysis with signal processing, transformer-based forecasting with deep learning, and multitemporal satellite images with remote sensing. Econometrics and state space models are natural next steps too.

Related careers: Forecasting analyst, Data scientist, Quantitative analyst, Demand planner, Energy data analyst.

29.15Further reading

  • R. J. Hyndman and G. Athanasopoulos, Forecasting: Principles and Practice (3rd ed., 2021): decomposition, exponential smoothing, ARIMA and rolling-origin validation in a freely readable, practical presentation.
  • G. E. P. Box, G. M. Jenkins, G. C. Reinsel and G. M. Ljung, Time Series Analysis: Forecasting and Control (5th ed., 2015): the source of the method for building ARIMA models.
  • R. H. Shumway and D. S. Stoffer, Time Series Analysis and Its Applications (4th ed., 2017): autocorrelation, AR models, state space and spectral analysis at a more theoretical level.

29.16References

  1. Hyndman and Athanasopoulos, Forecasting: Principles and Practice, 3rd ed., OTexts, 2021.
  2. Box, Jenkins, Reinsel and Ljung, Time Series Analysis: Forecasting and Control, 5th ed., Wiley, 2015.
  3. Shumway and Stoffer, Time Series Analysis and Its Applications, 4th ed., Springer, 2017.
  4. Brockwell and Davis, Introduction to Time Series and Forecasting, 3rd ed., Springer, 2016.

Related pages: Slides · Slides (PDF) · Course page