Forecasting Many Related Time Series with Quantiles
A forecast of 12 units next Tuesday is hard to act on. Stocking 12 or 20 depends on what a shortfall costs against a surplus, and a point forecast says nothing about either. A forecast of quantiles does: a 50% chance of selling 12 or fewer, a 95% chance of selling 20 or fewer. This post shows how to produce and check such forecasts for many related series: the loss to train on, the baselines to beat, what a hierarchy changes, and how to tell whether the intervals can be trusted.
I used these methods in M5 Forecasting - Uncertainty (2020), where our team finished 34th of 907 with a silver medal. I have also built forecasting at work: outcome forecasting for several sports at a data-science consultancy, and time-series forecasting for real-time attack detection at Cisco. The numbers below come from a small synthetic lab, not from those projects or from M5. In the lab a quantile model beat two strong baselines on most levels and lost on one.
In short
- Train and score quantile forecasts with the pinball loss. Its expected value is lowest at the true quantile, so it rewards honest quantiles and nothing else.
- Intermittent series at the bottom of a hierarchy and smooth aggregates at the top need different care. Quantiles do not add: in the lab's toy case, summing 50 series' 90% quantiles gave 50 against 31 for the 90% quantile of their total.
- Start with a seasonal baseline plus the quantiles of its own past errors. In the lab, a 4-week seasonal mean did better than seasonal naive on every level.
- A pooled quantile boosting model had the lowest weighted loss over five seeds (0.164, against 0.176 for the 4-week mean and 0.206 for seasonal naive), but the highest loss at the single total series.
- An equal-weight average of the three methods was best only at the total (0.145). It did not beat boosting at the other three levels or overall (0.169 against 0.164).
- Check coverage per quantile and per level, not only the loss, and read it with the data's zeros in mind.
Why a point forecast is not enough
Stock decisions are asymmetric. An empty shelf loses a sale. A spare unit costs storage and perhaps spoilage. The right amount to hold is a quantile of demand, not its mean. If a missed sale costs three times a spare unit, the target is the 75% quantile: the level where the chance of running short is one in four. Server capacity, staffing and cash buffers work the same way.
So the output should be quantiles per series and per day. Two quantiles bound a prediction interval: the 0.025 and 0.975 quantiles bound a 95% interval. With good quantiles the user gets the median, the interval and any level between.
Quantiles and the pinball loss
The pinball loss (also called quantile loss) scores a forecast q of the τ-quantile against an outcome y:
ρτ(y, q) = τ · (y − q) if y ≥ q, (1 − τ) · (q − y) if y < q
Under-forecasting costs τ per unit. Over-forecasting costs 1 − τ. At τ = 0.9, being 1 unit too low costs 0.9 and being 1 unit too high costs 0.1, so the best forecast sits where about one outcome in ten lies above it. At τ = 0.5 both rates are equal and the loss is half the absolute error.
Why does it pick out the quantile? Raise q by a small amount. The loss falls by τ per unit on the outcomes above q and rises by 1 − τ per unit on those below. In expectation the loss changes at the rate F(q) − τ, where F is the distribution function. That rate is negative while F(q) is below τ and positive after, so the expected loss is lowest where F(q) = τ. A loss with this property is called consistent for the quantile. Squared error is lowest at the mean and absolute error at the median. The pinball loss does the same job for every other quantile. The lab checks it on a skewed sample:
def pinball(y, q, tau):
d = y - q
return np.where(d >= 0, tau * d, (tau - 1.0) * d)
grid = np.linspace(0, 12, 1201)
best = grid[np.argmin([pinball(y, g, tau).mean() for g in grid])]
# best is within 0.05 of np.quantile(y, tau), and for tau != 0.5 not the mean
A worked example. The table scores the lab's learned forecast for one item-level series, on the first five of its 28 test days, at three of the nine quantiles. Forecasts are rounded to one decimal and the losses are computed from the rounded values, so every row can be checked by hand. On day 1 the outcome is 2 and the 0.25 forecast is 2.5. The outcome is below the forecast, so the loss is (1 − 0.25) × (2.5 − 2) = 0.375.
| Day | Outcome | q 0.25 | Loss | q 0.5 | Loss | q 0.75 | Loss |
|---|---|---|---|---|---|---|---|
| 1 | 2 | 2.5 | 0.375 | 4.3 | 1.150 | 5.9 | 0.975 |
| 2 | 4 | 2.5 | 0.375 | 4.3 | 0.150 | 6.0 | 0.500 |
| 3 | 5 | 2.8 | 0.550 | 4.6 | 0.200 | 6.5 | 0.375 |
| 4 | 4 | 3.3 | 0.175 | 5.0 | 0.500 | 7.2 | 0.800 |
| 5 | 7 | 3.4 | 0.900 | 4.9 | 1.050 | 7.4 | 0.100 |
| Mean, days 1 to 5 | 0.475 | 0.610 | 0.550 | ||||
| Scaled, 28 days | 0.177 | 0.250 | 0.247 |
The last row is the scaled loss, SPL, from the unrounded forecasts over all 28 days: the mean pinball loss divided by the series' mean absolute one-day change in the training data (3.51 in the lab for this series). Scaling lets series of very different size be averaged together.
The M5 Uncertainty setup
These facts are from the organisers' guide (see Sources). The data are Walmart unit sales: 3,049 products in 3 categories and 7 departments, sold in ten stores in three US states, with daily history from 2011-01-29 to 2016-06-19. The series form a hierarchy of 12 aggregation levels and 42,840 series, from one total down to 30,490 product-store series. Participants had to provide "28 days ahead point forecasts (PFs) for all the series of the competition, as well as the corresponding median and 50%, 67%, 95%, and 99% prediction intervals (PIs)". That makes nine quantiles per series and day: 0.005, 0.025, 0.165, 0.25, 0.5, 0.75, 0.835, 0.975 and 0.995. The guide adds that, for the first time, the competition "focuses on series that display intermittency, i.e., sporadic demand including zeros".
The score is a scaled pinball loss, SPL, per series and quantile u, where h = 28 is the horizon and n the length of the training history:
SPL(u) = [ (1/h) Σt=n+1..n+h ρu(Yt, Qt(u)) ] / [ (1/(n−1)) Σt=2..n |Yt − Yt−1| ]
The denominator is the mean absolute one-step change of the series in training, counted only from its first non-zero sale. The ranking score, WSPL, is a weighted average over series and over the nine quantiles, "divided by nine", and lower is better:
WSPL = (1/K) Σk=1..K Σi in level k wi · (1/9) Σj=1..9 SPLi(uj), wi = dollarsi / Σlevel k dollars
Here dollarsi is the series' unit sales times price over the last 28 training days. The weights "sum to one at each aggregation level", "all hierarchical levels are equally weighted" (K = 12 in M5, 4 in the lab), and "no special weights are assigned to the examined quantiles". A method cannot win on the 30,490 bottom series alone, or by ignoring the tails.
What we did in M5
M5 was a team entry with one teammate. I tried three approaches. LightGBM quantile models and a point forecast with quantiles of its errors were early experiments; Keras neural networks trained with the pinball loss are what went into the final blend. Each approach has its own section in this post: the boosted models in A learned quantile model, the network's loss in Quantiles and the pinball loss, and the point forecast with error quantiles in Baselines that are hard to beat.
Our team write-up (see Sources) lists the networks behind the final blend: two stacked GRU sequence models and two dense networks, each ending in nine linear outputs, one per M5 quantile, and trained on a quantile loss, plus a public Keras quantile-regression baseline. The preprocessing and the starting network designs came from two public kernels by Ulrich GOUE, which we built on.
The GRU models worked well. Each stacks three GRU layers of 400 units (410 in the second model), with dropout of 0.5 between them and a context input joined back in after the first two layers. The last layer keeps one output per step of the sequence, and a dense layer turns each step into nine linear outputs, one per quantile. They were trained with Adam on a weighted quantile loss, and the learning rate dropped by a factor of 5 whenever the validation loss stalled for 5 epochs. From the write-up, in Keras:
x = L.GRU(400, return_sequences=True)(x)
x = L.Dropout(0.5)(x)
x = L.Concatenate()([x, context]) # the context input, joined back in
x = L.GRU(400, return_sequences=True)(x)
x = L.Dropout(0.5)(x)
x = L.Concatenate()([x, context])
x = L.GRU(400, return_sequences=True)(x)
preds = L.Dense(9, activation="linear")(x) # nine quantiles per step
model.compile(loss=wqloss, optimizer="adam")
Nine outputs from one network share everything below the last layer, which is cheaper than nine separate models. A linear output layer does not force the nine into order, so check for crossings and sort, as the lab does for its booster. The two dense networks in the blend used the same nine-output head on three layers of 500 or 400 units, with a plain quantile loss.
Our final submission was a plain average of six of the team's submissions, two of them mine. For every series, quantile and day, the submitted value was the mean of the six:
q̂τ,t = (1/6) Σm=1..6 q̂(m)τ,t
The average keeps the quantiles in order: if every input gives a lower value for a lower quantile, so does their mean. Equal weights also need no fitting, so they cannot overfit a public leaderboard that covers only a short window. The lab uses its own small numpy booster, not LightGBM, and has no neural network.
Hierarchies: sparse at the bottom, smooth at the top
A retail hierarchy counts the same sales several ways: by product and store, by product, by store, by state, in total. The bottom series are small counts. One analysis of the M5 data finds it "faces strong overdispersion and sporadic demand, especially zero demand" (Ziel, see Sources). The top series are large and have no zero days.
The lab builds the same shape at a smaller scale: 40 items sold in 5 stores give 200 bottom series, 40 item series, 5 store series and 1 total, 246 in all. Bottom demand is a Poisson count with a weekly pattern, a small trend, a store-wide daily shock, an occasional promotion hitting one item in every store, and per-cell overdispersion.
This changes the loss by level. At the bottom the median is often 0 and the information sits in the upper quantiles. At the top no day is zero, so the low quantiles are not stuck at 0. One forecaster has to handle both, which is why M5 scored each level separately and equally.
Quantiles do not add up
The mean of a sum is the sum of the means, so point forecasts add up a hierarchy. Quantiles do not. The 90% quantile of a total is not the sum of its parts' 90% quantiles, because the parts are unlikely to all run high on the same day. The extreme case, from the lab's tests: 50 independent series, each Poisson with mean 0.5 a day.
Each series has a 10% quantile and a median of 0, so those sums are 0, while the total's are 19 and 25. At 0.9 each series' quantile is 1, so the sum is 50 against 31. Positive correlation narrows the gap, but only series that always move together close it.
So do not forecast the bottom and add up the quantiles. Either forecast each level's quantiles directly, as the lab does, or simulate joint scenarios from the bottom up and take quantiles of the simulated sums. The next table shows what summing does to a real forecast. It adds the 200 bottom-level forecasts for each quantile and uses the sum as the total's quantile. Values are the mean observed share at or below the forecast.
| Nominal quantile | Boosting, forecast directly | Boosting, sum of 200 bottom quantiles | 4-week mean, forecast directly | 4-week mean, sum of 200 bottom quantiles |
|---|---|---|---|---|
| 0.025 | 0.00 | 0.00 | 0.04 | 0.00 |
| 0.25 | 0.06 | 0.00 | 0.32 | 0.00 |
| 0.5 | 0.48 | 0.01 | 0.53 | 0.14 |
| 0.75 | 0.85 | 0.99 | 0.75 | 1.00 |
| 0.975 | 1.00 | 1.00 | 0.98 | 1.00 |
For the learned model, the summed 0.25 quantile had an observed share of 0.00 and the summed 0.75 quantile 0.99, against 0.06 and 0.85 when forecast directly. The summed band is so wide that the range from 0.25 to 0.75 holds almost every outcome. The 4-week mean baseline shows the same pattern.
Baselines that are hard to beat
Before any learned model, build the cheapest forecast that can work: a point forecast plus quantiles of its own past errors. Take a seasonal reference: the value seven days earlier (seasonal naive), or the mean of the same weekday over the last four weeks. Compute its errors r = y − ŷ over the training history and take their empirical quantiles Qτ(r) per series. Then:
qτ(t) = max(0, ŷt + Qτ(r))
ref = mean of the same weekday over the last 4 weeks # per series and horizon step
res = y[t] - mean(y[t-7], y[t-14], y[t-21], y[t-28]) # in-sample errors
Q[u] = max(0, ref + quantile(res, u)) # one value per quantile
It needs no fitting beyond a few quantiles. It copes with zeros, because the error distribution contains them. And its band width is what the reference actually missed. Its weaknesses: the error spread is the same on every day and horizon step, and it sees one series only.
A learned quantile model
The next step is a global model that learns from all series at once. The lab's is a gradient-boosted tree model, fitted separately for each of the nine quantiles. Each round fits a small tree to the gradient of the pinball loss (τ where the outcome is above the forecast, τ − 1 where it is below) and sets each leaf to the τ-quantile of the residuals inside it. One model is trained on all four levels pooled, with each target divided by the series' recent mean. Features are the weekday, the horizon step, the level, the log of the scale, recent averages, the mean of the last four and eight same weekdays, the last same weekday's value and the share of zeros in the last 28 days. Forecasts are sorted afterwards so that quantiles never cross.
The booster trains only on days before the forecast origin, using many earlier origins so that every horizon step from 1 to 28 appears. Nothing from the 28 test days enters training, the baselines' error distributions or the scaling. The same recipe works with LightGBM's quantile objective, or with a neural network trained on the pinball loss with one output per quantile.
Calibration: reading a coverage plot
A low pinball loss is necessary, not sufficient. Coverage asks whether each quantile does what its name says. For N outcomes yi and forecasts qi(τ):
coverage(τ) = (1/N) Σi 1[ yi ≤ qi(τ) ], interval coverage = coverage(0.975) − coverage(0.025)
For the 0.9 quantile, about 90% of outcomes should fall at or below it. Plot the observed share against each nominal τ. A calibrated forecast lies on the diagonal. A curve above it means the quantile sits too high for its level. A curve below means it sits too low. If the lower quantiles are too low and the upper ones too high, the intervals are too wide. The reverse means they are too narrow.
Two cautions. Read each level separately: a model can be calibrated on the total and wrong at the bottom. And with count data, zeros limit coverage at low quantiles. If 51% of days are zero, a forecast of 0 for the 0.25 quantile has an observed share of at least 0.51. That is not a flaw in the forecast. The pinball loss handles it correctly, but the coverage plot needs reading with the share of zeros in mind.
A small lab you can run
The lab is synthetic and uses numpy: the hierarchy above, training on 420 days, testing on the next 28, the nine M5 quantiles and five seeds. Download the lab (zip), then run python run_lab.py (about 70 seconds) and python -m pytest -q (16 tests). Each test checks a claim against the alternative it rejects: the pinball minimiser is the quantile and not the mean; a sum of quantiles is not the quantile of the sum; the booster recovers a known quantile; the learned model has the lower weighted loss and is closer to nominal on the bottom and item levels. Two tests record unfavourable results: the learned model is worse at the total, and the equal-weight average does not beat boosting except at the total. A further test checks the numbers quoted in this post against the saved results.
The first table gives the scaled pinball loss, averaged over the nine quantiles and over each level's series, as mean and standard deviation over the five seeds. "Weighted" is the M5-style score: dollar-weighted within each level, averaged over the four levels. Lower is better; the lowest in each column is in bold.
| Method | Item-store | Item | Store | Total | Weighted |
|---|---|---|---|---|---|
| Seasonal naive + empirical quantiles | 0.237 ± 0.007 | 0.223 ± 0.017 | 0.207 ± 0.017 | 0.160 ± 0.038 | 0.206 ± 0.023 |
| 4-week mean + empirical quantiles | 0.197 ± 0.005 | 0.183 ± 0.011 | 0.176 ± 0.016 | 0.150 ± 0.026 | 0.176 ± 0.017 |
| Quantile boosting | 0.167 ± 0.006 | 0.164 ± 0.010 | 0.160 ± 0.018 | 0.171 ± 0.023 | 0.164 ± 0.017 |
The learned model had the lowest weighted loss, 0.164 against 0.176 for the 4-week mean and 0.206 for seasonal naive. It beat the 4-week mean in each of the five seeds. The gain is largest at the bottom: 0.167 against 0.197 and 0.237 on item-store series. It reverses at the single total series, where the 4-week mean was best (0.150 against 0.171). One guess is that the pooled model sees one total series among 246 and has not learned a narrow enough band for it. The lab does not test that. One series over 28 correlated days is weak evidence either way.
By quantile, boosting is lowest at all nine quantiles at the bottom. At the total, boosting is lowest at the median only (0.308 against 0.322 for the 4-week mean and 0.340 for seasonal naive) and highest in the tails.
The next table gives the mean absolute gap between observed share and nominal level over the nine quantiles. Smaller is closer to calibrated.
| Method | Item-store | Item | Store | Total |
|---|---|---|---|---|
| Seasonal naive + empirical quantiles | 0.244 ± 0.025 | 0.070 ± 0.016 | 0.020 ± 0.006 | 0.031 ± 0.016 |
| 4-week mean + empirical quantiles | 0.216 ± 0.025 | 0.049 ± 0.010 | 0.023 ± 0.006 | 0.046 ± 0.011 |
| Quantile boosting | 0.202 ± 0.027 | 0.037 ± 0.006 | 0.023 ± 0.008 | 0.081 ± 0.006 |
Boosting was closest to nominal at item-store and item level (0.202 and 0.037, against 0.244 and 0.070 for seasonal naive). At store level the three were within 0.003 of each other. At the total it was furthest, 0.081 against 0.031: its total quantiles were too wide, with an observed share of 0.06 at the 0.25 quantile and 0.97 at 0.835. The item-store gaps are large for every method, mostly because of the zeros.
The last table sets the three methods side by side.
| Method | Assumes | Cost | Did well in the lab |
|---|---|---|---|
| Seasonal naive + empirical quantiles | Next week repeats last week; the error spread is the same on every day | No fitting beyond the error quantiles | Closest to nominal coverage at the store and total levels (gap 0.020 and 0.031) |
| 4-week mean + empirical quantiles | The weekday average of 4 weeks is the centre; the error spread is the same on every day | As above | Lowest loss at the total (0.150); lower than seasonal naive on every level |
| Quantile boosting | Series share patterns, so one pooled model can learn from all of them | Nine models on 60,000 training rows; the whole lab run, scoring included, took 13 s a seed | Lowest loss at item-store, item and store levels and in the weighted score; closest coverage at item-store and item |
Averaging the methods
Our M5 submission was an equal-weight average (see above). The lab tests the same idea on three methods of unequal strength. For every series, quantile and day, the forecast is the mean of the seasonal naive, 4-week mean and quantile boosting forecasts. Nothing is fitted, and the average of ordered quantiles stays ordered. It is scored like the others, over the same five seeds.
| Level | Equal-weight average | Quantile boosting | 4-week mean | Seasonal naive | Seeds beating boosting | Seeds beating all three |
|---|---|---|---|---|---|---|
| Item-store | 0.194 ± 0.006 | 0.167 ± 0.006 | 0.197 ± 0.005 | 0.237 ± 0.007 | 0 of 5 | 0 of 5 |
| Item | 0.179 ± 0.012 | 0.164 ± 0.010 | 0.183 ± 0.011 | 0.223 ± 0.017 | 0 of 5 | 0 of 5 |
| Store | 0.168 ± 0.017 | 0.160 ± 0.018 | 0.176 ± 0.016 | 0.207 ± 0.017 | 0 of 5 | 0 of 5 |
| Total | 0.145 ± 0.023 | 0.171 ± 0.023 | 0.150 ± 0.026 | 0.160 ± 0.038 | 5 of 5 | 2 of 5 |
| Weighted | 0.169 ± 0.018 | 0.164 ± 0.017 | 0.176 ± 0.017 | 0.206 ± 0.023 | 0 of 5 | 0 of 5 |
The average beat the 4-week mean and seasonal naive on every level. It did not beat boosting at item-store, item or store level in any seed, and its weighted loss was 0.169 against 0.164. At the total it was the lowest of all four (0.145), below boosting in all five seeds and below the best of the three in two. Its coverage gaps were 0.210 at item-store, 0.041 at item, 0.020 at store and 0.047 at the total. One possible reason for the weaker result is that two of the three members are weaker, and an equal weight pulls the average towards them. The M5 average combined six submissions, and the lab says nothing about how they compared with each other.
What I would check first
- The share of zero days at each level. It decides which quantiles carry information and what a coverage plot can show.
- A seasonal baseline with empirical error quantiles, before any model. In the lab the 4-week mean beat seasonal naive on every level.
- The loss at each level, not only the weighted score. Boosting won three levels and lost the total.
- Coverage per quantile and per level, with the zeros in mind.
- The total's quantiles, forecast directly. Summed bottom quantiles gave observed shares of 0.00 and 0.99 at 0.25 and 0.75.
- Several seeds or windows, with the spread and the paired wins. One 28-day window of one series is thin evidence.
- An equal-weight average of your own methods. It costs nothing, but in the lab it helped at the total only.
Limits of this post
- The data are synthetic: Poisson demand with a weekly pattern, shocks and promotions. Real retail data have holidays, price changes, stock-outs and a start and end for each product. The lab shows the logic of the checks, not scores to expect on real data.
- One 28-day horizon is scored per seed, and the total is a single series, so its numbers are noisy. Five seeds are few; the spreads shown are standard deviations over them.
- The booster is a small numpy implementation with fixed settings and no tuning. A tuned LightGBM, a neural network or a distributional model such as a negative binomial could do better.
- The post says nothing about how the winning M5 methods worked or ranked.
- Coverage is measured against the lab's own synthetic future, so it checks calibration on that data only.
Sources
- S. Makridakis, E. Spiliotis, V. Assimakopoulos et al., M5 Competitors Guide, M5-methods repository, Mcompetitions on GitHub (2020): series, levels, horizon, quantiles, SPL and WSPL, quoted above.
- F. Ziel, M5 Competition Uncertainty: Overdispersion, distributional forecasting, GAMLSS and beyond, arXiv:2107.06675 (2021): overdispersion and zero demand in the M5 data.
- M5 Forecasting - Uncertainty, Kaggle: the competition's home page.
- 36th Position Solution, our team's write-up, Kaggle (2020): the models behind the final blend. It was written before the final standings; Kaggle lists the final place as 34th.