Module 20

Time Series Analysis

Patterns in sequential data

Understanding Temporal Data

  • 01

    Trend

    Long-term increase or decrease

  • 02

    Seasonality

    Regular periodic patterns

  • 03

    Stationarity

    Statistical properties constant over time

  • 04

    Autocorrelation

    Correlation with lagged values

01

Time Series Components

Decomposing Time Series

Yt = Trend + Seasonal + Residual
Original
Trend
Seasonal
Residual

Time series can be decomposed into three components: Trend (long-term direction), Seasonal (repeating patterns at fixed intervals), and Residual (random noise). Decomposition helps understand what drives the series and improves forecasting by modeling each component separately.

Long-term Direction

Upward Trend
Growing over time
Downward Trend
Declining over time
No Trend
Stationary mean

Trend represents the long-term movement in the series. It can be linear (constant rate of change), exponential (accelerating), or more complex. Identifying trend is crucial for forecasting - extrapolating trend is often the main predictive component for long-horizon forecasts.

Periodic Patterns

Common Seasonal Patterns:
Daily (24h)
Weekly (7d)
Monthly (30d)
Quarterly (90d)
Annual (365d)
Retail Sales Example:
J
F
M
A
M
J
J
A
S
O
N
D

Seasonality is regular, predictable variation that repeats at known intervals. Retail peaks in December, energy use peaks in summer/winter, website traffic drops on weekends. Understanding seasonality allows adjustment and better comparison (year-over-year vs month-over-month).

What's Left Over

Residual = Observed - Trend - Seasonal
Good residuals: Random, mean zero, constant variance, no autocorrelation

Residuals are what remains after removing trend and seasonality. Good model residuals look like white noise - random, centered at zero, constant spread, no patterns. Structured residuals indicate the model is missing something important.

02

Stationarity

What is Stationarity?

Stationary
Mean & variance constant
Non-Stationary
Mean changes over time

A stationary series has constant statistical properties over time: same mean, same variance, same autocorrelation structure. Most time series methods assume stationarity. Non-stationary series (trending, changing variance) must be transformed before analysis.

Importance for Analysis

✗
Non-stationary series can show spurious correlations
✗
Forecasts from non-stationary data are unreliable
✗
Standard statistical tests become invalid
Solution: Transform non-stationary series to stationary through differencing, detrending, or log transformation

Non-stationary series cause problems: two unrelated trending series can appear highly correlated (spurious correlation), forecasts deteriorate quickly, and hypothesis tests give wrong answers. Always check stationarity before modeling.

Making Series Stationary

First Difference: ΔYt = Yt - Yt-1
Original (trending)
→
Differenced (stationary)
d = 1: Remove linear trend
d = 2: Remove quadratic trend
Seasonal diff: Yt - Yt-s removes seasonality

Differencing is the most common way to achieve stationarity. First differencing (d=1) removes linear trends by computing changes between consecutive values. Seasonal differencing removes periodic patterns. Most series need d=1 or d=2 at most.

Augmented Dickey-Fuller Test

ADF Test Hypotheses:
H₀: Series has unit root (non-stationary)
H₁: Series is stationary
p < 0.05
Reject H₀
Evidence of stationarity
p ≥ 0.05
Fail to reject H₀
Likely non-stationary

The ADF test checks for stationarity by testing for a 'unit root' (indicator of non-stationarity). Low p-value means we can reject non-stationarity. Apply differencing and re-test until stationary. Also check KPSS test for confirmation.

03

Autocorrelation

Correlation with Past Self

ACF(k) = Corr(Yt, Yt-k)
Correlation between Y and Y lagged by k periods
Today's value
Yt = 105
↔
Yesterday's value
Yt-1 = 103
High autocorrelation: knowing past helps predict future

Autocorrelation measures how much a series correlates with lagged versions of itself. High autocorrelation at lag 1 means today's value is similar to yesterday's. This is the key feature distinguishing time series from cross-sectional data and the basis for forecasting.

Autocorrelation Function

ACF Plot (Correlogram)
0
1
2
3
4
5
6
Bars = correlation at each lag. Dashed lines = significance bounds.

The ACF plot shows autocorrelation at each lag. Bars exceeding the significance bounds (±1.96/√n) indicate significant correlation. Slow decay suggests trend (needs differencing). Spikes at regular intervals suggest seasonality.

Partial Autocorrelation

PACF: Direct Effect Only
ACF(2)
Yt ↔ Yt-2
Total correlation (includes Yt-1)
PACF(2)
Yt ↔ Yt-2 | Yt-1
Direct effect only
PACF removes intermediate correlations to show only the direct relationship at each lag.

PACF measures correlation at lag k after removing effects of shorter lags. If lag-2 ACF is high just because lag-1 is high, PACF(2) will be near zero. PACF helps identify the true 'memory' of the process - how many past values directly influence the present.

Identifying Models from ACF/PACF

ModelACFPACF
AR(p)Gradual decayCuts off after lag p
MA(q)Cuts off after lag qGradual decay
ARMA(p,q)Gradual decayGradual decay
White NoiseAll near zeroAll near zero

ACF and PACF patterns help identify appropriate models. AR processes show PACF cutoff. MA processes show ACF cutoff. Combined ARMA shows decay in both. White noise (random) has no significant correlations. These patterns guide model selection.

04

ARIMA Models

ARIMA(p, d, q)

ARIMA(p, d, q)
p
AR order
Autoregressive terms
d
Differencing
Integration order
q
MA order
Moving average terms

ARIMA combines three components: AR (autoregressive) uses past values to predict current, I (integrated) handles non-stationarity through differencing, MA (moving average) uses past forecast errors. Together they model a wide range of time series patterns.

Autoregressive Component

Yt = c + φ₁Yt-1 + φ₂Yt-2 + ... + εt
AR(1) Example:
Yt = 10 + 0.7×Yt-1 + εt
Today = 10 + 70% of yesterday + noise
If yesterday was 100, predict: 10 + 70 = 80

AR models predict using weighted past values. AR(1) uses one lag, AR(2) uses two lags, etc. The coefficients φ measure how strongly each lag influences the current value. Values revert toward the mean; the rate depends on φ.

Moving Average Component

Yt = c + εt + θ₁εt-1 + θ₂εt-2 + ...
MA(1) Example:
Yt = 50 + εt + 0.5×εt-1
Today = 50 + this shock + 50% of yesterday's shock
Shocks persist for limited time

MA models use past forecast errors (shocks) to predict. Unlike AR where effects persist indefinitely, MA effects are temporary - an MA(q) shock affects only the next q periods. MA captures short-term dependencies and sudden shifts.

Choosing p, d, q

Step-by-step:
1. d: Difference until stationary (ADF test)
2. p: Look at PACF cutoff (or decay)
3. q: Look at ACF cutoff (or decay)
4. Validate: Check residuals, use AIC/BIC
Common Models:
ARIMA(1,1,0) - Random walk with drift
ARIMA(0,1,1) - Exponential smoothing
ARIMA(1,1,1) - Mixed model

Model selection: (1) Set d by differencing until ADF rejects non-stationarity, (2) Examine PACF for AR order p, (3) Examine ACF for MA order q. Use information criteria (AIC, BIC) to compare models. Lower is better. Always validate with residual diagnostics.

05

Forecasting

Forecasting Approaches

Naive
Ŷt+1 = Yt
Tomorrow = Today
Drift
Ŷt+h = Yt + h×trend
Extrapolate trend
Seasonal Naive
Ŷt+h = Yt+h-s
Same as last season
ARIMA/ETS
Statistical models
Optimal weights

Simple benchmarks often work surprisingly well. Naive (tomorrow = today) beats many complex models. Seasonal naive uses last year's value for same period. Compare your model against these baselines - if you can't beat naive, your model isn't useful.

Prediction Intervals

|← Forecast →
Prediction intervals widen over time as uncertainty accumulates. Short-term forecasts are more reliable than long-term.

Point forecasts are almost always wrong - report prediction intervals. Intervals widen with forecast horizon because errors accumulate. A 95% prediction interval means the true value should fall within those bounds 95% of the time.

Measuring Forecast Accuracy

MAE
Mean Absolute Error = avg(|actual - forecast|)
RMSE
Root Mean Squared Error = √avg(error²)
MAPE
Mean Absolute Percentage Error = avg(|error|/actual)
MASE
Mean Absolute Scaled Error (vs naive)
MASE < 1 means you beat naive forecast

Evaluate forecasts using holdout data (train on past, test on future). MAE is interpretable in original units. RMSE penalizes large errors more. MAPE gives percentage but fails at zero. MASE compares to naive baseline - below 1 means you're adding value.

Common Forecasting Mistakes

✗
Overfitting to past data (too complex model)
✗
Ignoring structural breaks (regime changes)
✗
Forecasting too far ahead
✗
Not updating models with new data
✗
Assuming past patterns will continue

Forecasting pitfalls: Overfit models perform great in-sample but poorly out-of-sample. Structural breaks (policy changes, crises) invalidate historical patterns. Long-horizon forecasts are essentially guessing. Models need regular updating. The future often differs from the past.

★

Real-World Examples

Apply your knowledge to practical scenarios

01

Retail Sales Forecasting

A store has 3 years of monthly sales data. They observe: overall upward trend, peaks every December, and dips every January. Total sales: Year 1: $1.2M, Year 2: $1.4M, Year 3: $1.6M.

Q Identify the three time series components in this data. +
A Trend: Growing ~$200K per year (upward). Seasonality: December peak, January dip (12-month cycle). Residual: Random variation around the pattern.
Q Why would using just the overall average to forecast next December be wrong? +
A It ignores both trend and seasonality. December is always above average (seasonal effect), and sales are growing (trend). The average would seriously underestimate December sales.
Q If December typically accounts for 15% of annual sales, estimate December Year 4 sales. +
A Projected Year 4 total: ~$1.8M (continuing $200K/year trend). December = 15% × $1.8M = $270K. This combines trend extrapolation with seasonal pattern.
Q What could cause this forecast to be wrong? +
A Many factors: economic recession (breaks the trend), new competitor opens, pandemic restricts shopping, supply chain issues, or the trend was actually slowing. Past patterns don't guarantee future results.
Key Insights
  • Decomposition separates trend, seasonality, and noise
  • Forecasts should account for ALL components
  • External events can break historical patterns
02

Are Stock Prices Predictable?

An investor analyzes 5 years of daily stock prices for a major company. They fit a complex ARIMA model and achieve R² = 0.001 on out-of-sample predictions. The naive forecast (tomorrow = today) achieves similar accuracy.

Q Why does the complex model fail to beat the naive forecast? +
A Stock prices approximately follow a random walk—each day's change is essentially unpredictable. If prices were predictable, traders would exploit the pattern until it disappeared. Market efficiency limits predictability.
Q What does R² = 0.001 mean for the sophisticated model? +
A The model explains only 0.1% of price variation—essentially nothing. 99.9% of daily price movement is unpredictable noise. The model adds no value over simply predicting 'no change.'
Q Does this mean technical analysis is worthless? +
A For short-term price prediction, largely yes. Academic evidence consistently shows most technical trading rules don't beat buy-and-hold after accounting for transaction costs. Some weak patterns may exist but are hard to profit from.
Q What time series ARE predictable? +
A Series with strong trends (GDP growth), regular seasonality (electricity demand), or physical constraints (temperature). Competitive markets like stocks make prediction harder because predictability gets arbitraged away.
Key Insights
  • Random walks are fundamentally unpredictable beyond naive forecasts
  • Low R² in forecasting is common—don't expect high accuracy
  • Market efficiency limits financial forecasting
03

The COVID Structural Break

A hotel chain's forecasting model was trained on 2015-2019 data. In March 2020, actual bookings crashed to near zero while the model predicted normal seasonal patterns. The model continued predicting 'recovery' that didn't match reality.

Q Why did the forecasting model fail so dramatically? +
A COVID-19 was a structural break—a fundamental change in the data-generating process. The model assumed historical patterns would continue, but the underlying dynamics completely changed.
Q What is a 'structural break' in time series terms? +
A A structural break is when the statistical properties of the series change permanently or for an extended period. Trends, seasonal patterns, or volatility shift to new values that historical data didn't capture.
Q How should forecasters handle structural breaks? +
A Detect them quickly (monitor forecast errors), acknowledge uncertainty, use shorter recent data, incorporate external information, and communicate that models may be unreliable during regime changes.
Q What's the lesson for all forecasting? +
A All models assume the future resembles the past. Black swan events—rare, impactful, unpredictable—break this assumption. Humility and scenario planning beat false precision.
Key Insights
  • Structural breaks invalidate historical patterns
  • Models fail when the underlying system changes
  • Always ask: 'What could break my assumptions?'
?

Time Series Quiz

Test your understanding • Passing score: 70%

0 of 10 answered
Q1 multiple-choice

Which is NOT a component of time series decomposition?

Explanation: Time series decomposition splits data into Trend, Seasonal, and Residual (error) components. Correlation is a relationship measure, not a decomposition component.
Q2 multiple-choice

A stationary time series has:

Explanation: Stationarity means statistical properties (mean, variance, autocorrelation) don't change over time. A stationary series fluctuates around a constant mean with constant spread.
Q3 multiple-choice

What does ACF (Autocorrelation Function) measure?

Explanation: ACF measures how correlated a time series is with itself at different lags. High ACF at lag 12 means values 12 periods apart are correlated (suggesting yearly seasonality in monthly data).
Q4 multiple-choice

To make a non-stationary series stationary, you might:

Explanation: Differencing removes trends by subtracting each value from the previous one. A random walk becomes white noise after differencing. This is fundamental to ARIMA modeling.
Q5 multiple-choice

In ARIMA(1,1,1), what does the middle '1' represent?

Explanation: ARIMA(p,d,q): p = AR order, d = differencing order, q = MA order. The middle '1' means one difference is taken to achieve stationarity.
Q6 multiple-choice

A naive forecast for tomorrow's value is:

Explanation: The naive forecast predicts tomorrow equals today. It's the simplest possible forecast and is often surprisingly hard to beat, especially for random walk data like stock prices.
Q7 multiple-choice

Why is MASE (Mean Absolute Scaled Error) preferred over raw error measures?

Explanation: MASE scales errors relative to naive forecast errors. MASE < 1 means you beat the naive method. This allows comparison across different series and makes interpretation easier.
Q8 multiple-choice

What is a structural break?

Explanation: A structural break is when the underlying process generating the data changes—trends shift, volatility changes, or relationships alter. Examples: policy changes, crises, market disruptions.
Q9 multiple-choice

Exponential smoothing gives more weight to:

Explanation: Exponential smoothing weights recent observations more heavily, with weights decaying exponentially as data gets older. This makes forecasts responsive to recent changes.
Q10 multiple-choice

For a 12-month seasonal pattern, you would look for significant ACF at lag:

Explanation: Seasonality shows up as significant autocorrelation at the seasonal lag. Monthly data with yearly patterns shows ACF spikes at lag 12 (and possibly 24, 36, etc.).

Quiz Results

0 %

← Bayes' Theorem Next: Clustering →