Introduction: A Forecast Is Only as Good as the Order It Produces
Quick commerce is e-commerce in which the emphasis is on fast delivery, typically in under an hour and, for some services in India, in under ten minutes.1 The promise is kept with geography, not with speed on the road: stock is held in small local warehouses, called dark stores, close enough to the customer that picking and a short ride fit inside the delivery window.1 Business Today counted 6,563 dark stores across India in a February 2026 report, with Swiggy Instamart's stores averaging 4,217 square feet and handling an average of 1,034 orders per store per day.2 A profile of Zepto by Contrary Research, citing press reports, gives a median delivery time of 11 minutes in 2024 over an average distance of 1.5 km, from dark stores replenished by larger mother warehouses.3
That arrangement moves the hard problem from logistics to inventory. A supermarket can absorb a bad forecast in its back room. A dark store of a few thousand square feet cannot, and the engineering blog of Rabbit, an Egyptian quick-commerce company, states the consequence plainly: forecasts have to be made per store and per hour, not as a national average, because a store that holds only a few thousand items has little buffer when a guess is wrong.4
Four constraints shape every system described in this paper:
- The grain is fine. The decision is per SKU, per store and per replenishment cycle. At that grain many items sell zero units on most days, and methods built for smooth aggregate series break.5
- Sales are not demand. When the shelf is empty, sales stop but demand does not. A model trained on recorded sales forecasts low, which orders low, which causes more stockouts.6
- The costs are lopsided. A unit too few and a unit too many cost different amounts, so the right order is a chosen quantile of the demand distribution, not its mean.78
- Levels must agree. The store forecast drives the store order, the city forecast the mother warehouse, and the category forecast procurement. If they do not add up, the supply chain plans against itself.9
The paper follows a number from raw data to a purchase order: the data and how accuracy is scored (Section 1), classical methods for sparse demand (Section 2), global tree and neural models (Section 3), what moves demand and what hides it (Section 4), reconciliation across the hierarchy (Section 5), turning the forecast into an order (Section 6), and a comparison (Section 7).
Quick-commerce companies publish little about their forecasting, so the sources are the academic literature, library documentation, and engineering write-ups from Picnic, Swiggy Instamart, Rabbit, Instacart and Amazon. Where a claim rests on a secondary summary, the text says so.
sales, stock status, prices, promotions, calendar, weather
|
v
1. recover latent demand undo the effect of stockouts
|
v
2. forecast a distribution per SKU, per store, per cycle
|
v
3. reconcile make the levels add up
|
v
4. choose a quantile, order costs decide which quantile
|
v
stock arrives and sells, or runs out
|
+----> sales and stockouts become the next training data
(back to the top)
The loop at the bottom is what separates this from ordinary time-series prediction: the orders the system places determine what can be sold, and what is sold becomes its next training data.
Section 1: The Shape of the Data
1.1 What is being forecast, and for when
The review of the field by Fildes, Ma and Kolassa notes that the SKU is the basic operational unit for daily replenishment, and that good short-term estimates of sales at the SKU-by-store level lead to better customer satisfaction, less waste and more revenue.5 The scale is large even in ordinary retail: Walmart faces over one billion SKU-store combinations.5
Quick commerce pushes the grain finer in time. Rabbit describes forecasting both how much of an item a store will sell and when in the day it will sell, because replenishment windows and picker capacity are planned by the hour.4 A 2023 conference talk on Swiggy Instamart describes daily forecasts per SKU per dark store, with SKU counts on the order of 104.10
FreshRetailNet-50K, a public dataset released in 2025 from a Chinese fresh-grocery retailer, shows what the data looks like at this grain. It holds hourly sales and hourly stock status for 50,000 store-product series: 863 perishable SKUs across 898 stores in 18 cities, over three months in 2024.11 Weekday demand has two intraday peaks, around 9 AM and 4 PM. Demand is concentrated, with 20% of SKUs accounting for 51.8% of transactions. And the stockout rate follows the replenishment clock: under 2% after the 6 AM restock, rising steadily to 26% by 8 PM.11
1.2 A hierarchy in three dimensions
Each bottom-level series sits at the crossing of three hierarchies. Products roll up from SKU to brand to category. Locations roll up from store to city to region. Time rolls up from hour to day to week. The M5 competition, the standard public benchmark for retail forecasting, makes the structure concrete: Walmart unit sales for 3,049 products in 10 stores across 3 US states give 30,490 product-store series at the bottom, and aggregating them by store, state, department and category in every combination gives 42,840 series across 12 levels.12
all stores, all products 1 series
/ \
by state (3) by category (3)
| |
by store (10) by department (7)
| |
+------- crossed -------+------+
|
product x store 30,490 series
(mostly zeros, daily)
12 aggregation levels, 42,840 series in total (M5)
The top is smooth, seasonal and easy to forecast. The bottom is noisy and full of zeros. M5's organisers measured how much the top 50 entries improved on the best statistical benchmark at each level: about 40% on average at the very top, about 23% in the middle, and about 3% at the product, product-state and product-store levels.12 The gains from sophisticated methods were concentrated where forecasting was already easy, and were smallest at the level that orders are placed at.
1.3 Intermittency, and how to classify it
A series is intermittent when many of its periods have zero demand. The standard classification, by Syntetos, Boylan and Croston (2005), uses two numbers. The average demand interval (ADI) is the mean number of periods between two periods with demand, and measures regularity in time. The squared coefficient of variation (CV2) of the non-zero demand sizes measures regularity in quantity.1314 The cut-offs are ADI = 1.32 and CV2 = 0.49, and they are not arbitrary: the authors derived them by comparing the theoretical mean squared error of competing estimators and finding where each one wins.13
The classes are a routing table. Smooth series suit ordinary time-series methods. Intermittent and lumpy series need the methods of Section 2 or a model with a count likelihood.
The class of a series depends on the bucket it is measured in. An item that sells twice a day is smooth at daily grain and intermittent at hourly grain. Moving to hourly forecasts therefore moves a large part of the catalogue to the right-hand side of Figure 1, and that is the main statistical cost of forecasting at the grain quick commerce operates at.
1.4 Sales are a censored view of demand
Point-of-sale data records what was sold, and sales cannot exceed stock. When demand exceeds the inventory on hand, the excess is not recorded. This is the demand censoring effect, and estimates built on sales alone are biased downward for the item that ran out.5 There is a second-order effect: some customers who meet an empty shelf buy a substitute, which inflates the sales of the substitute and biases its estimate upward.5
The DeepAR paper from Amazon describes what happens if the bias is ignored: at best a systematic under-forecast, and at worst a downward spiral in which an out-of-stock leads to a lower demand forecast, lower re-ordering and more out-of-stocks.6
Zeros therefore come in two kinds. A natural zero means nobody wanted the item in that period. An artificial zero means the item could not be bought, because of a stockout, a delisting or a recording error. Svetunkov and Sroginis propose making this the first step of any demand classification: identify the artificial zeros, and only then decide whether what remains is regular or intermittent.15 A dark-store operator is well placed to do this, because it owns the inventory and knows its stock position hour by hour.
1.5 Keeping score
Percentage errors divide by the actual value. When the actual is zero they are infinite or undefined, which rules out MAPE for intermittent series.16 The mean absolute scaled error (MASE), proposed by Hyndman and Koehler, avoids the problem by dividing each absolute error by the in-sample mean absolute error of a naive forecast.16
Absolute errors have a subtler flaw. The forecast that minimises expected absolute error is the median of the distribution, and the median of a series that is zero more than half the time is zero. A metric built on absolute error therefore rewards forecasting nothing. The M5 organisers cite this as the reason for scoring with squared errors, which are minimised by the mean. Their metric, the root mean squared scaled error (RMSSE), was averaged over all 42,840 series with weights proportional to each series' dollar sales, giving the weighted RMSSE, with all twelve aggregation levels weighted equally.12
Three practical rules follow.
- Match the metric to the statistic you need. If the order will be set from the mean, score with squared error. If it will be set from a quantile, score with the quantile (pinball) loss of Section 6.
- Report bias separately. Volume-weighted absolute error (WAPE, also written wMAPE) is the usual headline number, but only a signed error shows whether the system leans towards stockouts or waste. FreshRetailNet's headline finding is in the bias: a model trained on raw sales under-forecast by 7.37%.11
- The backtest is censored too. Instamart's team tracks availability (the share of the day an item could be ordered) and wastage, and found that choosing models by wMAPE against recorded sales was unreliable for both.10
Section 2: Forecasting Sparse Demand
2.1 Croston's method
Simple exponential smoothing applied to a sparse series behaves badly. The estimate jumps after each sale and decays through each run of zeros, so it is highest just after a sale, which is exactly when a replenishment order is likely to be placed. Croston's 1972 answer was to stop smoothing the series and smooth its two components instead: the sizes of the non-zero demands, and the intervals between them.1712
Let q be the sequence of non-zero demand sizes and a the sequence of intervals between them. Each is updated by simple exponential smoothing, and only in a period when a sale occurs. The forecast of demand per period is the ratio of the two smoothed values:17
on a period with demand q_i, arriving a_i periods after the previous one:
size <- size + alpha * (q_i - size)
interval <- interval + alpha * (a_i - interval)
forecast per period = size / interval (unchanged until the next sale)
Croston used a smoothing parameter of 0.1 for both components, initialised with the first observation of each, and that remains the default in common implementations.1718 A worked example: over ten days an item sells 0, 0, 3, 0, 0, 0, 2, 0, 4, 0. The sizes are 3, 2, 4 and the intervals 3, 4, 2. Starting from the first values and smoothing with 0.1, the size estimate moves 3 → 2.9 → 3.01 and the interval estimate 3 → 3.1 → 2.99, so the forecast is 3.01 / 2.99, about 1.01 units per day. The observed average is 0.9.
The method has known limits. Its forecast is a single flat rate for every horizon. It does not correspond to any statistical model, so it has no prediction intervals, and it ignores the fact that the data are counts.17
2.2 The bias, and the Syntetos-Boylan fix
Croston's forecast is biased upward. Dividing one smoothed estimate by another does not give an unbiased estimate of the ratio, and the size of the error depends on the smoothing parameter used for the intervals.1217 Syntetos and Boylan proposed a correction that multiplies the forecast by (1 − α/2), where α is that smoothing parameter.12 With α = 0.1 the factor is 0.95, which is the constant hard-coded in the CrostonSBA model of Nixtla's statsforecast library.18 In the example above the corrected forecast is 0.96 units per day.
2.3 TSB: forecasting the probability of a sale
Croston's method has a second weakness that matters more in a fast-changing assortment. Because it updates only when a sale occurs, an item that stops selling keeps its last forecast indefinitely. The system keeps ordering a product that customers have abandoned.19
Teunter, Syntetos and Babai (2011) replaced the interval with the probability that a period has any demand. The probability is smoothed every period, towards 1 after a sale and towards 0 after a zero, while the size is still updated only on sales. The forecast is the product of the two.1912
every period:
if demand > 0: prob <- prob + beta * (1 - prob)
size <- size + alpha * (demand - size)
else: prob <- prob + beta * (0 - prob)
forecast per period = prob * size
The estimate is unbiased, and it decays during a run of zeros, so the forecast for a dying item falls on its own and can trigger a delisting or a run-down of stock.19
2.4 Aggregating the zeros away
A different approach is to change the bucket. Summing a daily series into weekly buckets removes most of the zeros, and the weekly series can be forecast with ordinary smoothing and then spread back to days. This is the Aggregate-Disaggregate Intermittent Demand Approach (ADIDA). The M5 benchmark implementation sets the bucket to the mean inter-demand interval, and the statsforecast implementation disaggregates with equal weights.1218 IMAPA repeats the exercise at several aggregation levels and averages the results, so that no single choice of bucket has to be right.18
All of these are available off the shelf, for example as CrostonClassic, CrostonSBA, TSB, ADIDA and IMAPA in statsforecast, which makes them cheap baselines.18
Equal-weight disaggregation is the weak point here, because demand within a week and within a day is strongly patterned. Section 5.4 gives a better way to split.
2.5 What these methods leave out
The classical intermittent methods are univariate. Each series is forecast from its own history alone, which fails in three ways that matter here. They cannot use what is known about the future: a promotion next Tuesday, a holiday, a forecast of rain. They cannot say anything about an item with no history. And they give a rate, not a distribution.
The alternative to the last point is to model the count directly. If demand over the period that an order has to cover is treated as a draw from a Poisson or negative binomial distribution, every quantile is available. The negative binomial is the usual choice for sales counts because its variance can exceed its mean, as real sales do.6
Section 3: One Model for Every Series
3.1 Why global models won
A local model is fitted to one series. A global model is one set of parameters fitted to all of them, with each series supplying training examples. One SKU in one store may have a few dozen non-zero days, far too few to learn a weekly pattern, a price response and a holiday effect. Ten thousand SKUs in a thousand stores share those effects, and a model that pools them can learn each from millions of examples.
Amazon's account of its own history shows the operational side. In 2008 its system used textbook time-series methods, which worked for stable products and failed for new and highly seasonal ones. Teams bolted on separate components until, in the words of one of its scientists, the system was incredibly hard to maintain. The way out was a single model, on the observation that products in different categories often behave the same way.20
Pooling brings its own difficulty: scale. The DeepAR authors plotted the sales velocity of millions of Amazon items and found an approximate power law across several orders of magnitude.6 A model trained naively on such data spends its capacity on the scale of the series instead of their shape, and sees the few high-volume items, which matter most to the business, too rarely.
3.2 Gradient-boosted trees
The dominant approach in practice turns forecasting into tabular regression. Each row is one series at one date. The columns are lagged sales, rolling means and counts of recent zeros, calendar fields, price and promotion flags, and identifiers for item, store and category. A gradient-boosted tree model is fitted to predict sales some days ahead.
M5 is the clearest evidence for this recipe. The competition drew 5,507 teams. Only 415 of them, 7.5%, beat the best statistical benchmark, a bottom-up exponential smoothing forecast, which is a warning about how strong simple methods are on sparse data.12 Most of the top methods the organisers examined used LightGBM. The winner averaged LightGBM models trained on three poolings of the data (by store, by store and category, by store and department), each in a recursive and a non-recursive variant, 220 models in all, and beat the best benchmark by 22.4%.12
The detail that transfers most directly is the loss function. The winning models were trained on the likelihood of the Tweedie distribution, chosen because the data have a point mass at zero and a non-negative, strongly right-skewed distribution.12 A Tweedie distribution's variance is proportional to a power p of its mean. At p = 1 it is the Poisson, at p = 2 the gamma, and in between it is a compound Poisson-gamma distribution: a positive probability of exactly zero, and a continuous distribution over positive values.21 LightGBM exposes it as an objective with a log link, with the power set by tweedie_variance_power, which must lie in [1, 2) and defaults to 1.5; values nearer 1 move towards Poisson.22
# LightGBM, mean forecast for sparse counts
params_mean = {
"objective": "tweedie",
"tweedie_variance_power": 1.1, # 1.0 <= p < 2.0; default 1.5
"metric": "rmse",
}
# LightGBM, one model per quantile needed by the ordering policy
params_p80 = {
"objective": "quantile",
"alpha": 0.8, # the quantile; default 0.9
}
Trees have two limits worth knowing. A tree predicts by averaging training targets in a leaf, so it cannot predict outside the range it has seen. Picnic started with gradient-boosted trees and met this during the pandemic, when demand for some products went beyond anything in the training data and the model could not follow.23 The second is horizon. Lag features for a forecast several days ahead are not all known yet, so one must either feed predictions back in as lags (the recursive strategy, where errors compound) or train a separate model per horizon (the direct strategy). The M5 winner averaged both.12
3.3 DeepAR: an autoregressive network with a count likelihood
DeepAR, published by Amazon in 2017, is a recurrent network trained on all series at once that outputs the parameters of a probability distribution for the next step instead of a point value.6 For count data the distribution is negative binomial, parameterised by a mean and a shape. Training maximises the likelihood of the observed values. Forecasting draws a sample for the next step, feeds it back as input, and repeats to the end of the horizon; doing this many times (the paper used 200 sample paths) gives an empirical distribution from which any quantile can be read.6
Two devices deal with the power-law scale problem. Inputs are divided by a per-item scale factor, one plus the item's mean sales, and the likelihood parameters coming out of the network are multiplied back, because counts cannot simply be rescaled in preprocessing. And training windows are sampled with probability proportional to that scale, so high-volume items are not starved.6
Because the output is sample paths, DeepAR gives the distribution of total demand over a multi-day window directly: sum each path, then take the quantile. DeepAR also has an explicit treatment of stockouts: an out-of-stock period is marked as unobserved, its value is replaced by a sample from the model, and its term is dropped from the likelihood.6
3.4 Direct quantile models
The model Amazon describes as its production successor takes a different path to the same end. The multi-horizon quantile recurrent forecaster (MQ-RNN, 2017) encodes the history with a recurrent or convolutional network and then emits, in one shot, the chosen quantiles for every horizon. There is no feedback of predictions, which avoids the error accumulation of recursive forecasting, and no assumed distribution: the network is trained on the quantile loss summed over horizons and quantiles.24 Its training scheme, which the authors call forking sequences, attaches a decoder at every time step of the encoder, so one pass over a series trains on every possible forecast date at once.24
The trade against DeepAR is this. Direct quantile models are trained on the quantity the business uses, and Amazon credits training on quantile loss across horizons as the step that let neural networks overtake its random forest.20 But they give marginal quantiles per horizon, not joint sample paths, so the distribution of a sum over several days must be requested as a separate output.
3.5 The Temporal Fusion Transformer
The Temporal Fusion Transformer (TFT, 2019) is organised around the fact that forecasting inputs come in three kinds: static attributes of the series, time-varying inputs known into the future such as calendar and planned promotions, and time-varying inputs observed only up to now such as past sales.25 It has a separate path for each. Static covariate encoders produce context vectors that condition the rest of the network. Variable selection networks weight the inputs at each time step. A recurrent layer handles local patterns, and an interpretable self-attention layer handles long-range ones. Like MQ-RNN it is trained on quantile loss summed across horizons.25
TFT appears repeatedly in grocery write-ups. Picnic chose it after finding that LSTMs gave no meaningful gain over trees and that DeepAR did not handle its mix of static and time-varying inputs. It runs one TFT for articles and one for deliveries, predicts the 10th, 50th and 90th percentiles, and reports a 20% improvement in forecast precision, with the largest gains on slow-moving articles.23
3.6 Plain networks: N-BEATS, N-HiTS and TiDE
A line of work argues that attention and recurrence are unnecessary. N-BEATS (2019) is a deep stack of fully connected blocks with backward and forward residual links, and took the top results on the M3, M4 and Tourism benchmarks using nothing specific to time series.26 N-HiTS (2022) adds multi-rate input sampling and interpolated outputs, and reports about 20% better accuracy than Transformer models on long horizons at roughly a fiftieth of the computation.27 TiDE (2023), an encoder-decoder built from multilayer perceptrons, takes covariates and runs five to ten times faster than the best Transformer baseline.28
N-BEATS in its original form is univariate and gives point forecasts, which suits the smooth upper levels of the hierarchy. The second-placed M5 team used it that way, with LightGBM for the intermittent bottom level.29 TiDE is a candidate for replacing TFT at lower cost, and Picnic lists it among the models it is evaluating.30
3.7 Pretrained models
The newest option is a model trained once on a large corpus of time series and applied to new series with no training, as language models are. Chronos (Amazon, 2024) scales and quantises series values into a fixed vocabulary of tokens and trains T5-family language-model architectures, from 20 million to 710 million parameters, to predict the next token; sampling tokens gives a probabilistic forecast.31 TimesFM (Google, 2023) is a decoder-only attention model over patches of the series.32
The first generation of these models was univariate, a serious gap for retail, where price and promotion drive much of the variance. That is closing. TimesFM 2.5 regained covariate support, through an interface called XReg, in October 2025, and Chronos-2 handles multivariate series and both past-only and known-future covariates through a group attention mechanism, with its largest reported gains on tasks with covariates.3334
There is one published quick-commerce deployment. According to a summary of a May 2026 post by Swiggy Instamart's team, Instamart moved warehouse SKU forecasting and orders-per-day forecasting to TimesFM used zero-shot, with covariates brought in through ridge regression, and combined it with hierarchical forecasting. The reported results are relative accuracy gains of 21–38% across product categories for warehouse forecasting and, against the previous TFT-based system, a 7.5% improvement in WMAPE with half the runtime for orders per day.35 The original post could not be opened while this paper was researched, so those figures come from the summary and should be read as indicative.
One caution applies. The published results are at aggregated levels (warehouse, city, category), where series are smooth; whether zero-shot models do as well on single-store slow movers is not established by these sources.
Section 4: What Moves Demand, and What Hides It
4.1 Recovering demand from censored sales
There are four broad ways to handle a period in which the item was out of stock. In increasing order of effort:
- Mask it. Treat the period as missing and exclude it from the loss. This is DeepAR's approach.6 It removes the downward bias in training but discards the information that demand was at least as large as sales.
- Scale it up. If the item sold out part-way through the day, divide the day's sales by the share of a normal day's demand that falls in the hours it was in stock. A store that sells out of 10 units at 6 PM, in a store-category where 70% of demand normally arrives by then, is credited with about 14. Fildes and co-authors cite evidence that using the timing of a stockout, not just the fact of one, improves estimation.5
- Model the censoring. A sold-out observation says only that demand was at least the stock level. Statistical treatments use that inequality directly, through nonparametric methods in the Kaplan-Meier tradition or parametric models built on hazard rates.5
- Impute, then forecast. Treat latent demand recovery as its own learning task, fill in the stockout hours, and train the forecaster on the result.
FreshRetailNet-50K quantifies the last approach. With a TFT forecaster, training on recovered demand instead of raw sales cut WAPE from 31.75% to about 29%, and moved the signed error from −7.37% to between 0.57% and 2.58%, depending on the imputation model.11 The bias correction is the point, because a systematic 7% under-forecast compounds through the ordering loop.
Substitution complicates all four. When an item is out, part of its demand moves to a neighbour, so the neighbour's sales that day are inflated.5 The summary of Instamart's system describes forecasting at the level of a group of substitutable SKUs to reduce the variance substitution causes.35
A caution from theory: recovery has limits that no model removes. If a store has never stocked more than ten units of an item, its history contains no information about how often demand exceeds ten. Besbes and Muharremoglu show that censoring creates a tension between ordering what looks optimal and ordering more in order to learn, and that a simple flag recording whether a stockout occurred removes most of the need to explore when demand is discrete.36 Hssaine and Sinclair show that with offline censored data there are regimes where censoring puts a floor under any algorithm's performance however much data it has, and that what can be learned is bounded by the largest quantity ordered in the past.37 The practical reading is that a system which always under-stocks cannot learn its way out from its own data. Occasionally stocking above the forecast is a way of buying information.
4.2 Promotions and price
Promotions are a large, controllable driver of demand, and hard to model. In FreshRetailNet the median uplift from a promotion was 1.43 times baseline, with an interquartile range from 1.05 to 2.06.11
The review literature identifies three complications. Promotions on goods that keep bring forward purchases (the review calls it pantry loading), so a lift is followed by a dip; fresh categories show less of both. They cannibalise: the promoted item takes sales from its neighbours on the shelf. And the variable space is large, since each item can be affected by its own price, its promotion type and those of its substitutes, giving too many variables for too little data.5 The evidence the review cites is that for store-by-SKU demand in promotion-heavy categories, regression-based methods that include these drivers are substantially more accurate than univariate ones.5
4.3 Calendar, events and weather
Calendar effects are the best-understood covariates and still cause trouble, because the important ones are rare. A festival occurs once a year, so even three years of history give three examples. Rabbit lists paydays, Ramadan (which moves demand towards the evening and pre-dawn meals), Eid, national holidays and school calendars, along with local events such as football matches and road closures.4
Weather is a real but uneven effect. In FreshRetailNet, rain was associated with an 11% rise in vegetable demand, which the authors attribute to shoppers substituting away from outdoor markets.11 A study of German stores found that snowfall significantly changed store traffic and sales in food retail, while rain changed traffic only.38
The engineering consequence is that weather is a different kind of input from the calendar. Its future values are themselves forecasts, with error that grows with horizon. Picnic classifies weather as an input whose future is not known with certainty, and validates incoming weather data against plausible ranges before it reaches the model.2330
4.4 Intraday signals, and the cost of a very good feature
At short horizons, the best predictor of today is the part of today that has already happened. Picnic's experience with such a feature is instructive. Its delivery forecast was given the number of deliveries already confirmed for a slot and the minutes remaining before cutoff. It was the model's strongest input, and the team estimates, informally, that it cut next-day error by 20–50%.39 It also multiplied the training data, since every moment of the day is a different snapshot (an estimated 150 million rows, cut to under 30 million by sampling five snapshots a day). It made backtesting depend on reconstructing what was known at each past moment, and it sometimes produced forecasts below the number already booked.39
The lesson generalises. A stateful intraday feature turns forecasting into a point-in-time data problem: the feature store must be able to answer what was known at 14:00 last Tuesday. Without that, the backtest leaks future information.
4.5 New items and new stores
A fast-growing network is always opening stores, and an assortment tuned to each neighbourhood is always adding items. Neither has history. The standard device is borrowing. Rabbit matches a new store to existing stores with similar density, demographics and surrounding retail, and gives a new product the profile of its category and of similar items.4 Global models do the same thing implicitly: a model that takes static attributes as input, as MQ-RNN and TFT do, can produce a forecast for a series it has never seen from its attributes alone.2425
Section 5: Making the Numbers Add Up
5.1 Coherence
Forecast every node of the hierarchy independently and the results will not agree: the sum of the store forecasts for a city will differ from the city forecast. Forecasts that respect the aggregation structure are called coherent.9 Coherence is an operational requirement, because a mother warehouse stocked against the city forecast must be able to fill store orders computed from the store forecasts. It is also a statistical opportunity, because the levels carry different information.
The algebra is compact. Stack every series in the hierarchy into a vector y and the bottom-level series into a vector b. A summing matrix S of zeros and ones encodes the structure, so that y = S b. Every linear way of producing coherent forecasts from a set of independent base forecasts ŷ can be written as9
y_coherent = S G y_base
S : n x m summing matrix (n series in total, m at the bottom)
G : m x n matrix that maps the base forecasts to bottom-level forecasts
The methods differ only in the choice of G.
5.2 Bottom-up, top-down, middle-out
Bottom-up forecasts the bottom level and sums. G selects the bottom-level base forecasts and discards the rest. No information is lost to aggregation, but the bottom-level data are noisy and hard to model, and errors that share a sign add up on the way to the top.9
Top-down forecasts the total and splits it by proportions. The proportions may be the average of historical shares, the share of historical averages, or shares taken from forecasts at each level. Historical proportions do not track changes over time, so these methods tend to be less accurate at the lower levels than bottom-up, and no top-down method gives unbiased coherent forecasts even when the base forecasts are unbiased.9
Middle-out picks a level in between, sums upward from it and splits downward.9
All three use the base forecasts from only one level and throw the others away.
5.3 Optimal reconciliation
Reconciliation methods use every base forecast. The idea is to treat the base forecasts as noisy measurements of a coherent truth and find the coherent set closest to them, where "closest" is weighted by how reliable each forecast is. Wickramasuriya, Athanasopoulos and Hyndman showed that the choice of G that minimises the total variance of the reconciled forecast errors, among unbiased reconciliations, has a closed form.409
G = (S' W^-1 S)^-1 S' W^-1
W : covariance matrix of the base forecast errors
This is minimum-trace reconciliation (MinT). The difficulty is W, which for a retail hierarchy is far too large to estimate freely, so practice relies on approximations:9
Method (min_trace) | Assumption about W | When it fits |
|---|---|---|
ols | Identity. All base forecasts equally reliable | Cheap, and G does not depend on the data. Ignores the difference in scale between levels |
wls_var | Diagonal, from the residual variance of each base model | The common default when residuals are available |
wls_struct | Diagonal, each node weighted by the number of bottom series under it | No residuals available, for example judgmental forecasts |
mint_shrink | Full covariance, shrunk towards its diagonal | Cross-series correlation matters, and there are many more series than time points |
A two-store example shows the mechanics. A city has stores A and B. The base forecasts are 100 for the city, 60 for A and 30 for B. They are incoherent by 10. With OLS weights, reconciliation gives A = 63.3, B = 33.3 and city = 96.7. The gap is shared equally among the three numbers. With variance weights the split would follow reliability: if the city forecast is far more accurate than the store forecasts, as it usually is, the stores absorb most of the adjustment and the city figure barely moves.
MinT forecasts are not guaranteed to be more accurate than the base forecasts for every individual series, but they are more accurate on average.9 In R the whole procedure is a pipeline stage:9
sales |>
aggregate_key(city / store, units = sum(units)) |>
model(base = ETS(units)) |>
reconcile(
bu = bottom_up(base),
mint = min_trace(base, method = "mint_shrink")
) |>
forecast(h = 7)
Nixtla's hierarchicalforecast library offers the same family in Python, along with methods that reconcile whole predictive distributions.41
5.4 Time is a hierarchy too
The same machinery applies along the time axis. Aggregate an hourly series into days and weeks, forecast each frequency separately, and reconcile them. Athanasopoulos and co-authors call these temporal hierarchies, and report that the reconciled forecasts are more accurate than conventional ones, especially when it is unclear which model is right, and that they align short-term operational plans with longer-term ones.42 For quick commerce this is a principled answer to the weakness of ADIDA noted in Section 2.4. The daily total, which is forecastable, anchors the hourly profile, which is not, and the hourly forecasts still add up to the daily number that the order was sized on.
5.5 What practitioners do instead
Published accounts of production systems show several simpler patterns.
Align the bottom to the top. The second-placed M5 team forecast the top levels with N-BEATS and the bottom with LightGBM, then scaled the bottom-level forecasts with multipliers so that their sums lined up with the top-level ones. The authors describe this as a bottom-up method that corrects biases which are hard to see at the bottom level.29
Separate the level you report from the level you model. The summary of Instamart's system describes a dual-hierarchy framework that distinguishes the level at which the business objective is defined from the level at which modelling works best.35
Build coherence into the model. Rangapuram and co-authors put the reconciliation step inside a neural network as a differentiable projection, so the model is trained end to end to produce coherent probabilistic forecasts.43
Section 6: From Forecast to Order
6.1 The newsvendor
The simplest inventory problem is also the closest to a perishable item in a dark store. You choose a quantity once, demand arrives, and whatever is left over at the end is worth little or nothing. This is the newsvendor problem.
The solution comes from a marginal argument. Suppose each unit of unmet demand costs Cu (the underage cost, usually the lost margin) and each unsold unit costs Co (the overage cost, usually the purchase price less any salvage value). Adding one more unit to an order of q gains Cu if demand exceeds q and loses Co otherwise. The optimum is where the two expected effects balance:
P(demand <= q*) = Cu / (Cu + Co) the critical ratio (critical fractile)
q* = F^-1( Cu / (Cu + Co) ) F : cumulative distribution of demand
With a selling price p, a unit cost c and no salvage value, Cu = p − c and Co = c, and the ratio becomes (p − c)/p, the form in which the result is usually quoted.7
An example. An item costs 60 and sells for 100. Unsold units are thrown away. The critical ratio is 40/100 = 0.4, so the best order is the 40th percentile of demand, which is below the median. If demand is roughly normal with mean 50 and standard deviation 20, that is about 45 units. If instead leftovers can be cleared at 30, the overage cost falls to 30, the ratio rises to 40/70 = 0.57, and the best order rises to about 54. Nothing about the forecast changed. Only the economics did.
A low-margin perishable should therefore be deliberately under-stocked relative to its mean demand, and a high-margin or long-lived item over-stocked.
6.2 The quantile is the decision
The connection between forecasting and ordering can be made exact. The quantile loss, also called the pinball loss, for a target quantile τ charges τ per unit when the actual value is above the forecast and (1 − τ) per unit when it is below.4445 The forecast that minimises its expected value is the τ-quantile of the distribution.44
pinball_tau(y, q) = tau * (y - q) if y >= q (under-forecast)
(1 - tau) * (q - y) if y < q (over-forecast)
newsvendor cost = Cu * max(y - q, 0) + Co * max(q - y, 0)
= (Cu + Co) * pinball_tau(y, q) with tau = Cu / (Cu + Co)
The newsvendor's cost is the pinball loss at the critical ratio, times a constant. So a model trained on pinball loss at τ = Cu/(Cu + Co) is trained directly on the cost of its own orders. Picnic states the purpose in the same terms: choosing the quantile lets the team balance waste against unavailability.23
It also explains why evaluating an ordering system on a symmetric accuracy metric misleads. The M5 competition had a second track for exactly this, scoring nine quantiles per series.46
6.3 More than one period: the order-up-to policy
Most items are not thrown away at night, and orders are placed repeatedly. The standard policy for repeated ordering at fixed intervals is order-up-to, or base-stock: at each review, order enough to raise the inventory position to a target level S. Inventory position counts stock on hand plus stock on order, minus anything owed.47 In the textbook base-stock model the optimal target satisfies the same critical-ratio condition as the newsvendor, with the backorder cost b and holding cost h in place of underage and overage: the probability that demand does not exceed S should be b/(b + h).47
The question is: demand over what period? An order placed now arrives after the lead time L. The next chance to correct the position comes one review period R later, and that correction arrives a further L after it. Stock ordered now must therefore cover demand over R + L, the protection interval.
order 1 placed order 1 arrives order 2 arrives
| | |
------+----------------------+-------------+-----------------------+-> time
|<--- lead time L ---->| |<---- lead time L ---->|
|<---------- review period R ------->|
| order 2 placed
|<--------------- protection interval R + L --------------->|
order 1 has to cover all demand until order 2 arrives
Under the textbook assumptions (normally distributed demand, independent between periods, and a fixed lead time) the target is the mean demand over the protection interval plus a safety stock of z standard deviations of that demand. The standard deviation grows with the square root of the interval's length. Wikipedia's treatment gives the lead-time form, with reorder point = L·E(D) + z·σD·√L, and a general form that adds a term for variable lead time.48 Substituting the protection interval for the lead time gives the periodic-review version:
S = mean_daily * (R + L) + z * sigma_daily * sqrt(R + L)
\___________________/ \______________________________/
expected demand over safety stock
the protection interval
z = 1.65 for a 95% cycle service level
Take an item that sells 20 a day with a daily standard deviation of 6. With one delivery a day and a one-day lead time, R + L = 2 and S = 40 + 1.65 × 6 × √2 ≈ 54. With two deliveries a day and a half-day lead time, R + L = 1 and S = 20 + 1.65 × 6 ≈ 30. Halving the protection interval nearly halves the stock needed for the same service level. That arithmetic is the inventory case for frequent replenishment from a nearby mother warehouse.
The textbook assumptions fail in specific ways at this grain, and each failure has a known repair.
- Demand is not normal. A slow mover's demand over two days might average one unit. With a Poisson model, the probability that demand is at most 2 is 0.92 and at most 3 is 0.98, so a 95% target needs S = 3. Lokad's own page on the safety-stock formula now carries a note calling the normal-based approach dysfunctional for real supply chains, because neither demand nor lead time is normally distributed.49
- Days are not independent. Errors are correlated across days: a heatwave or a missed promotion effect lasts. The square-root rule then understates the spread of the total. The repair is to forecast the distribution of the sum over the protection interval directly, either from sample paths, as DeepAR does, or as a separate output of a quantile model.6
- Lost sales, not backorders. The base-stock model assumes unmet demand waits.47 In quick commerce the customer does not wait, and lost-sales models are harder to solve exactly. The newsvendor reasoning still applies as an approximation, with the lost margin as the underage cost.
6.4 Which service level?
"95% service" has at least two meanings, and they lead to different stock levels. The α, or cycle, service level is the probability that a replenishment cycle passes with no stockout. It registers whether a stockout happened, not how much demand was missed. The β service level is the share of demand served from stock on hand, and is the one widely used in practice.50
Instamart's availability metric, the share of the day an item could be ordered, is a third, time-based variant that suits a store open most of the day.10 Whichever is used, a service level is a proxy. The critical ratio derives the target from costs. A service target asserts it. When item economics differ as much as they do between a bag of rice and a punnet of strawberries, one target for both is wrong for both.
6.5 Perishables
Shelf life complicates the multi-period policy. Stock is no longer a single number, because ten units that expire tomorrow are not the same as ten that expire next week. Nahmias's 1982 review of perishable inventory theory covers ordering policies for stock with a fixed lifetime and for stock that decays continuously, under deterministic and random demand, and the optimal and approximate policies known for each.51 The exact problem is hard because the state is the whole age profile of the stock, which is why much of the literature and nearly all practice use approximations.
The practical approximations for a dark store are three.
- For a shelf life of about a day, treat each cycle as a newsvendor (Section 6.1). The overage cost is the full unit cost less whatever a markdown recovers.
- For a shelf life of several days, use an order-up-to policy, but subtract from the inventory position the units expected to expire before they can be sold, given the forecast and the age of the stock.
- Control the issuing order. If the oldest units are picked first, waste is lowest.
For a one-day item, a stockout in the evening is the planned result of a critical ratio below one. The question for the business is whether it arrives at the hour the economics imply.
6.6 Skipping the forecast
If the quantile is the decision, the forecasting step can in principle be removed and a model trained to output the order directly. Oroojlooyjadid, Snyder and Takáč trained a neural network on the newsvendor cost itself, with no demand distribution estimated along the way, and report that it beats forecast-then-optimise approaches, most clearly when demand is volatile.52
Most systems keep the two stages apart for a reason. A forecast serves many consumers (replenishment, procurement, staffing, finance), each with different costs. A distribution can serve all of them, while a learned order quantity serves one. A workable middle is to keep the probabilistic forecast as the shared product and let each decision choose its own quantile.
Nor does everyone build this in-house. DoorDash has used forecasting and replenishment software from the vendor RELEX for its DashMart dark stores since 2022, and extended the deployment in 2025.53
Section 7: Trade-offs and How to Choose
7.1 The model families compared
| Family | Covariates | Output | New items | Cost | Use it when |
|---|---|---|---|---|---|
| Croston, SBA, TSB, ADIDA | None | A flat rate | No | Negligible | As the baseline for every sparse series, and for long-tail items with no useful drivers |
| Gradient-boosted trees (LightGBM) | Any, hand-built | Mean (Tweedie or Poisson) or one quantile per model | Yes, through attributes | CPU, minutes to hours | As the default. Strong with good features. Cannot extrapolate beyond the training range |
| DeepAR | Known-future and static | Sample paths from a count distribution | Yes, through embeddings | GPU | You need the distribution of a multi-day sum, or principled masking of stockouts |
| MQ-RNN, TFT | Static, known-future, past-only | Quantiles per horizon | Yes | GPU, hours | Mixed input types, several horizons, and enough data and people to maintain it |
| N-BEATS, N-HiTS, TiDE | None to moderate | Mostly point forecasts | Limited | Moderate | Smooth upper levels of the hierarchy, or a cheaper replacement for a Transformer |
| Pretrained (Chronos, TimesFM) | Recent versions only | Quantiles | Zero-shot from little history | Inference only | Aggregated series, quick coverage of new markets, a strong second baseline |
The M5 result that only 7.5% of teams beat exponential smoothing means a sophisticated model should not be trusted until it has beaten the simple ones on your own data, by series class.12 The right design is usually a portfolio routed by the classification of Section 1.3: a feature-based global model for smooth and erratic items with drivers, intermittent methods or a count likelihood for the tail, and reconciliation to tie the levels together.
7.2 Choices that matter more than the model
| Choice | Options | What decides it |
|---|---|---|
| Training target | Raw sales, masked sales, recovered demand | Stockout frequency. At the levels in FreshRetailNet, raw sales cost about 7% in bias11 |
| Loss | Squared error, Tweedie, pinball at τ | Whether the order is set from a mean plus safety stock or from a quantile directly |
| Modelling level | SKU-store, group of substitutes by store, SKU-city | Sparsity and substitution. Model where there is signal, then disaggregate |
| Time grain | Hourly, by replenishment cycle, daily | The protection interval. A forecast finer than the decision adds noise without adding information |
| Reconciliation | Bottom-up, middle-out, MinT, top-down alignment | How biased the bottom-level forecasts are, and how many consumers need coherent numbers |
| Intraday features | None, snapshots, streaming | Whether there is a decision left to change within the day, and whether point-in-time data exists |
7.3 Running it
Picnic's production setup is a reasonable checklist. Forecasts are precomputed in batches, hundreds of millions a day. Inputs and outputs are validated against schemas and plausible ranges. A retrained model is promoted only if it beats the current one, and if anything fails, slightly stale forecasts are served, on the principle that old predictions are better than incorrect ones.30
Two ideas from Instacart's availability system transfer. Instacart's shoppers pick from other retailers' shelves, so it has to predict whether an item is in stock. It scores items in tiers: the roughly 1% with a signal in the last ten hours are rescored hourly and the rest daily, which cut computation by about 80%.54 And because models adapt slowly to shocks, it added thresholds outside the model that could be moved at once, by retailer, location and category, while the models caught up.55 The replenishment equivalent is an override layer on the target stock level, with every override logged.
Conclusion: Forecast the Distribution, Then Decide
The mental model to keep has four parts.
First, the data lie in a known direction. Sales understate demand whenever the shelf was empty, and at dark-store grain the shelf is empty often enough to matter. Flag stockout periods, then mask them or reconstruct demand before training. Evaluate on bias as well as accuracy.
Second, sparse series need their own tools. Classify by ADI and CV2. Use squared-error or scaled metrics, never MAPE, and be wary of absolute error on series that are mostly zero.
Third, levels help each other. Aggregates in product, space and time are easy to forecast and carry the seasonality and trend that the bottom level cannot show. Reconcile means across the hierarchy, with MinT or a simpler alignment. Do not add quantiles.9
Fourth, the output is an order. The right quantity is a quantile of demand over the protection interval, set by the ratio of underage cost to total cost. Train on the pinball loss at that quantile, or produce a distribution and read the quantile from it. Shortening the protection interval cuts the stock needed directly, whatever the quality of the forecast.744
Some practical takeaways for a team building this:
- Start with LightGBM on well-built features with a Tweedie objective, beside Croston-family baselines. This is the configuration that won M5, and it is cheap to run.12
- Record stock status at the same grain as sales. Without it, censoring cannot be corrected and backtests cannot be trusted.
- Make every feature point-in-time correct before adding intraday signals.39
- Set service targets from item economics, by category at least, and state which service level you mean.
The approach also has limits, and it helps to know when not to use it. For lumpy items, one planning-software vendor's guidance is that no tool will produce a reliable forecast.14 The sensible response is a stocking policy: a minimum presentation quantity, a cap, and a rule for delisting. For items where availability matters more than margin, such as baby formula or a staple the customer's whole basket depends on, the critical ratio computed from that item's own margin understates what a stockout costs, and a judgment-based target is the more defensible choice. And when the supply side is the binding constraint (a supplier that delivers twice a week, a minimum order quantity larger than a week's sales), a better demand forecast changes little. In those cases, work on the protection interval first.