Beyond Point Forecasts: A Step-by-Step Guide to Probabilistic Demand Forecasting and Inventory Simulation
Introduction: Why this guide exists
It is six o'clock in the morning in a supermarket. The replenishment manager has until nine to place tomorrow's order for a popular yogurt. On her screen, the forecasting tool says 100 units.
She hesitates. She remembers that last Tuesday the shelf was nearly untouched, and that last Saturday, during a promotion, the product sold out before noon. A forecast of 100 sounds reasonable, but it hides something she cares about: how wrong could it be? And more importantly, which number should she actually type in the order form?
This is the gap this guide fills. In many data science projects, success is measured by forecast accuracy: a lower RMSE, a better MAPE. But the business does not get paid for accuracy. It gets paid, or loses money, through empty shelves, wasted products, and cash tied up in stock. Between a forecast and an order there is a whole chain of reasoning: uncertainty, costs, replenishment rules, and testing under many possible futures.
We will walk through that chain step by step, with one continuous example, and we will see how each method connects to the next.
- Data scientists and ML engineers who build demand forecasts and want to connect them to decisions.
- Analysts and supply chain professionals who want to understand what the models behind the numbers actually do.
- Students preparing for retail or supply chain data science interviews.
What you need: a basic understanding of probability (mean, variance, distribution) and of supervised learning. You do not need any background in operations research: we introduce every concept from scratch.
Each concept follows the same rhythm: a business intuition, a small numerical example, then the formula, with a table explaining every symbol. All numbers are illustrative. If the formulas feel heavy, read the examples first and come back to the maths later. Part 11 is a cheat sheet you can keep. This is the first of two guides: the second one adds accounting KPIs (turnover, GMROI, working capital) and explainability.
Enough context. Let's begin.
Let's rebuild everything from the beginning, connecting regression models, quantile regression, probabilistic forecasting, stochastic inventory simulation, and inventory optimization.
We will use one continuous example: a retailer selling a product and deciding how many units to order each day.
The goal is to understand not only the formulas but also what every symbol means, why each method is useful, and how the different methods work together.
Part 1. Understanding the business problem
Imagine that you work as a Data Scientist for a supermarket.
Every day, the supermarket needs to decide how many units of a particular product to order. Tomorrow's demand could be 60 units, 100 units, or 160 units. The problem is that you don't know tomorrow's demand in advance.
- If you order too few units, customers may find the product out of stock.
- If you order too many, you may have to store the excess inventory or throw it away.
Your objective is to determine an appropriate order quantity using historical data, machine learning, and inventory optimization.
To solve this problem, we need to understand five concepts:
- Regression and demand forecasting.
- Probabilistic forecasting.
- Quantile regression.
- Inventory policies and the Newsvendor model.
- Stochastic inventory simulation.
Here is the map of the journey. The first steps predict demand, the following ones decide what to do about it. Let's explore them in order.
Part 2. Regression: Predicting demand
2.1 What is regression?
Regression is a machine learning task in which we predict a numerical value from input features. Suppose you have historical supermarket data:
| Day | Price (€) | Promotion | Temperature (°C) | Actual demand |
|---|---|---|---|---|
| Monday | 2.00 | No | 18 | 80 |
| Tuesday | 1.50 | Yes | 20 | 140 |
| Wednesday | 2.00 | No | 22 | 95 |
| Thursday | 1.80 | Yes | 25 | 130 |
| Friday | 2.00 | No | 19 | 90 |
The features might influence demand. Lower prices may increase demand. Promotions may increase sales. Temperature may influence demand for seasonal products. Weekends and holidays may affect customer behavior.
We want to learn a function that predicts demand from these features. We can represent the problem as:
$$\hat{y}=f_\theta(x)$$Let's explain every symbol.
| Symbol | Meaning |
|---|---|
| \(x\) | Input features, such as price, promotion, and temperature |
| \(y\) | Actual observed demand |
| \(\hat{y}\) | Predicted demand |
| \(f\) | The prediction function or model |
| \(\theta\) | The model's learned parameters |
For example, if the input is \(x=(2.00,\text{No},18)\), the model might predict \(\hat{y}=85\). This means the model predicts demand of 85 units. Notice that \(\hat{y}\) is a prediction, not necessarily the actual demand.
2.2 How does the model learn?
During training, the model compares its predictions with historical observations and adjusts \(\theta\) to make the errors smaller. For Monday, the model predicted 85 and the actual demand was 80: an error of \(-5\). For Tuesday, it predicted 130 and the actual demand was 140: an error of \(+10\).
A common regression objective is the Mean Squared Error (MSE):
$$\operatorname{MSE}(\theta)=\frac{1}{n}\sum_{i=1}^{n}\bigl(y_i-f_\theta(x_i)\bigr)^2,\qquad \theta^*=\arg\min_\theta \operatorname{MSE}(\theta)$$Here \(n\) is the number of observations, \(i\) identifies one observation, \(\sum\) adds up all the squared errors, and \(\arg\min\) means find the parameter values that minimize the objective.
What does the model learn?
A conventional regression model trained with squared error generally estimates the conditional mean:
$$\hat{y}\approx \mathbb{E}[D\mid X=x]$$where \(D\) is the random variable representing demand, \(X=x\) are the features we know, and \(\mathbb{E}\) is the average under the probability distribution of demand.
Given the product's price, promotion status, and other information, what is the expected demand?
Suppose the model predicts 100. The expected demand is 100 units. But this doesn't tell us how uncertain demand is. Tomorrow's demand might be 95 units, 100 units, or 150 units.
This is the limitation we need to address next.
Part 3. Probabilistic forecasting: Predicting uncertainty
3.1 Point forecasting versus probabilistic forecasting
Suppose two products have the same expected demand.
| Product | Expected demand | Possible demand values |
|---|---|---|
| A | 100 | Usually between 90 and 110 |
| B | 100 | Could range from about 40 to 160 |
A point forecasting model might predict 100 units for both. However, their demand uncertainty is very different, and Product B needs a different inventory strategy because demand fluctuates much more.
This leads to two different forecasting objectives. A point forecast predicts one numerical value, \(\hat{y}=f_\theta(x)\). A probabilistic forecast estimates the whole conditional distribution of demand:
$$P(D\mid X=x)$$This distribution describes which demand values are plausible and how probable they are. For example, suppose demand follows a normal distribution:
$$D\mid X=x\sim\mathcal{N}(100,\,20^2)$$Here \(\mathcal{N}\) is the normal distribution, 100 is the conditional mean, and 20 is the conditional standard deviation (the notation \(20^2\) is the variance, 400). A probabilistic model lets us answer questions such as:
- What is the probability that demand exceeds 120 units?
- What quantity covers approximately 90% of demand outcomes?
- How much inventory should we order if stockouts are expensive?
These are exactly the questions that matter for inventory management.
3.2 How can we estimate a demand distribution?
There are several approaches.
| Method | What it estimates |
|---|---|
| Parametric distributional regression | Parameters of an assumed distribution, such as mean and standard deviation |
| Quantile regression | Specific conditional quantiles of demand |
| Distributional boosting | Distribution parameters, using boosting-based methods |
| GAMLSS | Distribution parameters that depend on explanatory variables |
| Conformal prediction | Prediction intervals with coverage guarantees under appropriate assumptions |
For example, a distributional model might learn \(\mu(x)=f_\theta(x)\) and \(\sigma(x)=g_\phi(x)\), where \(f_\theta\) and \(g_\phi\) are functions learned from data. If the model assumes a normal distribution, these two functions determine everything: \(D\mid X=x\sim\mathcal{N}(\mu(x),\sigma(x)^2)\).
However, real retail demand may be skewed, discrete, or contain many zero-demand observations. A normal distribution is not always appropriate. This is one reason quantile regression is so useful: it doesn't need to assume a shape.
Part 4. Quantile regression: Predicting different levels of demand
4.1 What is a quantile?
A quantile is a value below which a specified proportion of observations falls. Let \(D\) represent demand. The cumulative distribution function, or CDF, is:
$$F_D(d)=P(D\leq d)$$| Symbol | Meaning |
|---|---|
| \(D\) | Random variable representing demand |
| \(d\) | A candidate demand quantity |
| \(F_D\) | Cumulative distribution function of demand |
| \(P(\cdot)\) | Probability of an event |
| \(\leq\) | Less than or equal to |
Suppose the demand distribution is:
| Demand | Probability | \(F_D(d)\) |
|---|---|---|
| 60 | 20% | 20% |
| 100 | 50% | 70% |
| 160 | 30% | 100% |
For example, \(F_D(100)=P(D\leq100)=0.70\): there is a 70% probability that demand will be at most 100 units.
What is the inverse CDF?
The inverse CDF does the opposite: it converts a probability into a demand quantity. We write:
$$Q_\tau=F_D^{-1}(\tau)=\min\{d:\ F_D(d)\geq\tau\}$$where \(F_D^{-1}\) is the quantile function, \(\tau\) is the quantile level (between 0 and 1), and \(Q_\tau\) is the demand quantity at that level. In our example, \(Q_{0.70}=100\): the 70th percentile is 100 units.
With discrete demand the CDF jumps, so the inverse must be defined carefully. We use the lower quantile: the smallest \(d\) such that \(F_D(d)\geq\tau\). Here that means \(Q_{0.80}=160\), not 130, because the CDF goes from 70% straight to 100% at 160.
4.2 What is conditional quantile regression?
In retail, we don't want only the overall demand distribution. We want demand quantiles given the product characteristics and current conditions, because a promotion, a holiday, or a heat wave changes the distribution. The conditional quantile function is:
$$Q_\tau(D\mid X=x)$$Read this as: the demand quantity corresponding to quantile level \(\tau\), given the features \(X=x\). Suppose the model produces the following predictions:
| Quantile | Predicted demand | Interpretation |
|---|---|---|
| 10th percentile | 65 | 10% of demand outcomes are at or below 65 units |
| 50th percentile | 100 | The median demand is 100 units |
| 80th percentile | 130 | 80% of demand outcomes are at or below 130 units |
| 95th percentile | 160 | 95% of demand outcomes are at or below 160 units |
These are illustrative predictions, not results calculated from the earlier discrete distribution.
Why estimate multiple quantiles?
Because different business decisions require different risk levels. The 50th percentile might be suitable when overstocking is costly. The 80th percentile might be appropriate when stockouts are more expensive. The 95th percentile might be useful for products where stockouts are particularly undesirable. The optimal choice depends on the costs and business constraints.
4.3 The objective function of quantile regression
Now let's see how a model learns a quantile. For ordinary regression, we used squared error. Quantile regression uses a different loss function called the pinball loss. First, define the prediction error:
$$u_i=y_i-\hat y_i$$The pinball loss at quantile level \(\tau\) is:
$$\rho_\tau(u)=\begin{cases}\tau\,u, & u\geq 0\\[2pt] (\tau-1)\,u, & u\lt 0\end{cases}$$Why use this loss? Because it penalizes underprediction and overprediction differently. Let's see it in action.
If actual demand is 120 and predicted demand is 100, then \(u=120-100=20\). Because \(u\geq0\): \(\rho_{0.80}(20)=0.80\times 20=16\). The model underestimated demand, and the loss is 16.
Now suppose actual demand is 100 and predicted demand is 120. Then \(u=-20\), and \(\rho_{0.80}(-20)=(0.80-1)\times(-20)=4\). The model overestimated demand, and the loss is 4.
At the 80th percentile, underestimating demand is penalized more heavily than overestimating it. That is exactly what we want when learning a higher demand quantile.
The full objective function
For \(n\) training observations, the model minimizes:
$$\theta^*=\arg\min_\theta\sum_{i=1}^{n}\rho_\tau\bigl(y_i-f_\theta(x_i)\bigr)$$The important difference from ordinary regression is that the objective depends on the selected quantile \(\tau\).
4.4 Do we need one model per quantile?
Not necessarily. There are two approaches.
Approach A: separate models. Train one model for each quantile: \(\hat Q_{0.10}(x)=f_{\theta_{0.10}}(x)\), \(\hat Q_{0.50}(x)=f_{\theta_{0.50}}(x)\), \(\hat Q_{0.80}(x)=f_{\theta_{0.80}}(x)\). Each model has its own learned parameters. This is a common approach in tree-based forecasting systems.
Approach B: one quantile-conditioned model. Train one model that receives both the features and the quantile level:
$$\hat Q_\tau(x)=f_\theta(x,\tau),\qquad \theta^*=\arg\min_\theta\sum_{i=1}^{n}\sum_{k=1}^{K}\rho_{\tau_k}\bigl(y_i-f_\theta(x_i,\tau_k)\bigr)$$Here \(K\) is the number of quantile levels used during training and \(\tau_k\) is the \(k\)-th one. The model is exposed to many quantile levels and learns how predictions should change with \(\tau\).
Nothing forces independently trained quantiles to be ordered. The model might predict the 80th percentile below the 50th. Monitor it, or fix it by sorting the predicted quantiles of each row. Also, knowing many quantiles approximates the conditional distribution, but does not necessarily give a smooth or perfectly calibrated probability distribution.
4.5 A minimal LightGBM example
Let's see what this looks like in code, with one model per quantile, a fix for quantile crossing, and a calibration check.
import numpy as np
import lightgbm as lgb
taus = [0.10, 0.50, 0.80, 0.95]
models = {}
for tau in taus:
models[tau] = lgb.LGBMRegressor(objective="quantile", alpha=tau,
n_estimators=400, learning_rate=0.05)
models[tau].fit(X_train, y_train)
pred = np.column_stack([models[t].predict(X_test) for t in taus])
pred = np.sort(pred, axis=1) # remove quantile crossing
# Calibration check: each share should be close to its tau
for j, tau in enumerate(taus):
print(tau, (y_test <= pred[:, j]).mean()) Evaluate with the pinball loss for each quantile and with calibration (the empirical coverage). A model that is accurate on average but badly calibrated will produce poor inventory decisions.
Part 5. From quantile forecasts to inventory decisions
So far, we have learned how to predict demand and its uncertainty. But a retailer does not make money simply by predicting demand. The retailer needs to decide how many units to order. This brings us to inventory policies.
5.1 What is an inventory policy?
An inventory policy is a rule that determines when to order and how much to order. For example:
Whenever inventory falls below 30 units, place an order that brings the inventory position back to 100 units.
This is an example of a reorder-point and order-up-to policy, written \((R,S)\). Let's define the notation.
| Symbol | Meaning |
|---|---|
| \(I_t\) | Inventory on hand at time \(t\) |
| \(IP_t\) | Inventory position at time \(t\) |
| \(R\) | Reorder point |
| \(S\) | Order-up-to level (target inventory position) |
| \(O_t\) | Order quantity placed at time \(t\) |
The inventory position includes stock on hand and stock already ordered but not yet received, minus backorders, and the replenishment rule is:
$$IP_t=I_t+\text{On-order}_t-\text{Backorders}_t,\qquad O_t=\begin{cases}S-IP_t, & IP_t\leq R\\ 0, & IP_t\gt R\end{cases}$$If the inventory position is at or below the reorder point \(R\), order enough to reach \(S\). Otherwise, do not order. For example, with \(R=30\), \(S=100\), and \(IP_t=25\), the retailer orders \(100-25=75\) units.
Notice that the inventory position, not merely the physical stock on the shelf, determines the order quantity. This prevents the retailer from ordering too much when other replenishment orders are already on the way.
5.2 How do we choose the target inventory level?
One possibility is to use a demand quantile. Suppose tomorrow's forecasts are \(Q_{0.50}=100\), \(Q_{0.80}=130\), and \(Q_{0.95}=160\). If the retailer wants to cover demand up to approximately the 80th percentile, it might choose 130 units as a target.
The right target depends on the replenishment lead time, the existing inventory, and the policy itself. If a supplier takes three days to deliver, the retailer must cover demand over the whole exposure period, not just tomorrow. And be careful: the sum of daily 80th percentiles is not the 80th percentile of the sum. Forecast the cumulative demand distribution directly, or simulate it, as we will do in Part 7.
Part 6. The Newsvendor model: Deriving an optimal order quantity
The Newsvendor model is a classic operations research model for deciding how much to order when demand is uncertain. It is especially useful for products with a single selling period or a clearly defined replenishment decision: fresh food, seasonal merchandise, newspapers, products with short selling windows.
6.1 Understocking and overstocking costs
Suppose a retailer must choose an order quantity \(q\) before observing demand \(D\). There are two possibilities.
- If demand exceeds the order (\(D\gt q\)), the retailer loses potential sales. Define \(C_u\) as the underage cost per unit.
- If demand is below the order (\(D\lt q\)), the retailer holds excess stock. Define \(C_o\) as the overage cost per unit.
The model balances these two costs.
6.2 Deriving the optimal quantity
Think about adding one more unit to the order. With probability \(F_D(q)\), demand is at or below \(q\), the unit is not needed, and it costs us \(C_o\). With probability \(1-F_D(q)\), demand exceeds \(q\), the unit sells, and it saves us \(C_u\). We keep adding units until the two effects balance, \(C_u\,(1-F_D(q))=C_o\,F_D(q)\), which gives:
$$\boxed{\,q^*=F_D^{-1}\!\left(\tau^*\right),\qquad \tau^*=\frac{C_u}{C_u+C_o}\,}$$| Symbol | Meaning |
|---|---|
| \(q^*\) | Optimal order quantity |
| \(F_D^{-1}\) | Inverse CDF, or demand quantile function |
| \(C_u\) | Marginal cost of ordering one unit too few |
| \(C_o\) | Marginal cost of ordering one unit too many |
| \(\tau^*\) | Critical fractile: the target quantile level |
The formula tells us that the optimal order quantity is a particular quantile of the demand distribution, and that the quantile depends on the relative costs of understocking and overstocking.
Suppose \(C_u=4\) euros and \(C_o=1\) euro. The critical fractile is \(\tau^*=4/(4+1)=0.80\), so the retailer should order the 80th percentile of demand. If a trained quantile regression model predicts \(\hat Q_{0.80}(x)=130\), then \(q^*=130\) units.
This is how quantile regression can directly support inventory decisions. The model does not need to predict only the mean demand. It can estimate the quantile that matches the business's cost structure.
Important assumption: this is the classical result for a single-period decision with constant marginal costs. In more complicated inventory systems, the optimal policy may differ.
6.3 Why quantile regression fits so well
There is a beautiful connection hiding here. The newsvendor cost of ordering \(q\) when demand turns out to be \(D\) is \(C_u\max(D-q,0)+C_o\max(q-D,0)\). A little algebra shows that this equals \((C_u+C_o)\,\rho_{\tau^*}(D-q)\): the pinball loss at \(\tau^*\), scaled by a constant.
Let's check with our numbers. When \(u=+20\): \(4\times20=80=5\times16\). When \(u=-20\): \(1\times20=20=5\times4\). Both match the pinball losses we computed in Part 4.
Training a quantile model at \(\tau^*\) is the same as training it to minimize expected newsvendor cost. The forecast and the decision share one objective.
Part 7. Stochastic inventory simulation
Now we arrive at the next major concept. The Newsvendor model gives us an analytical solution for a particular class of problems. But real inventory systems are often more complicated:
- Products are replenished repeatedly.
- Suppliers have lead times.
- Inventory carries over from one day to the next.
- Orders may arrive in batches.
- Products may expire.
- Stockouts may create lost sales or backorders.
For these systems, we can use stochastic inventory simulation.
7.1 What does stochastic mean?
A stochastic process involves randomness. In inventory management, daily demand is often stochastic:
$$D_t\sim P(D_t\mid X_t)$$where \(D_t\) is the random demand during period \(t\) and \(X_t\) is the contextual information for that period. For example, \(D_1\) is Monday's demand, \(D_2\) is Tuesday's, and so on. Demand is not necessarily independent from one day to the next, so the model should reflect seasonality, promotions, trends, and temporal dependencies.
7.2 What does simulation mean?
Simulation means reproducing how a system evolves over time using a mathematical model. Instead of solving every part of the problem analytically, we generate possible demand scenarios and watch the consequences of our inventory decisions. A simplified simulation follows these steps:
- Initialize inventory.
- Generate demand.
- Fulfil customer demand.
- Calculate unmet demand.
- Receive replenishment orders when they arrive.
- Place new orders according to the chosen policy.
- Calculate costs.
- Repeat over the planning horizon, then across many scenarios.
This is often implemented using Monte Carlo simulation.
7.3 Inventory dynamics
Let's define the quantities we track.
| Symbol | Meaning |
|---|---|
| \(I_t\) | Inventory at the start of period \(t\) |
| \(A_t\) | Replenishment arriving in period \(t\) |
| \(D_t\) | Demand in period \(t\) |
| \(V_t\) | Units sold |
| \(L_t\) | Unmet (lost) demand |
For a simple lost-sales system where arrivals are available before demand is served, let \(B_t=I_t+A_t\) be the inventory available to serve demand. Then:
$$V_t=\min(B_t,D_t),\qquad L_t=\max(0,\,D_t-B_t),\qquad I_{t+1}=\max(0,\,B_t-D_t)$$Here, \(\min\) returns the smaller value and \(\max\) the larger one. These equations assume unmet demand is lost rather than carried forward as backorders. If backorders are allowed, the state-transition equations must be modified.
7.4 An illustrative simulation
Suppose a supermarket starts Monday with 100 units, ignores replenishment for now, and loses sales when stock is insufficient. Imagine that the simulation generates these demands:
| Day | Start | Demand | Sold | Lost | End |
|---|---|---|---|---|---|
| Monday | 100 | 70 | 70 | 0 | 30 |
| Tuesday | 30 | 50 | 30 | 20 | 0 |
| Wednesday | 0 | 80 | 0 | 80 | 0 |
| Thursday | 0 | 40 | 0 | 40 | 0 |
On Monday, \(I_2=\max(0,100-70)=30\). On Tuesday, the supermarket has 30 units but receives demand for 50, so it sells 30 and loses 20 sales: \(L_2=\max(0,50-30)=20\). The example illustrates how inventory decisions influence sales and stockouts over time. In a real simulation, replenishment orders would arrive according to the ordering policy and the supplier lead times.
Part 8. Evaluating inventory policies through simulation
The purpose of simulation is not simply to reproduce inventory movements. It is to evaluate and compare inventory policies under uncertainty. A policy defines how the system makes decisions. A simulation evaluates the consequences of applying that policy.
8.1 Define the cost function
Suppose the retailer incurs holding costs for inventory, penalties for unmet demand, and fixed costs for placing orders. A simplified total cost over \(T\) periods is:
$$C=\sum_{t=1}^{T}\Bigl[h\,I_{t+1}+p\,L_t+K\,\mathbf{1}(O_t\gt 0)\Bigr]$$| Symbol | Meaning |
|---|---|
| \(C\) | Total cost over the simulation horizon |
| \(h\) | Holding cost per unit per period |
| \(p\) | Penalty per unit of unmet demand |
| \(K\) | Fixed cost per order |
| \(\mathbf{1}(O_t>0)\) | Indicator equal to 1 when an order is placed and 0 otherwise |
This is an illustrative cost function. A real model may also include purchasing costs, disposal costs, expiration, salvage value, and transportation.
8.2 Why simulate many scenarios?
Suppose you simulate one week of demand and obtain a total cost of €500. That result depends on the particular demand values generated during that week. A different sequence could produce €800 or €300. One simulation is not enough, so we run \(M\) independent scenarios and average:
$$\widehat{\mathbb{E}[C]}=\frac{1}{M}\sum_{m=1}^{M}C^{(m)},\qquad \text{standard error}\approx\frac{s_C}{\sqrt{M}}$$Here \(C^{(m)}\) is the cost in scenario \(m\), and \(s_C\) is the standard deviation of those costs. For example, if 1,000 scenarios give an average of €9,200, the estimated expected cost is €9,200 over the horizon. The standard error tells you how precise that average is: quadrupling \(M\) halves it.
When comparing policies, run each one on the same set of demand scenarios. Differences in cost then reflect the policies, not luck in the random draws.
8.3 Comparing policies
Suppose we simulate three policies over the same horizon. The following results are hypothetical:
| Policy | Expected total cost | Stockout rate |
|---|---|---|
| A: Conservative inventory | €8,000 | 25% |
| B: Moderate inventory | €9,200 | 10% |
| C: High inventory | €12,000 | 3% |
Policy A has the lowest cost, but the highest stockout rate. Policy C has the lowest stockout rate, but the highest cost. Policy B offers a compromise. Which should the retailer select? It depends on the objective. If the business must keep stockouts below 5%, only Policy C is feasible. Without a service constraint, Policy A is preferable. This leads us to the distinction between simulation and optimization.
Part 9. Simulation versus optimization
These concepts are related but different. Simulation evaluates a policy. Optimization searches for the best policy. Suppose a retailer wants the best order-up-to level \(S\). We test candidate values and, for each, run simulations and estimate expected cost:
| Target \(S\) | 80 | 100 | 120 | 140 | 160 |
|---|---|---|---|---|---|
| Expected cost | €14,000 | €10,500 | €9,200 | €9,700 | €11,300 |
The best tested target is \(S^*=120\), because it has the lowest estimated expected cost. More generally, we can formulate the problem as:
$$\pi^*=\arg\min_{\pi\in\Pi}\ \mathbb{E}[C(\pi)]\qquad\text{subject to}\qquad \operatorname{ServiceLevel}(\pi)\geq 0.95$$where \(\pi\) is an inventory policy, \(\Pi\) is the set of candidate policies (reorder points, target levels, order quantities, or richer rules), and \(\pi^*\) is the best one under the objective. The service-level definition must be specified: a 95% cycle service level is not the same as a 95% fill rate.
Part 10. Putting everything together: An end-to-end retail Data Science pipeline
Let's now connect the concepts into one practical workflow. Imagine you are building an inventory decision-support system for a supermarket chain.
Step 1: Collect historical data
Collect daily sales, prices, promotions, holidays, seasonality, inventory levels, stockouts, and supplier lead times. One critical issue is that observed sales are not always equal to actual customer demand. If the supermarket has only 10 units available and sells all 10, the true demand could have been 10, 15, or 30. Without accounting for stockouts, a forecasting model will systematically underestimate demand.
Step 2: Train a demand forecasting model
Use a regression algorithm such as LightGBM to predict demand from the features. You could start with a point forecasting model, \(\hat D_t=f_\theta(X_t)\), as a baseline.
Step 3: Estimate demand uncertainty
Choose a probabilistic approach. For example, use quantile regression to estimate \(\hat Q_{0.50}(X_t)\), \(\hat Q_{0.80}(X_t)\), and \(\hat Q_{0.95}(X_t)\). Evaluate the forecasts with the pinball loss and calibration checks.
Step 4: Define an inventory policy
Specify the ordering rule, for example: if the inventory position falls below the reorder point, order enough to reach the target level. Set the parameters from the forecasts, the lead time, the underage and overage costs, supplier constraints, and service-level requirements.
Step 5: Simulate inventory
Generate demand scenarios from the forecast model, and simulate demand, sales, inventory, replenishment, stockouts, and costs. Repeat many times. Here is a compact simulator and Monte Carlo loop.
import numpy as np
def simulate(demand, R, S, lead, h, p, K, I0):
T = len(demand)
on_hand = I0
pipeline = np.zeros(T + lead + 1) # pipeline[t] = units arriving at start of day t
cost = lost = 0.0
for t in range(T):
on_hand += pipeline[t] # replenishment arrives (A_t)
sold = min(on_hand, demand[t]) # V_t
lost += demand[t] - sold # L_t
on_hand -= sold # I_{t+1}
ip = on_hand + pipeline[t + 1:].sum()
if ip <= R: # (R, S) rule, lead >= 1
pipeline[t + lead] += S - ip
cost += K
cost += h * on_hand + p * (demand[t] - sold)
return cost, lost / demand.sum()
def sample_demand(taus, qvals, size, rng):
u = rng.uniform(taus[0], taus[-1], size) # tails beyond the grid are truncated
return np.interp(u, taus, qvals)
rng = np.random.default_rng(42)
taus = np.array([0.05, 0.10, 0.25, 0.50, 0.75, 0.90, 0.95])
qvals = np.array([55, 65, 80, 100, 120, 145, 160]) # from your quantile model
scenarios = [sample_demand(taus, qvals, 30, rng) for _ in range(1000)]
for S in [80, 100, 120, 140, 160]:
out = [simulate(d, R=40, S=S, lead=2, h=0.1, p=4, K=20, I0=S) for d in scenarios]
costs = np.array([c for c, _ in out])
print(S, costs.mean().round(0), (costs.std() / np.sqrt(len(costs))).round(1)) For simplicity, days are drawn independently here. Real demand has weekly and promotional structure, so in practice you would sample from forecasts conditioned on each day's features.
Step 6: Optimize the policy
Test alternative policy parameters. For each policy, calculate the expected total cost, stockout rate, fill rate, average inventory, and waste. Select the policy that minimizes expected cost or satisfies the chosen business objective.
Step 7: Validate the result
A policy that works in a simulation is not automatically successful in production. You should also validate forecasts on data not used for training, test the sensitivity to forecast errors and lead-time changes, compare against the existing business policy, perform historical backtesting or a controlled pilot, and monitor performance after deployment.
The final goal is not simply to obtain an accurate forecast, but to produce reliable inventory decisions that improve measurable business outcomes.
Part 11. The key formulas to remember
Here is a compact reference for the notation and objectives.
| Concept | Formula | Meaning |
|---|---|---|
| Point forecast | \(\hat y=f_\theta(x)\) | Predict one number |
| Mean squared error | \(\frac1n\sum_i(y_i-\hat y_i)^2\) | Penalizes squared errors; targets the mean |
| Demand CDF | \(F_D(d)=P(D\leq d)\) | Chance demand is at most \(d\) |
| Quantile | \(Q_\tau=F_D^{-1}(\tau)\) | Demand level at probability \(\tau\) |
| Conditional quantile | \(Q_\tau(D\mid X=x)\) | Quantile given features |
| Pinball loss | \(\rho_\tau(u)=\tau u\) if \(u\geq0\), else \((\tau-1)u\) | Asymmetric loss for quantiles |
| Quantile regression | \(\min_\theta\sum_i\rho_\tau(y_i-f_\theta(x_i))\) | Learn a chosen quantile |
| Inventory position | \(IP_t=I_t+\text{On-order}_t-\text{Backorders}_t\) | Stock plus pipeline minus backorders |
| Order rule | \(O_t=\max(0,S-IP_t)\) if \(IP_t\leq R\) | Order up to \(S\) |
| Newsvendor | \(q^*=F_D^{-1}\!\bigl(\tfrac{C_u}{C_u+C_o}\bigr)\) | Optimal single-period order |
| Simulated cost | \(C=\sum_t[hI_{t+1}+pL_t+K\mathbf{1}(O_t>0)]\) | Illustrative total cost |
| Monte Carlo average | \(\frac1M\sum_m C^{(m)}\) | Expected cost estimate |
| Policy optimization | \(\pi^*=\arg\min_{\pi\in\Pi}\mathbb{E}[C(\pi)]\) | Best policy |
Comments
Post a Comment