Forecasting in eCommerce: demand, stock, cash and revenue, and how far to trust it
TL;DR
Difficulty: Advanced
A shop forecast exists to make a decision: what to reorder, how much seasonal stock to buy, whether the cash holds.
- Forecast at the level the decision is made, and forecast demand, not sales: correct for the days a product was sold out.
- Start from an event aligned seasonal naive baseline, then smoothing with a seasonal decomposition, regression or gradient boosting for promotions, Croston for the long tail, and reconcile the levels.
- Score on unseen weeks with WAPE and MASE, never MAPE, and check that an 80% interval holds 80% of outcomes.
- Turn it into decisions: reorder points from forecast error and service level, a newsvendor order for Christmas, revenue from new customers plus cohorts, and a cash forecast that shows the VAT month early.
Every shop owner forecasts, usually in their head: how many lamps for Christmas, when to reorder the mug that keeps selling out, whether February will be tight. This chapter builds those forecasts properly from a shop's own orders and stock, shows which methods work at which level, how to score them honestly, and how to turn a forecast with a range into a reorder point, a seasonal order and a cash plan.
A forecast is there to make a decision, not to be right
"How many Christmas lamps should I order in August? When do I reorder the mug that keeps selling out? Will there be enough money in the bank in February?" Those are the questions a shop owner actually asks. None of them is "what will sales be". Each one is a decision with a deadline, and a forecast is only useful if it makes that decision better.
That changes how you build one. A stock forecast is per product, for the weeks until the next delivery, with an honest range. A cash forecast is in money, by month, with the dates bills fall due. Same shop, same data, different forecasts.
This chapter is the shop specific part of a topic I have written about before. The general methods (moving averages, ARIMA, Prophet, judgement) are explained in forecasting for business, the regression view of a weekly series with autocorrelation in forecasting demand: autocorrelation and seasonality, and how to draw and present a forecast in communicating forecasts. Here I go further on what is particular to a shop: censored demand, thousands of products, slow sellers, levels that must add up, honest accuracy at low volumes, safety stock, the one shot Christmas order, and revenue and cash from your own orders. The reference book underneath most of it is Hyndman and Athanasopoulos, Forecasting: Principles and Practice, third edition, free online1.
Example: the three decisions at Wrenfield Home
Wrenfield Home is the invented example shop of this series: an online homeware shop in Leeds at wrenfieldhome.example, run by Priya, with Callum as her developer. It sells ceramics, kitchen textiles, lamps and small furniture, about 1,400 products. The example's baseline: 110,000 sessions a month, a conversion rate of 1.8%, about 1,980 orders a month (1,300 of them from new customers), an average order value of £72 including VAT, a gross margin of 52%, a return rate of 9% and £14,000 a month on Google and Meta ads.
In late summer 2026 Priya writes down three decisions she has to make:
- Stock, every week: when to reorder each of the 140 products that bring most of the revenue, and how many to keep in reserve. The best seller, the Hebden stoneware mug, ran out twice last year.
- Seasonal stock, once: how many Fenwick star lamps to order from the supplier before Christmas. There is one order, placed in August, and no second chance.
- Cash, every month: whether February 2027 is safe, with the Christmas VAT bill and the spring stock both falling due.
Choose the level: total, category or product, and week or day
A shop's sales form a hierarchy: the total splits into categories, categories into products, products into variants (a colour, a size). Time forms a second one: days, weeks, months. The right level is the one at which the decision is made. A reorder is a product decision taken weekly, a packing room rota a total by day, a cash plan a total by month.
The catch is noise. The fewer sales a series has, the more of what you see is chance. A useful rule of thumb comes from the Poisson distribution, the standard model for counts of independent events such as orders (see Foundations: distributions). For a Poisson count, the typical random wobble relative to the average is:
where is the coefficient of variation (the standard deviation as a share of the average), is the standard deviation of weekly sales, is the average weekly sales, and is the average number of units a week, which for a Poisson count equals both and . Real sales are usually noisier than Poisson, never quieter, so this is the floor of the noise, not the ceiling.
Example: how noisy each level is at Wrenfield Home
Wrenfield Home sells about 731 units a week in total (1,980 orders a month, about 457 a week, at 1.6 units an order). Working the formula through at each level:
- Total, 731 units a week: , so at least 3.7% of pure chance.
- Ceramics, 330 units a week: , so 5.5%.
- The Hebden mug, 38 a week: , so 16.2%.
- A typical lamp, 4 a week: , so 50%.
- A long tail sideboard, one sale every two weeks, 0.5 a week: , so 141%.
The total can be forecast to within a few per cent. A single sideboard cannot be forecast week by week, however clever the model. For the sideboard the right question is "how many to keep so that I rarely miss a sale", the safety stock question later in this chapter. Choosing the level is the first modelling decision, made before any model.
Demand is not sales: a sold out product hides its demand
The order table records sales: what people bought. A forecast for stock needs demand: what people would have bought if the product had been there. The two are the same only while the product is in stock. On the days it is sold out, sales are zero or close to it, and the true demand is hidden. Statisticians call such data censored: you see a value only up to a limit, here the stock you had.
Feed censored sales into a model and it learns that the product sells less than it does. You order less, run out again, record even lower sales, and the forecast spirals down. Best sellers are hit hardest, because they run out.
The fix has three parts. First, record for every product and every day whether it was in stock. Second, estimate the demand on the sold out days from the selling rate on the days it was available. Third, train the model on that demand, or at least exclude the sold out days from training. For a simple estimate, see Foundations: ratios and rates:
where is the estimated demand for the period, is the units actually sold, is the number of days the product was in stock, and is the number of days it was sold out. The fraction is the daily selling rate while it was available.
Example: the Hebden mug in moss glaze
Over four weeks in October 2025 (28 days), the Hebden mug in moss glaze sold 96 units. It was sold out for nine of those days, so it was in stock for 19.
- Daily rate while in stock: units.
- Hidden demand on the nine sold out days: units.
- Estimated demand: units.
The order table says 96. The demand was about 141. Sales understated demand by . A forecast trained on the 96 would have ordered a third too little for the next autumn. One caveat keeps this honest: some customers who found the moss glaze sold out bought the sage glaze instead, so part of the hidden demand shows up elsewhere. The estimate is a correction, not a measurement.
Building the weekly demand series from a Solidus shop
On a shop built on Ruby on Rails and Solidus, everything the forecast needs is already in your own database. Sales come from spree_orders and spree_line_items. Stock history comes from spree_stock_movements: every change to a product's stock (a shipment, a delivery from the supplier, a return put back on the shelf) is a row with the stock item, the quantity (negative for stock going out) and the time, and each spree_stock_items row ties a variant to a stock location2. Adding up the movements day by day gives the stock level at the end of each day.
One caution from the Solidus source: creating a stock movement adjusts the stock count, but the method set_count_on_hand writes a new count directly without creating a movement3. If someone corrects stock that way, the running sum drifts. Check the reconstruction against today's count_on_hand for each product before you trust it, and record stock counts as movements from then on.
-- Weekly units sold per variant, and the days each variant was in stock
WITH sales AS (
SELECT li.variant_id,
date_trunc('week', (o.completed_at AT TIME ZONE 'UTC') AT TIME ZONE 'Europe/London') AS week,
sum(li.quantity) AS units
FROM spree_line_items li
JOIN spree_orders o ON o.id = li.order_id
WHERE o.completed_at IS NOT NULL
AND o.state <> 'canceled'
GROUP BY 1, 2
),
moves AS (
SELECT si.variant_id,
((sm.created_at AT TIME ZONE 'UTC') AT TIME ZONE 'Europe/London')::date AS day,
sum(sm.quantity) AS change
FROM spree_stock_movements sm
JOIN spree_stock_items si ON si.id = sm.stock_item_id
WHERE si.deleted_at IS NULL
GROUP BY 1, 2
),
days AS (
SELECT v.id AS variant_id, d::date AS day
FROM spree_variants v
CROSS JOIN generate_series(
(SELECT min(day) FROM moves), current_date - 1, interval '1 day') AS d
WHERE v.deleted_at IS NULL
AND v.track_inventory
),
levels AS (
SELECT days.variant_id, days.day,
sum(coalesce(m.change, 0))
OVER (PARTITION BY days.variant_id ORDER BY days.day) AS stock_at_close
FROM days
LEFT JOIN moves m ON m.variant_id = days.variant_id AND m.day = days.day
),
weekly_stock AS (
SELECT variant_id, date_trunc('week', day) AS week,
count(*) FILTER (WHERE stock_at_close > 0) AS days_in_stock
FROM levels
GROUP BY 1, 2
)
SELECT w.variant_id,
w.week::date AS week,
coalesce(s.units, 0) AS units,
w.days_in_stock
FROM weekly_stock w
LEFT JOIN sales s ON s.variant_id = w.variant_id AND s.week = w.week
ORDER BY 1, 2;
How it works, step by step:
salesadds up the units of every placed, uncancelled order per variant and week, in London time, because Rails stores times in UTC.date_trunc('week', ...)starts weeks on a Monday4.movesadds up the stock movements per variant and day, anddaysbuilds one row per variant and calendar day, so quiet days still exist.levelsturns the daily changes into a stock level with a running sum, andweekly_stockcounts the days that ended with stock above zero.
The demand column is then the sales scaled up by the in stock share of the week, using the formula above, and a week with no day in stock is marked as missing, not zero. A day that ended at zero counts as sold out even if the product sold out at 9pm, a simplification that a nightly stock snapshot removes later.
Example: what the query returns for the mug
For the moss mug in the week starting 13 October 2025 the query returns units = 21 and days_in_stock = 3, so the demand estimate is units. The next week returns 0 and 0, and goes into the model as missing, not as a week nobody wanted the mug.
Start with the baselines, because they are hard to beat
A baseline is the simplest forecast that could work, and every model has to beat it. The two that matter for a shop are the naive forecast, which says next week equals last week, and the seasonal naive forecast, which says next week equals the same week last year5. Two things are worth adding for a shop.
First, baselines are humbling. The M5 competition asked thousands of teams to forecast 42,840 daily sales series from Walmart, from single products in single stores up to the total. Of the teams, 48.4% beat the naive forecast, 35.8% beat the seasonal naive, and only 7.5% beat the best benchmark, plain exponential smoothing on every product with the results added up6. Most clever submissions lost to exponential smoothing, a method first proposed in the late 1950s7.
Second, the shop calendar does not line up with week numbers. Black Friday 2025 fell on 28 November, in ISO week 48. Black Friday 2026 falls on 27 November, also week 48. Black Friday 2027 falls on 26 November, in week 47. A seasonal naive forecast by week number puts the 2027 peak a week late. Easter moves by up to five weeks. And some years have 53 ISO weeks, because a year is 52.18 weeks on average8. So align by event, not by week number: keep a calendar table of the dates that move (Black Friday, Easter, bank holidays, your own sale dates) and compare like with like.
Example: the baseline for the Black Friday week of 2027
Callum's seasonal naive forecast for ISO week 47 of 2027 copies week 47 of 2026: about 1,010 units, a normal busy pre peak week. The real Black Friday of 2027 is in week 47, so the forecast is about 700 units too low for that week and about 700 too high for week 48. Aligning by event (the Black Friday week copies the Black Friday week) fixes it with one join on the calendar table.
Exponential smoothing: the workhorse for totals and categories
Exponential smoothing forecasts with a weighted average of the past, in which recent weeks count most and older weeks count less and less. Its simplest form needs one number, the smoothing weight, and adapts to a level that drifts7. See Foundations: mean for weighted averages:
where is the forecast for next week, is what actually happened this week, is what had been forecast for this week, and is the smoothing weight between 0 and 1. A high follows the latest week closely, a low one is calmer.
The full family adds a trend and a season, and the ETS framework (error, trend, season) chooses the combination automatically by fitting each and keeping the one with the best information criterion. One practical limit matters for a shop with weekly data. A seasonal model needs one seasonal value per period, and 52 of them is too many to estimate well. Forecasting: Principles and Practice recommends splitting off the season first with a decomposition (STL) and forecasting the rest with non seasonal smoothing8, and the statsforecast library refuses a seasonal ETS model when the season is longer than 24 periods9. Its MSTL model does exactly the recommended split.
Example: smoothing the lamp category
The lamp category's last three weeks were 120, 132 and 126 units, and the forecast going into the first of those weeks was 118. With :
- After week 1: .
- After week 2: .
- After week 3: .
The forecast for next week is about 124 lamps. The jump to 132 moved it by only four units, because one busy week is weak evidence. The seasonal part, added back on top, lifts it towards Christmas.
Regression: add the promotions and holidays you know about
Smoothing only looks at the series' own past. A shop also knows the future: a sale planned for March, a newsletter feature, a bank holiday weekend. Regression adds them as explanatory variables, usually as dummy variables that are 1 in an affected week and 0 otherwise10. Modelling the logarithm of sales turns each effect into a percentage, which is how promotions behave. See Foundations: regression and Foundations: logarithms:
where is units sold in week , is the base level, is 1 in a week with a sitewide promotion, is 1 in a week the product line is featured in the newsletter, is 1 in a week with a bank holiday weekend, is 1 in the week straight after a promotion, is the seasonal pattern, and is what the model cannot explain. Each coefficient turns into a multiplier through .
The term is the one most shop models forget. A promotion pulls purchases forward, so the week after it is weaker than normal. Leave it out and the model credits the promotion with sales it merely moved. How price itself enters such a model, as an elasticity, is covered in modelling demand and price elasticity, and whether a promotion pays at all in the maths behind every discount.
Example: the March promotion for ceramics
Callum fits the model on three years of weekly ceramics demand. The coefficients come out as for a 20% sitewide promotion, for a newsletter feature, for a bank holiday weekend, and for the week after a promotion. As multipliers:
- Promotion: , so 50.7% more units.
- Newsletter feature: , so 19.7% more.
- Bank holiday weekend: , so 11.3% fewer (people are out, not on the sofa with a phone).
- Week after a promotion: , so 7.7% fewer.
The normal forecast for ceramics in the second week of March 2027 is 330 units. Priya plans the promotion and a newsletter feature in that week. The forecast becomes units, and the week after drops to . Priya knows how many mugs the promotion needs, and that the week after will look weak without anything being wrong.
The long tail: products that sell now and then
At Wrenfield Home, 980 of the 1,400 products sell less than once a week, so their weekly series are mostly zeros. This is intermittent demand, and ordinary smoothing handles it badly: after each sale the forecast jumps up, then decays through the zero weeks, and it is never right.
Croston's method splits the series in two: the size of the demand when there is a sale, and the number of weeks between sales. It smooths each separately and divides one by the other11. See Foundations: ratios and rates:
where is the forecast demand per week, is the smoothed size of a sale when one happens, and is the smoothed number of weeks between sales. Forecasting: Principles and Practice is frank about its limits: the forecasts are biased, the method has no proper model behind it, and there is no formula for a prediction interval11. For the long tail that matters less than it sounds: what you need is a rate for the safety stock and a flag when the rate changes.
Example: the Ashby oak sideboard
Over the last 12 weeks the Ashby sideboard sold 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 1, 0. The sales happened in weeks 2, 5, 9 and 11, with sizes 1, 2, 1 and 1. To keep the arithmetic visible, this example uses plain averages where Croston's method would use smoothed values.
- Average size of a sale: units.
- Gaps between sales: 2 weeks (from the start to week 2), then 3, 4 and 2 weeks. Average gap: weeks.
- Forecast rate: units a week.
That is about one sideboard every two weeks, which is what goes into the reorder point. Nobody should read it as "0.45 sideboards next Tuesday".
Many products at once: gradient boosting
One smoothing model per product works, but it ignores what products share: the calendar, the promotions, the newsletter, the traffic. Gradient boosting fits one model across all products, a machine learning method that builds hundreds of small decision trees, each correcting the errors of the ones before. Each row of its training data is one product in one week, and the columns are features: last week's sales, sales a year ago, a rolling average, the price, whether a promotion runs, the category, the week of the year.
In the M5 competition most of the top methods used LightGBM, a fast gradient boosting library6. The same paper has the sobering detail: the top 50 methods beat the benchmark by about 40% at the total level, but by only about 3% at the level of single products in single stores6. A single product's weekly sales stay noisy, whatever you throw at them.
The library mlforecast wraps this in the same long format (unique_id, ds, y) as the statistical models, and future values of known features, such as a planned promotion, go in when you predict12.
import lightgbm as lgb
from mlforecast import MLForecast
from mlforecast.lag_transforms import RollingMean
fcst = MLForecast(
models=[lgb.LGBMRegressor(random_state=0, verbosity=-1)],
freq="W-MON",
lags=[1, 52],
lag_transforms={1: [RollingMean(window_size=4)]},
date_features=["month"],
)
# weekly: unique_id, ds, y, plus promo, price and category per row
fcst.fit(weekly, static_features=["category"])
# future: the next 12 weeks of promo and price for every product
preds = fcst.predict(h=12, X_df=future)
Example: one row of the training data
For the Hebden mug in the week starting 1 March 2027, the row the model sees is:
| Feature | Value | Where it comes from |
|---|---|---|
| Sales last week (lag 1) | 41 | the weekly demand series |
| Sales same week last year (lag 52) | 36 | the weekly demand series |
| Average of the last four weeks | 38.5 | rolling mean of lag 1 |
| Price | £14 | spree_prices for the variant |
| Promotion running | 0 | your promotions calendar |
| Category | ceramics | the product's taxon |
| Month | 3 | the calendar |
The target the model learns to predict is that week's demand. Because one model sees all 1,400 products, it learns from the 140 best sellers how a promotion lifts ceramics, and applies that to a new mug with only six weeks of history.
Make the levels add up: hierarchical reconciliation
Forecast each level separately and the category forecasts will not add up to the total forecast. The warehouse then plans to one number while the stock orders add up to another.
Making forecasts coherent, so that they add up the way the data does, is called reconciliation13. The simple options are:
- Bottom up: forecast every product and add up. Nothing is lost through aggregation, but the noisy bottom level makes the totals noisy too.
- Top down: forecast the total and split it by proportions. It is reliable at the top, but it cannot see what is particular to each product, and it is biased even when the total is not14.
- Optimal reconciliation (MinT): forecast every level, then adjust them all together, giving more weight to the levels that have forecast well in the past. It is what the open source reconciliation libraries implement, and it usually beats both simple options13.
Top down with forecast proportions works like this (see Foundations: ratios and rates):
where is the reconciled forecast for category , is that category's own forecast, is the sum of all category forecasts, and is the forecast for the total.
Example: next week's categories at Wrenfield Home
The forecasts for the week starting 7 September 2026 are 760 units for the total, and 340 for ceramics, 205 for kitchen textiles, 130 for lamps and 50 for furniture. The categories add up to 725, so 35 units are missing between the levels.
- Bottom up: the total becomes 725.
- Top down: each category is scaled by . Ceramics becomes , textiles , lamps , furniture , and they add up to 760.
Which is right? In Callum's backtest (next section) the total forecast was off by 7% on average, the categories added up by 9%. The total has the better record, so the top down version is the better starting point, and MinT would sit close to it.
Accuracy: MAE, WAPE and MASE, and why MAPE misleads
Score a forecast on weeks it never saw, with the right measure. The most popular one, the mean absolute percentage error (MAPE), is the wrong one for a shop with a long tail.
Three measures do the job (see Foundations: mean):
where is the actual value in week , the forecast, the number of test weeks, the number of training weeks, and the season length used for the scaling (52 for a weekly seasonal naive, 1 for a plain naive). The mean absolute error (MAE) is the average miss in units. The weighted absolute percentage error (WAPE) divides all the misses by all the sales, so it is a percentage that does not explode when a week has zero sales. The mean absolute scaled error (MASE), proposed by Hyndman and Koehler, divides the MAE by the error a naive forecast made on the training data: below 1 means better than naive15.
The MAPE averages the percentage error of each week. In a week with zero sales that percentage is infinite or undefined, and in weeks with small sales it is huge16. Tools that drop the zero weeks make it worse, because they ignore exactly the weeks where the forecast said "some" and the truth said "none". One more subtlety: a forecast that minimises the MAE aims at the median, not the average16. For a product that sells in fewer than half of all weeks, the median week is zero, so the MAE rewards forecasting zero, which is useless for stock.
The testing itself is time series cross validation: pick a cutoff, fit on everything before it, forecast the next weeks, score, move the cutoff forward and repeat. The book calls it evaluation on a rolling forecasting origin17.
Example: scoring the sideboard two ways
Over eight test weeks the sideboard sold 0, 2, 0, 1, 0, 0, 3, 0, so 6 units. Croston forecast 0.75 a week throughout.
- Absolute errors: 0.75, 1.25, 0.75, 0.25, 0.75, 0.75, 2.25, 0.75. Sum: 7.5.
- MAE: units a week.
- WAPE: .
- MAPE: undefined, because five of the eight weeks have zero sales. Dropping them gives , a number that looks better than the WAPE and means nothing.
- A forecast of zero every week: absolute errors add up to 6, so the MAE is , better than Croston's 0.94. Yet a shop that stocked zero sideboards would have lost all six sales.
At the sideboard's level, judge the forecast by what it does to stock (sales missed, stock left over), not by an error score. At higher levels the scores work, and Callum's backtest over 26 weekly cutoffs, with 12 weeks ahead each time, gives this WAPE by level (invented example figures):
| Level | Seasonal naive | MSTL with smoothing | LightGBM across products |
|---|---|---|---|
| Total | 14% | 8% | 7% |
| Category | 18% | 11% | 10% |
| A products (140 best sellers) | 38% | 29% | 27% |
| C products (980 slow sellers) | 120% | 96% | 94% |
The pattern matches what the M5 competition found: large gains at the top, small gains at the bottom.
How far you can trust it: prediction intervals, checked
A prediction interval gives the range in which the actual value should fall with a stated probability. For a forecast with roughly normal errors (see Foundations: confidence intervals):
where is the forecast weeks ahead, is the standard deviation of the forecast error at that horizon, and is the multiplier for the chosen probability, 1.28 for an 80% interval. The error grows with the horizon, so the interval widens the further ahead you look, which is the fan shape explained in communicating forecasts.
The model's own interval is a claim. Check it. In the backtest, count how often the actual landed inside the 80% interval. It should be about 80% of the time. If it is much less, the model is overconfident, usually because it does not know about the shocks your shop lives with (a supplier delay, a viral post, a site outage). Widen the interval by the factor that makes the backtest coverage right.
Example: the autumn forecast and its coverage check
Callum checks the interval first. In the backtest of the previous 52 weeks, the actual total landed inside the model's 80% interval 37 times: . With 52 tries and a true rate of 80%, about 41 or 42 hits would be expected, with a typical wobble of about 3, so 37 is clearly short. He widens all intervals by 20% and the backtest gives 42 hits out of 52, 81%. The chart shows the widened band. For the Black Friday week, it says: plan for about 1,720 units, and do not be surprised by anything from about 1,360 to 2,080. Priya staffs the packing room for 1,900 and arranges two temps on call.
Safety stock and the reorder point
A reorder point is the stock level at which you order more. It has to cover the demand until the delivery arrives (the lead time), plus a reserve for the case that demand runs higher than forecast: the safety stock. The size of the reserve follows from the cycle service level, the probability of not running out before each delivery arrives18.
The standard formula (see Foundations: distributions):
where is the reorder point in units, is the forecast demand over the lead time, is the safety factor for the chosen service level, is the standard deviation of the forecast error over the lead time, is the standard deviation of the weekly forecast error, and is the lead time in weeks. The term is the safety stock. The square root comes from adding independent weekly errors: variances add, so standard deviations grow with the square root of the number of weeks18.
Two details make the difference in practice. First, is the error of your forecast, ideally its root mean square error from the backtest, not the raw spread of sales: the MIT supply chain course notes make exactly this point, and a better forecast therefore directly means less stock18. Second, the safety factor comes from the normal distribution: for 90%, for 95% and for 98%19.
When the supplier's lead time varies too, the uncertainty has a second source, and the standard deviation becomes19 (see Foundations: spread):
where is the average lead time in weeks, is the weekly forecast error as before, is the average weekly demand, and is the standard deviation of the lead time in weeks.
Example: the reorder point for the Hebden mug
The mug's forecast is 38 a week, the weekly forecast error from the backtest is 9 units, the potter in Stoke takes four weeks, and Priya wants a 95% cycle service level.
- Demand over the lead time: units.
- Error over the lead time: units.
- Safety stock: , so 30 mugs.
- Reorder point: mugs.
Now suppose the potter's lead time is four weeks on average but varies with a standard deviation of one week:
- units.
- Safety stock: , so 70 mugs, and the reorder point is .
An unreliable lead time more than doubles the safety stock, from 30 to 70 mugs. Most of the reserve now protects against the supplier, which is worth a conversation with the potter before a better model.
Service levels by product class: where the stock money goes
Every per cent of service level costs stock, and the cost rises steeply near 100%. One level for all 1,400 products ties up money where it matters least, so sort products into classes by revenue (an ABC analysis) and give each class its own target. Which products belong in which class is covered in product and category analytics.
Example: safety stock at Wrenfield Home, one level for all against tiered levels
Callum groups the products (invented example figures, lead times and errors per product):
| Class | Products | Weekly forecast error per product | Lead time | Service level | Safety stock per product | Unit cost |
|---|---|---|---|---|---|---|
| A, top revenue | 140 | 1.6 units | 4 weeks | 98% | £14 | |
| B, middle | 280 | 0.9 units | 6 weeks | 95% | £16 | |
| C, long tail | 980 | 0.35 units | 6 weeks | 90% | £20 |
Multiplying by the number of products and the unit cost gives the money tied up in safety stock:
- A: £12,858.
- B: £16,307.
- C: £21,560.
- Total, tiered: £50,725.
With 98% for every class, B and C need and times as much: B £20,260 and C £34,529, a total of £67,647. Tiering frees about £16,900, almost all of it from the long tail, while the products that bring most of the revenue keep the highest protection.
Seasonal stock you order once: the newsvendor problem
Some products are ordered once per season: Christmas decorations, a garden range, a limited edition. There is no second order. Order too few and you lose sales at full margin, too many and the rest goes into a clearance at a loss. This is the newsvendor problem, named after a vendor who must decide each morning how many papers to buy20.
The answer weighs the two mistakes. The underage cost is what one unit too few costs you, the lost contribution. The overage cost is what one unit too many costs you, its cost minus whatever you recover. The best order quantity is the one at which the probability of selling out equals the critical ratio20 (see Foundations: expected value):
where is the best order quantity, is the probability that demand is at most , and are the mean and standard deviation of the season's demand forecast, and is the point of the standard normal distribution with that probability below it. When a missed sale costs more than a leftover unit, the ratio is above 0.5 and you order more than the average forecast. When a leftover costs more, you order less.
Example: how many Fenwick star lamps to order
The Fenwick star lamp sells for £45 including VAT, which is £37.50 without VAT. It costs £16 from the supplier. Each order costs £6.50 to pick, pack and ship, and the payment fee is 1.7%, so £0.77. Leftover lamps go into the January sale at £20 including VAT, £16.67 without VAT, which after fulfilment and the fee brings . Storing a leftover lamp until January costs about £1.
- Underage cost, the contribution lost per missed sale: £14.23.
- Overage cost, the loss per leftover lamp: £7.17.
- Critical ratio: .
- The forecast for the season is 600 lamps with a standard deviation of 150. The normal point with 66.5% below it is .
- Order: lamps.
Now suppose there is no clearance channel, because the lamp carries the 2026 date and will not sell in January. The overage cost becomes the full £16 plus £1 storage, £17. The ratio drops to , , and the order becomes lamps, below the average forecast. Same forecast, different economics, 81 lamps apart. And both answers need the standard deviation: a forecast without a range cannot answer this question at all.
Revenue from cohorts and orders: forecast the parts separately
Revenue is two flows: orders from new customers, which depend mostly on marketing spend, and orders from existing customers, which follow from the cohorts you already have. The first is a decision, the second close to arithmetic, so forecast them separately.
The returning part comes straight from cohort analysis: each cohort of past customers places orders at a rate that depends on its age. Group cohorts by age, multiply each group's size by its order rate, and add up. See Foundations: expected value:
where is the revenue forecast for the month, is the forecast number of first orders, is the number of customers in cohort age group , is the average number of orders per customer per month for that age group, and AOV is the average order value. The new customer part comes from the planned ad spend divided by the cost of winning a customer, the subject of customer acquisition cost and payback.
The two parts also differ in uncertainty. If the errors of the two parts are independent, their standard deviations combine like this (see Foundations: spread):
where is the standard deviation of the total order forecast, that of the new customer orders and that of the returning orders.
Example: January 2027 revenue at Wrenfield Home
January is quieter, and Priya plans less ad spend. The forecast for first orders is 1,150. The returning orders come from the cohorts (invented example rates):
| Cohort age group | Customers | Orders per customer per month | Orders |
|---|---|---|---|
| 1 to 3 months (October to December 2026) | 5,600 | 0.040 | 224 |
| 4 to 12 months (January to September 2026) | 11,250 | 0.024 | 270 |
| 13 months and older | 38,000 | 0.005 | 190 |
| Returning, total | 684 |
Total orders: . Revenue: £132,048 including VAT.
Callum puts an 80% range on each part from past forecast errors: plus or minus 15% on new customers (ad auctions move), plus or minus 6% on returning orders (cohorts are steady). As standard deviations, that is orders and orders. Combined: orders, so an 80% range of orders, or £12,744. January revenue: about £132,000, likely between about £119,300 and £144,800. Almost all of the uncertainty sits in the new customer part, which is the part Priya controls through the budget.
Cash: when the money actually moves
Profit and cash are different things, and a growing shop can run out of cash while profitable. A cash forecast moves each forecast item to the date it hits the bank: customer payments within days, stock on the supplier's terms, VAT in one lump after the quarter.
In the UK, a VAT return usually covers three months, and the return and the payment are due one calendar month and seven days after the end of the period21. So the VAT on the Christmas quarter, October to December, is due on 7 February, in what is often the quietest month of the year. This is general information on timing, not tax advice: your accountant confirms your own periods and dates.
Example: the cash forecast for February 2027
Callum builds February 2027 from the forecasts (invented example; payments assumed to settle within the month):
- Opening balance on 1 February: £85,000.
- Customer receipts: 1,760 forecast orders at £72 is £126,720. Minus payment fees of 1.7%, £2,154, and refunds of 9%, £11,405, leaves £113,161.
- Stock: January's purchases for spring, on 30 day terms: £52,000.
- Ads: £12,000. Fulfilment: £11,440. Fixed costs: £19,500.
- VAT for October to December 2026, due 7 February. Sales in the quarter including VAT: £581,760. Without VAT: £484,800. After 9% refunds: £441,168, so output VAT of £88,234. Stock bought at 48% of that, £211,761, carries input VAT of £42,352. VAT payable: £45,882. (The example counts input VAT on stock only, so the real bill would be a little lower.)
Closing balance: £57,340.
The month ends positive, at £57,340, but the VAT payment alone takes more than half of the opening balance. Run the same forecast with the bottom of the 80% revenue range, about 10% fewer orders, and receipts fall by about £10,900, so February ends at about £46,400. Bring March's £52,000 stock payment forward into February as well, as the supplier asked for this year, and the account ends about £5,600 overdrawn. Known in September, it can still be changed: Priya moves part of the spring order to 60 day terms. That is what a cash forecast is for.
Choosing the method for each series
With the pieces in place, the choice per series follows four questions, in this order.
Example: the backtest in Python for every product at once
The statistical models run on all products in one call with the statsforecast library, on the weekly demand series from the SQL above, in the long format of unique_id, ds and y22. MSTL handles the 52 week season, and Croston covers the long tail:
import pandas as pd
from statsforecast import StatsForecast
from statsforecast.models import CrostonOptimized, MSTL, SeasonalNaive
df = pd.read_csv("weekly_demand.csv", parse_dates=["ds"]) # unique_id, ds, y
sf = StatsForecast(
models=[SeasonalNaive(season_length=52), MSTL(season_length=52), CrostonOptimized()],
freq="W-MON",
n_jobs=-1,
)
cv = sf.cross_validation(df=df, h=12, step_size=4, n_windows=6)
def wape(group, model):
return (group["y"] - group[model]).abs().sum() / group["y"].sum()
scores = {m: wape(cv, m) for m in ["SeasonalNaive", "MSTL", "CrostonOptimized"]}
cross_validation moves the cutoff forward six times, four weeks apart, and forecasts 12 weeks from each23. The result has one row per product, test week and cutoff, with the actual value and each model's forecast side by side, so WAPE by class or category is one groupby away. The forecasts go back into a table in the shop's own database, so the admin shows each product's reorder point next to its stock.
What owning the system adds to forecasting
Nothing in this chapter needs a particular platform: a rented platform with a good export can feed the same Python. Owning the system changes the plumbing. The stock movements, the promotions calendar, the newsletter schedule and the supplier lead times all live in the same database as the orders, so the features a forecast needs are one query away, not four exports from four apps. The forecast can be written back where the decisions happen: a reorder suggestion on the product page in the admin, a purchase order drafted by a background job, a cash view next to the order report. Chapter 3, automating shop operations, shows that side, and the shop database as the source of truth the data side.
This is also work I do for clients: forecasting, lifetime value and segmentation as part of Data Science, on shops I build on Ruby on Rails and Solidus, with the code belonging to the client once paid.
Example: the forecasting rhythm at Wrenfield Home
- Every Monday: the background job refits the models, writes forecasts and reorder points, and flags every A product below its reorder point.
- Every month: Callum scores last month's forecasts by level and checks the interval coverage.
- Every quarter: the cash forecast for the next six months, with a low revenue scenario, and the service levels per class.
- Once a year, in summer: the newsvendor orders for Christmas, from the forecast range and the margins, not last year's number plus a feeling.
Conclusion
A shop forecast exists to make a decision: what to reorder and when, how much seasonal stock to buy, and whether the cash will hold. Choose the level the decision is made at, and accept that a single slow product cannot be forecast week by week. Forecast demand, not sales, by correcting for the days a product was sold out. Start from the seasonal naive baseline aligned on events, use smoothing with a seasonal decomposition for totals and categories, regression or gradient boosting where promotions and holidays drive sales, and Croston's method for the long tail. Reconcile the levels so they add up. Score on weeks the model never saw with WAPE and MASE, not MAPE, and check that an 80% interval really contains 80% of outcomes. Then turn the forecast into decisions: a reorder point from the forecast error and a service level per class, a newsvendor order from the margins, revenue from new customers plus cohorts, and a cash forecast that shows the VAT month early enough to act. How far can you trust it? Exactly as far as the backtest says, and no further.