Data Science

A Practical Playbook for Demand Forecasting with Machine Learning

How to move from spreadsheet forecasts to machine learning forecasts planners trust: data preparation, baselines, LightGBM and deep models, metrics, backtesting and rollout.

Summary

Demand forecasting with machine learning works when the data is fixed first: model hierarchies, promotions and holidays explicitly and treat stock-outs as censored demand. Beat seasonal-naive and ETS baselines before adopting LightGBM or deep models, judge every model on WAPE, bias and MASE in rolling backtests, and roll out with planner overrides measured through forecast value add.

Key takeaways

  • Sales history is not demand history: flag promotions and holidays, and treat stock-out periods as censored demand rather than true zeros.
  • Every model must beat a seasonal-naive and an ETS baseline in a rolling-origin backtest before it reaches production.
  • A global LightGBM model with leakage-safe lag, price and calendar features is the strongest default; TFT and N-HiTS earn their cost on large, covariate-rich portfolios.
  • Report WAPE and bias to the business, use MASE to compare models, and avoid MAPE on intermittent or low-volume items.
  • Adoption is the finish line: explain drivers, track overrides with forecast value add, and hand probabilistic forecasts to inventory optimization.
On this page

Demand forecasting with machine learning is the practice of predicting future sales or consumption for each product, location and channel with models trained on demand history and its drivers: prices, promotions, holidays, weather and product availability. This playbook describes how LehtAI moves planning teams from spreadsheet forecasts to machine learning forecasts that are measurably more accurate and that planners actually use.

Spreadsheet forecasts tend to fail in predictable ways: a moving average that lags every trend, manual promotion uplifts that nobody revisits, and a single number with no sense of uncertainty. Machine learning fixes much of this, but only if the data, the evaluation and the rollout get the same care as the model.

Why does data preparation decide forecast accuracy?

Most of the accuracy in a forecasting project is won or lost before the first model is trained. Sales history is not demand history. It is demand filtered through availability, pricing and promotions, and four issues matter most.

Product and location hierarchies

Demand lives in hierarchies: SKU to category to department, store to region to country, and often channel on top. Decide early which levels planners act on, for example SKU-store-week for replenishment and category-month for budgeting. Build a mapping table with effective dates, because products move between categories and stores open, close and change format.

Promotions and price

Promotions are often the largest source of forecast error in retail and consumer-goods portfolios. Capture each event as features (discount depth, mechanic such as multi-buy or percentage off, display and feature support, duration) rather than a single promo flag. Model the post-promotion dip and the cannibalization of substitute products explicitly, or the model will learn that promotions create demand out of nothing. The price-response estimates this produces also feed dynamic pricing and markdown optimization.

Holidays and events

Moving holidays such as Diwali, Eid, Easter and Lunar New Year shift between weeks and months every year, so a same-week-last-year comparison is wrong by design. Encode holidays as features with lead and lag windows for the days before and after. Keep a calendar of regional events, school terms and paydays alongside it.

Stock-outs as censored demand

When a product is out of stock, recorded sales are zero or truncated, but demand was not. Training on those periods teaches the model to under-forecast exactly the items that sell out, and lower forecasts then cause more stock-outs. Treat stock-out periods as censored observations: mask them from the training loss, impute demand from comparable stores and periods, or use a censored likelihood. This needs inventory or on-shelf availability data, which is why we ask for it in week one.

Which baselines should a machine learning forecast beat?

Before training any machine learning model, build simple baselines and keep them running for the life of the system:

  • Seasonal naive. Next period equals the same period last season. It needs no tuning and is surprisingly hard to beat on strongly seasonal items.
  • Exponential smoothing (ETS). A fitted level, trend and seasonality for each series, available in open-source libraries such as statsforecast and the R fable package. It is often close to what a skilled planner does by hand in a spreadsheet.
  • Croston or TSB. For intermittent demand such as spare parts and slow movers, where most periods are zero and the methods above perform poorly.

Run the baselines through the same backtest as every candidate model. If a complex model cannot beat ETS by a margin the business cares about on the series that matter, it does not go to production. Baselines also serve as the fallback for new or very sparse series and as a sanity check whenever a model's output drifts.

Which machine learning models work best for demand forecasting?

There is no single best model, but there is a sensible order in which to try them.

Gradient boosting with lag features (LightGBM)

A single global LightGBM model trained across thousands of series is our default first model. Features include lagged demand (for example 1, 2, 4 and 52 weeks back, shifted by the forecast horizon so the model never sees data it would not have at forecast time), rolling means and volatility, price and discount, promotion attributes, holiday windows, and static attributes such as category, store format and region.

Because the model is global, new or sparse items borrow strength from similar ones. A Tweedie or Poisson objective suits count-like demand, and quantile objectives produce prediction intervals that inventory planning can use directly.

Deep learning: TFT, N-BEATS and N-HiTS

Deep models earn their cost on large portfolios with long histories and rich covariates. The Temporal Fusion Transformer (opens in new tab) handles static covariates, known future inputs such as planned prices and promotions, and other exogenous series in one architecture, with built-in interpretability. N-BEATS (opens in new tab) is built from deep stacks of fully connected layers with residual links, and N-HiTS (opens in new tab) extends it for long horizons with hierarchical interpolation and multi-rate sampling. Open-source implementations in neuralforecast and PyTorch Forecasting make all three practical to test.

In our experience, the gain over a well-featured LightGBM model varies by portfolio and is often modest, while training, tuning and serving costs are higher. We adopt deep models when the backtest says they help, and frequently ensemble them with the gradient-boosted model.

Hierarchical reconciliation

Forecasts produced independently at SKU, category and region level will not add up, and planners notice immediately. Reconciliation makes them coherent. Bottom-up is simple but noisy, top-down loses detail, and MinT (minimum trace) reconciliation (opens in new tab) combines forecasts from every level using their error covariance, which is usually our choice. The open-source hierarchicalforecast library implements these methods.

Demand forecasting methods compared
MethodBest suited toStrengthsLimitations
Seasonal naiveStable, strongly seasonal seriesNo tuning; an honest baselineIgnores trend, price and promotions
ETSSingle series with clear level, trend and seasonalityFast, robust, interpretable componentsOne model per series; weak with promotions and causal drivers
Croston / TSBIntermittent demand such as spare parts and slow moversDesigned for many zero periodsLimited use of drivers; needs care with obsolescence
LightGBM with lag featuresLarge portfolios driven by price, promotions and calendar effectsLearns across series; handles many features; fast to trainNeeds careful feature engineering and leakage-safe lags
Temporal Fusion TransformerCovariate-rich portfolios with long historiesUses known future inputs; attention-based interpretabilityHeavier to train and tune; needs more data
N-BEATS / N-HiTSMany series and long horizons with few covariatesStrong accuracy with little feature workHarder to explain promotion effects to planners

How should you measure forecast accuracy: MAPE, WAPE or MASE?

Metric choice changes which model wins, so agree it with finance and supply chain before the first experiment.

  • MAPE (mean absolute percentage error) is familiar but misleading at item level. It is undefined when actual demand is zero, explodes on low-volume items and, as Forecasting: Principles and Practice (opens in new tab) notes, puts a heavier penalty on negative errors than on positive ones.
  • WAPE (weighted absolute percentage error: total absolute error divided by total actual demand) weights items by volume, stays defined with zeros and translates directly into units or revenue. It is our primary business metric.
  • MASE (mean absolute scaled error) divides the error by the in-sample error of a naive forecast, so a value below 1 means the model beats naive. It is the cleanest way to compare models across series of very different scale.
  • Bias (total forecast minus total actual, divided by total actual) shows systematic over- or under-forecasting. A model with good WAPE and a persistent bias still drives the wrong inventory.

Two practical rules apply. Measure at the level and lag at which decisions are made, for example SKU-store at a two-week lead time for replenishment. Weight by value rather than units when margins differ widely across the range.

How do you backtest a demand forecasting model properly?

Random train-test splits leak the future into the past. Use rolling-origin backtests, also called time series cross-validation, instead:

  1. Choose several forecast origins spread across at least one full seasonal cycle, including peak periods and major promotions.
  2. At each origin, train only on data available at that date, including prices and promotion plans as they were known then rather than as later corrected.
  3. Forecast the full horizon the business uses and record errors by horizon, hierarchy level and segment.
  4. Compare every candidate with the seasonal-naive and ETS baselines on the same origins and the same metrics.
  5. Inspect the worst series and periods by hand, because aggregate metrics hide systematic failures on new products, promotions and holidays.

Point-in-time correctness is the most common backtest flaw we see. A promotion calendar edited after the event, or a product hierarchy that reflects today's assortment, makes a model look better in testing than it will be in production. Snapshotted tables or a feature store, set up as part of data engineering work, prevent this.

A realistic expectation, when the incumbent is a spreadsheet or a basic statistical method, is a 10–20% reduction in WAPE at the planning level, typically larger on promoted and holiday-affected items and smaller on stable, high-volume lines. Treat any such figure as a hypothesis until your own backtest confirms it.

How do you get planners to trust and adopt ML forecasts?

A forecast nobody uses has no value. Adoption has to be designed, not announced, and it rests on five practices:

  • Run in parallel first. Publish the ML forecast next to the current one for several planning cycles and review FVA together, so the numbers make the case.
  • Explain the drivers. Show the contribution of baseline, seasonality, price, promotion and holiday effects to each forecast, using SHAP values from the gradient-boosted model or the decomposition from the deep model.
  • Make overrides easy and accountable. Planners override inside the planning tool with a reason code, and FVA then shows which override types help.
  • Show uncertainty. P10 to P90 ranges tell planners which items need attention and which are stable enough to leave to the system.
  • Focus attention. Rank exceptions such as large changes versus the last cycle, persistent bias or new items, so planners review dozens of series instead of thousands.

How do forecasts hand off to inventory optimization?

A demand forecast is an input, not a decision. The decision about how much to order and where to hold stock belongs to inventory optimization, and it needs more than a single number per item:

  • Probabilistic forecasts. Quantiles or full distributions over the replenishment lead time, so safety stock reflects actual uncertainty instead of a fixed number of weeks of cover.
  • Lead-time variability. Supplier and transport lead-time distributions, combined with demand uncertainty.
  • Service-level targets. Target service levels by item class, for example higher for fast-moving A items than for long-tail C items, agreed with commercial teams.
  • Constraints and costs. Minimum order quantities, pack sizes, shelf and warehouse capacity, and the holding and stock-out costs that the policy trades off.

With those inputs, reorder points and order quantities can be optimized per item and location, and the whole chain of forecast, policy and orders can be evaluated together in simulation before it changes real purchasing. That end-to-end view is how we approach demand forecasting and inventory optimization and the wider data science and predictive analytics work around it, with monitoring and retraining handled through MLOps.

Frequently asked questions

Is machine learning always more accurate than spreadsheet demand forecasts?

No. On stable, strongly seasonal items, a seasonal-naive or exponential smoothing forecast is often as accurate as machine learning. ML gains come mainly from promotions, price changes, holidays and large portfolios where a global model learns patterns shared across products and stores. That is why every candidate should be compared with simple baselines in a rolling backtest before it replaces the current process.

Should we use MAPE or WAPE to measure forecast accuracy?

Use WAPE as the primary business metric for demand forecasting. It weights errors by volume, stays defined when actual demand is zero and translates directly into units or revenue. MAPE is undefined for zero-demand periods and inflates errors on slow movers. Add MASE to compare models across series of different scale, and always report bias alongside accuracy.

How much history do we need to start ML demand forecasting?

Two to three years of weekly history is a comfortable starting point because it covers at least two full seasonal cycles and repeated holidays. Global models such as LightGBM can still forecast newer items by learning from similar products, stores and attributes. Quality matters more than length: promotion calendars, price history and stock availability must cover the same period as sales.

Keep reading

More insights

All insights

Want these ideas applied to your data?

Tell us about the system you are building or fixing. A senior LehtAI practitioner replies within one business day with a practical next step.