Forecasting means predicting the next values in a sequence: tomorrow’s sales, next week’s electricity demand, next month’s sign-ups. It looks like any other prediction problem, but time changes the rules. The patterns repeat with the clock and the calendar, and the future must never help predict the past. Start with a simple baseline, and test every model the way you’ll use it: on days after the ones it learned from. Here you’ll forecast a café’s coffee sales four ways, then watch a model ace a test it should have failed.
What’s in a time series#
A time series is one measurement taken at regular intervals, here the number of cups a café sells each day. Most business series are built from the same few parts:
- Trend: the slow drift up or down. This café grows about 15% a year, from around 200 cups a day.
- Seasonality: patterns that repeat on a fixed cycle. Here there’s a weekly rhythm, with Saturday the busiest day and Sunday the quietest, and a yearly one: a little busier in the cold months.
- Events: one-offs and holidays. The café is closed on Christmas Day.
- Noise: ordinary day-to-day luck, a few per cent either way.
Baselines first#
Before building anything clever, try the simplest forecasts, because they are surprisingly hard to beat. The figure below has three of them, plus Holt-Winters, a classic method developed by Charles Holt and Peter Winters around 1960 that keeps a running estimate of the level, the trend and the weekly pattern, and updates each a little as every new day arrives. Methods of this kind are called exponential smoothing, because recent days count most and older ones fade away.
Predict first
Forecasting a café’s sales for the next four weeks, which simple rule do you expect to do best?
Forecasting 28 days ahead from 24 different starting days, “same as today” misses by 40.1 cups a day on average, the four-week average by 27.6, and copying the same day last week by 16.7. Holt-Winters does best, at 14.1, which is 15% better than copying last week. That’s the bar a fancier model has to clear. If a model can’t beat “same day last week”, it hasn’t learned anything worth deploying.
Notice too that from the starting day the figure opens on, Holt-Winters is slightly worse than copying last week: 19.3 cups against 18.9. A single forecast is one roll of the dice. Testing from many starting days, each time using only the past, is called backtesting, and it’s the honest way to compare methods.
Never let the future leak in#
In most machine learning, you test a model by holding back a random 20% of the data. Try that on a time series and something goes quietly wrong. Here’s a flexible model that is told only the date. To predict a day, it averages the 4 nearest days it was trained on that fall on the same weekday.
Predict first
Tested on a random 20% of days, the model misses by 11 cups a day, better than Holt-Winters. Tested on the last 20% of days, the actual future, how far off will it be?
Shuffled, the model misses by 11.2 cups a day and looks like the best forecaster on the page. Tested on the future, it misses by 27.6, worse than copying last week. It hasn’t changed; only the test has. A random split let it peek at the days around each answer.
The same leak gets in through features. A seven-day average centred on each day, a monthly total, a customer’s lifetime spend: anything computed with data from after the moment of the forecast tells the model something it won’t know in real use. Build each feature from the past only, and split by time. scikit-learn’s TimeSeriesSplit does the splitting for you: it always trains on earlier data and tests on later data, the same idea as the backtest above.
Beyond the basics#
- Machine learning with lag features. Turn the series into an ordinary table: for each day, yesterday’s sales, the same day last week, the last month’s average, the weekday, the weather, any promotions. Then train a model such as gradient-boosted trees on it.
- Many series at once. In the M4 forecasting competition in 2018, on 100,000 series, pure machine learning methods did worse than the standard statistical ones, and the winner combined exponential smoothing with a neural network. In M5 in 2020, forecasting Walmart’s sales, gradient-boosted trees (mostly LightGBM) dominated, trained across many related products at once. Classic methods are strong on a single series; machine learning shines with lots of related series and extra information.
- Forecast a range, not a number. The café’s manager deciding how many staff to roster on Saturday needs to know how busy it might plausibly get, not just the most likely number. Most forecasting tools can produce prediction intervals: a range expected to contain the real value, say, 90% of the time.
In code#
A café much like the figure’s, and the two leading methods, with statsmodels (pip install statsmodels pandas). The last four weeks are held back as the future:
import numpy as np
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
rng = np.random.default_rng(0)
days = pd.date_range("2025-01-01", periods=730, freq="D")
weekly = np.array([0.95, 1.0, 1.0, 1.02, 1.1, 1.25, 0.8])[days.dayofweek] # Monday first
growth = 1 + 0.15 * np.arange(730) / 365
sales = pd.Series(200 * growth * weekly * rng.normal(1, 0.06, 730), index=days)
train, test = sales[:-28], sales[-28:] # the last four weeks are "the future"
same_day_last_week = np.tile(train.iloc[-7:].to_numpy(), 4)
holt_winters = ExponentialSmoothing(train, trend="add", seasonal="add", seasonal_periods=7).fit().forecast(28)
def miss(forecast):
return np.mean(np.abs(test.to_numpy() - np.asarray(forecast)))
print(f"same day last week: {miss(same_day_last_week):.1f} cups a day")
print(f"Holt-Winters: {miss(holt_winters):.1f} cups a day")
# same day last week: 17.2 cups a day
# Holt-Winters: 12.5 cups a dayHere statsmodels picks the smoothing settings by fitting them to the training data; the figure uses fixed ones. This is a single four-week test, one roll of the dice: for a real decision, backtest from many starting points, as the figure does.
What to remember
- Time series combine trend, repeating seasons, one-off events and noise; simple rules like “same day last week” capture a lot of that.
- Always compare against a baseline, and backtest from many starting points using only the past.
- Never shuffle a time series for testing, and build features only from data available at the moment of the forecast.