Level 3 In-Depth AI · Classical Machine Learning
Time Series Forecasting
Predicting future values of something measured over time, such as sales, demand, traffic or temperature. Split the signal into trend and seasonality, turn the past into features, and test honestly by never letting the model see the future.
- Level
- ●●●●● Easy
- Reading
- 15 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 9 concepts →
- Quiz
- 5 questions ↓
Read first
Linear RegressionThis leads to
—The full path from zero — 9 concepts before this one
- What Is AI?
- Derivatives and Slopes
- Vectors
- How Machines Learn
- Partial Derivatives and Gradients
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- Time Series Forecasting
Read them roughly in this order. See it on the concept map →
Why it matters
A supermarket must decide tonight how much bread to bake for tomorrow. A power company must decide how much generating capacity to switch on for the evening peak. A hospital must staff next week's shifts. A cloud provider must buy servers for next year's traffic. Each of these needs a forecast: a prediction of a future value of something measured over time.
A time series is a sequence of measurements in time order: daily sales, hourly electricity load, monthly unemployment, a sensor reading every second. Forecasting predicts its future values, usually with some idea of uncertainty.
Time series look like ordinary Supervised Learning problems, and that is the trap. Two things make them different:
- The order matters. Today's value depends on yesterday's. Rows are not independent, so many standard tricks (shuffling, random splits) quietly break.
- You predict the future from the past. Any information from after the moment of prediction that leaks into training or features makes the model look brilliant in testing and fail in production.
This chapter covers the classic structure of time series (trend and seasonality), simple baselines you must always beat, turning a series into a table of lag features so any regression model can forecast, ARIMA briefly, gradient boosting on time series, and how to test without leaking the future.
The intuition
Ask an experienced shopkeeper how many umbrellas she'll sell next Saturday. She'll reason roughly like this:
- Level and trend: "We sell about 40 a week, and it's been creeping up as the area grows."
- Seasonality: "Saturdays are always busy; and it's autumn, our rainy season."
- Recent memory: "Last Saturday we sold 12, and the Saturday before 11."
- Special events: "There's a festival in town."
- Uncertainty: "Probably 10 to 15, depending on the weather."
Each of these becomes a part of a forecasting model. The first two describe the shape of the series. The third is what lag features capture. The fourth comes from external data. The fifth is the forecast interval.
Key idea Most time series are trend + seasonality + noise. Forecasting means capturing the first two, from the past only, and being honest about the third. Always compare against a naive baseline, and always test by training on the past and predicting the future.
How it works
Trend, seasonality and noise
- The trend is the long-run direction: growth, decline, or a level that drifts.
- Seasonality is a pattern that repeats with a fixed period: daily (traffic peaks at rush hour), weekly (weekend shopping), yearly (heating in winter). A series can have several at once.
- Cycles are rises and falls without a fixed period, such as business cycles.
- The residual (noise) is what's left: unpredictable variation.
A classic decomposition estimates these parts separately. A centred moving average over one full season (7 days for weekly data) smooths out the seasonality and leaves the trend. Subtract the trend, average what's left for each position in the season (all Mondays, all Tuesdays…), and you have the seasonal pattern. The rest is the residual. The first code example below does exactly this.
Patterns can combine additively (weekends add 15 sales) or multiplicatively (weekends add 15%). Multiplicative patterns grow as the series grows; taking logarithms turns them into additive ones.
Autocorrelation
Autocorrelation is the correlation of a series with a delayed copy of itself. If today's sales correlate strongly with sales 7 days ago, the autocorrelation at lag 7 is high, which reveals weekly seasonality. Plotting autocorrelation against lag (an ACF plot) is the standard way to see which past values carry information. It also tells you which lag features are worth building.
Baselines you must beat
Before any model, compute simple forecasts. They are surprisingly hard to beat, and a model that loses to them is useless.
- Naive forecast: tomorrow equals today. Every future value equals the last observed value.
- Seasonal naive forecast: equals the value one season ago. Next Monday equals last Monday.
- Mean forecast: the average of recent history.
A worked example by hand
Daily sales for two weeks (we will forecast week 2 using only week 1):
| Mon | Tue | Wed | Thu | Fri | Sat | Sun | |
|---|---|---|---|---|---|---|---|
| Week 1 | 100 | 95 | 96 | 97 | 102 | 112 | 115 |
| Week 2 (actual) | 101 | 97 | 97 | 99 | 104 | 113 | 118 |
We measure each forecast by the mean absolute error (MAE): the average size of the errors.
Naive (every day of week 2 = last value, 115): errors are 14, 18, 18, 16, 11, 2, 3. Sum 82, MAE .
Mean (every day = week 1's average, ): errors 1.4, 5.4, 5.4, 3.4, 1.6, 10.6, 15.6. MAE .
Seasonal naive (each day = the same day last week): errors , then 2, 1, 2, 2, 1, 3. MAE .
The seasonal naive forecast is seven times better than the naive one, because it captures the weekly pattern for free. Its errors are all positive, though: week 2 is slightly higher than week 1 every day. That is the trend showing through. A model that adds the trend to the seasonal naive forecast would do better still.
Turning a series into a table: lag features
Most machine-learning models expect a table with feature columns and a target. A time series becomes one by feature engineering on the past:
- Lag features: the value 1 day ago, 7 days ago, 14 days ago, 365 days ago.
- Rolling statistics: the mean, minimum or standard deviation of the last 7 or 28 days.
- Calendar features: day of week, month, day of year, holiday flags.
- External features: price, promotions, weather forecasts. Only values that would actually be known at forecast time.
The target is the value at the time you want to predict. Each row of the table is "everything known at time " paired with "the value at ", where is the forecast horizon: how far ahead you predict. Now any regressor, from Linear Regression to Gradient Boosting: XGBoost and LightGBM, can forecast.
The horizon matters. If you forecast one day ahead, yesterday's value is a legitimate feature. If you must forecast 28 days ahead in one go, the most recent value you will have is 28 days old, so lags shorter than 28 are not available, and including them leaks the future. Common strategies for multi-step forecasts: train one model per horizon, or predict one step and feed predictions back in as lags (recursive forecasting, which lets errors compound).
ARIMA, briefly
Before machine learning took over, the standard statistical approach was ARIMA (autoregressive integrated moving average). It has three parts:
- AR(), autoregressive: predict the value as a weighted sum of its last values, a Linear Regression on its own lags. For example, AR(2): .
- I(), integrated: difference the series times first (work with instead of ) to remove trends.
- MA(), moving average: also use the last forecast errors as inputs.
ARIMA requires the (differenced) series to be stationary: its mean, variance and autocorrelation don't change over time. Differencing removes trends; seasonal differencing () removes weekly patterns, which gives seasonal ARIMA (SARIMA). Its cousin, exponential smoothing (Holt–Winters), forecasts with weighted averages that give recent values more weight, plus trend and seasonal terms. Both work well on single, fairly regular series and give principled forecast intervals. They don't easily use many external features or learn across thousands of related series. In Python they live in the statsmodels package. The call looks like this (not run here, as statsmodels is a separate install):
from statsmodels.tsa.arima.model import ARIMA
model = ARIMA(y, order=(1, 1, 1), seasonal_order=(1, 0, 1, 7)).fit() # y: a pandas Series with a date index
print(model.forecast(steps=14)) # the next two weeks
Gradient boosting on time series
In practice, many forecasting systems in industry use gradient-boosted trees on lag, rolling, calendar and external features, often one global model trained across thousands of related series (every product in every store). In the M5 forecasting competition (2020), on Walmart sales data, LightGBM was at the heart of most of the top solutions.
Trees have one important weakness here: they can't extrapolate. A tree predicts averages of training targets, so if sales keep rising beyond anything seen in training, the tree's forecast goes flat. Fixes: remove the trend first (predict differences or ratios, such as "change since last week"), add a linear model for the trend, or include the trend as an input the trees don't have to reproduce.
Backtesting: test without leaking the future
The single most important rule: train on the past, test on the future. Never use a random Training, Validation and Test Sets or ordinary Cross-Validation on time series.
Backtesting (also called walk-forward or rolling-origin validation) mimics real use: pretend it is some date in the past, train on everything before it, forecast the period after, measure the error, then move the date forward and repeat. scikit-learn's TimeSeriesSplit produces these splits. Leave a gap between training and test periods if, in real life, the latest data arrives with a delay.
Leaks to hunt down:
- Features computed with future data: a rolling mean that includes today's value, or a scaler fitted on the whole series.
- Lags shorter than the horizon, as described above.
- Revised data: economic figures and sales are often corrected later. Train with the values that were known at the time.
In code
First, a classical decomposition from scratch in NumPy, on twelve weeks of synthetic daily sales with a known weekly pattern:
import numpy as np
# Twelve weeks of daily sales (Mon..Sun repeating), with a trend and noise
rng = np.random.default_rng(1)
t = np.arange(84)
weekly_true = np.array([0, -5, -4, -3, 2, 12, 15])
sales = 100 + 0.3 * t + weekly_true[t % 7] + rng.normal(0, 2, 84)
# 1. Trend: a centred 7-day moving average smooths away the weekly pattern
trend = np.convolve(sales, np.ones(7) / 7, mode="same")
trend[:3] = trend[-3:] = np.nan # edges lack a full window
# 2. Seasonality: average detrended value for each day of the week, centred on zero
detrended = sales - trend
season = np.array([np.nanmean(detrended[d::7]) for d in range(7)])
season -= season.mean()
# 3. Residual: whatever trend and seasonality don't explain
resid = sales - trend - season[t % 7]
print("estimated weekly pattern:", season.round(1))
print("true weekly pattern :", (weekly_true - weekly_true.mean()).round(1))
print("trend slope per day :", np.polyfit(t[3:-3], trend[3:-3], 1)[0].round(3))
print("residual std :", np.nanstd(resid).round(2))
# estimated weekly pattern: [-2.1 -7.1 -6.6 -5.7 -0.5 9.7 12.3]
# true weekly pattern : [-2.4 -7.4 -6.4 -5.4 -0.4 9.6 12.6]
# trend slope per day : 0.296
# residual std : 1.63
The decomposition recovers the weekly pattern to within half a unit and the trend of 0.3 per day. Next, a full forecasting comparison with Pandas and Working with Data and scikit-learn: two years of daily sales, lag features, and a five-fold backtest of one-day-ahead forecasts, each fold testing on the 28 days after its training data:
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import TimeSeriesSplit
# Two years of synthetic daily sales: upward trend + weekly pattern + yearly wave + noise
rng = np.random.default_rng(0)
days = pd.date_range("2023-01-01", periods=730, freq="D")
t = np.arange(730)
weekly = np.array([0, -5, -4, -3, 2, 12, 15])[days.day_of_week] # Mon..Sun effect
sales = 100 + 0.05 * t + weekly + 8 * np.sin(2 * np.pi * t / 365.25) + rng.normal(0, 4, 730)
df = pd.DataFrame({"sales": sales}, index=days)
# Features built ONLY from the past: lags and a rolling mean, plus the calendar
for lag in (1, 7, 14):
df[f"lag_{lag}"] = df["sales"].shift(lag)
df["mean_7"] = df["sales"].shift(1).rolling(7).mean()
df["dayofweek"] = df.index.day_of_week
df["dayofyear"] = df.index.day_of_year
df = df.dropna()
X, y = df.drop(columns="sales"), df["sales"]
models = {"linear regression": LinearRegression(),
"gradient boosting": HistGradientBoostingRegressor(random_state=0)}
scores = {name: [] for name in ["naive (yesterday)", "seasonal naive (last week)", *models]}
for train, test in TimeSeriesSplit(n_splits=5, test_size=28).split(X): # always train on the past
y_te = y.iloc[test]
scores["naive (yesterday)"].append(mean_absolute_error(y_te, X["lag_1"].iloc[test]))
scores["seasonal naive (last week)"].append(mean_absolute_error(y_te, X["lag_7"].iloc[test]))
for name, m in models.items():
m.fit(X.iloc[train], y.iloc[train])
scores[name].append(mean_absolute_error(y_te, m.predict(X.iloc[test])))
for name, s in scores.items():
print(f"{name:27} MAE {np.mean(s):.2f}")
# naive (yesterday) MAE 7.40
# seasonal naive (last week) MAE 4.49
# linear regression MAE 3.66
# gradient boosting MAE 4.26
Note .shift(1) before .rolling(7): the rolling mean for day uses days to , never day itself. The noise we added has a standard deviation of 4, which puts a floor of about 3.2 on the achievable MAE. Linear regression gets closest, and gradient boosting comes in behind it, barely beating the seasonal naive baseline. Here the true pattern really is linear (a straight trend plus fixed weekday effects), and the trees can't extrapolate the rising trend past the training period. On real data with promotions, holidays, prices and thousands of related series, boosting usually wins. The lesson is to always compare against baselines and simple models instead of assuming.
Common pitfalls
- Random splits and shuffled cross-validation. The classic time-series mistake. It leaks the future and inflates scores. Use backtesting.
- Features that peek. Rolling windows that include the current value, scalers fitted on the whole series, lags shorter than the forecast horizon. Build every feature as if standing at the forecast date.
- Skipping the baselines. If your model doesn't beat seasonal naive, it isn't helping. Report the baseline every time.
- Trees and trends. Tree models predict flat beyond their training range. Detrend, difference, or add a linear component.
- Ignoring uncertainty. A single number hides risk. Bakeries and power grids care about the chance of running short. Produce intervals or quantile forecasts (gradient boosting supports quantile loss).
- Structural breaks. A pandemic, a new competitor or a price change can make the past a poor guide to the future. Monitor forecast errors and retrain (see Monitoring and Data Drift).
- Scale-dependent metrics across series. An MAE of 10 is tiny for a product selling 10,000 a day and enormous for one selling 5. Use relative metrics such as MAPE (with care near zero) or MASE (error divided by the seasonal naive error).
Watch out If any feature uses information from after the moment of prediction, your backtest will look excellent and your production forecasts will not. Check every feature by asking: "Standing at the forecast date, would I actually know this value?"
Where it leads
- Global models train one model on many related series, sharing patterns across products or stores. This is usually far better than one model per series.
- Deep learning for forecasting. Recurrent networks, LSTMs and transformer-based forecasters learn directly from sequences. As of late 2026, pretrained "foundation models" for time series, such as Amazon's Chronos and Google's TimesFM, forecast new series without training, though tuned gradient boosting remains a strong competitor on many business problems.
- Anomaly detection on time series: forecast the next value and flag big surprises. See Anomaly Detection.
- Probabilistic forecasting: predict full distributions, not just single values, for planning under uncertainty.
- Causal questions ("what will sales be if we cut the price?") need more than forecasting. They need experiments or causal inference.
A bit of history
Exponential smoothing was developed in the late 1950s by Robert Brown, for inventory control in the US Navy, and by Charles Holt; Peter Winters added seasonality in 1960. George Box and Gwilym Jenkins systematised ARIMA modelling in their 1970 book Time Series Analysis: Forecasting and Control, which shaped the field for decades. The M-competitions, run by Spyros Makridakis since 1982, repeatedly compared forecasting methods on thousands of real series. A recurring finding was that simple methods were hard to beat. That changed in the M4 (2018), where a hybrid of exponential smoothing and neural networks won, and the M5 (2020), where gradient-boosted trees dominated. The textbook Forecasting: Principles and Practice by Hyndman and Athanasopoulos, freely available online, has become the standard introduction.
Try it
- In the hand example, build a "seasonal naive plus trend" forecast: last week's value for the same day, plus the average daily increase between week 1 and week 2 that you would have estimated from earlier data. Assume earlier weeks showed growth of about 1.5 per day of the week, week on week. What MAE do you get?
- In the backtest code, add
lag_28andmean_28features. Does the error change?- Harder: change the backtest to forecast 7 days ahead: drop
lag_1andmean_7(they wouldn't be known yet) and shift every feature by 7 instead of 1. How much worse do all the methods get?Hint for 1: each forecast becomes week 1's value + 1.5, giving errors of 0.5, 0.5, 0.5, 0.5, 0.5, 0.5 and 1.5.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Forecasting: Principles and Practice (3rd edition)
The standard friendly textbook on forecasting: decomposition, exponential smoothing, ARIMA and evaluation. Free online (examples in R).
Kaggle Learn: Time Series
A short hands-on course on trend, seasonality, lag features and hybrid forecasting models in Python.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
scikit-learn User Guide
Excellent documentation that doubles as a textbook, with explanations and examples for every algorithm.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/time-series.md