Technical

The rule-based method

How the target stock is built, the three families of safety stock, a way to measure the rate of a store that ran out of stock, and the rule's first race against Lumoda's current method.

Warehouse to Store · 4 / 6

For three articles we talked about ideas. Now we write the sum down.

The SQL and Python below were not written for illustration. They are taken from the working code under cases/warehouse-to-store/. Every number in the article comes from that case’s report, report.py, too.

The whole rule-based method fits on two lines:

target stock = max(forecast, safety stock)                      for each store–option
need         = max(target × size share − on the rail − in transit, 0)   for each size

The target is set at store–option level. The size share comes from the past sales of the store’s products in the same category and size set. Take the stock on the rail and in transit off the part of the target that falls to a size, and what is left is that size’s request. The rest of the article is just filling in those two lines.

The forecast

The forecast is next week’s expected sales. In its simplest form, it is last week’s sales:

-- The raw input of the rule's forecast: sales in the 7 days before the
-- decision day (the decision day excluded), physical store × option.
-- $decision_day: the decision Monday. clean_sales: the sales table with its
-- duplicated rows dropped.
with last_week as (
    select s.store_id,
           u.option_id,
           sum(s.units) as sales_7d
    from clean_sales s
    join product u using (product_id)
    where s.units > 0                 -- negative rows are returns, not demand
      and s.store_id <> 'ONL'         -- the online channel is outside this decision
      and s.date::date between $decision_day - 7 and $decision_day - 1
    group by 1, 2
)
select count(*) as pairs, sum(sales_7d) as units
from last_week;

For the first decision Monday this query returns 10,700 store–option pairs and 154,403 units. That is how much the physical stores sold that week.

There is no date written in the query; the decision day is a parameter. The window is the seven days before the decision day. The decision day itself is not in the window, because on Monday morning there are no sales for that day yet.

Two corrections go on top of this. The first is for special days. We measured it in the second article: on a public holiday a store sells 0.59 to 0.62 of a normal day, and on Black Friday 3.24 to 4.41 times as much. We carry the forecast over to next week with these factors: the factors of the next seven days are added up and divided by the sum for the past seven. If there is a Black Friday in the coming week, the forecast grows. If last week had a holiday, it grows too, because that week’s sales looked lower than they really were.

The second correction is for days out of stock. I will give it a heading of its own below; it is the most important part of the method.

Safety stock: three families

On the shop floor safety stockExtra stock held so the shelf is not left empty when sales speed up or stock arrives late. It is added to the forecast as a buffer, or set as a floor for the target. is worked out in three different ways, and each has its supporters.

A fixed quantity. A floor for each store–option: “at least this many of this product on the rail.” On the shop floor this is called a minimum display quantity. It is the simplest method and the easiest to understand.

By rate of sale (ROSA product's average speed of sale over a period, usually in units per day or per week. Measured properly, it is divided by the days the product was on the shelf.). Daily rate of sale × days of cover. On a fast seller the floor goes up; on a product that does not sell, it does not. And the rate, as I describe below, we measure by dividing by the days in stock.

Statistical. Derived from the volatility of demand:

safety stock=Z×σ×period\text{safety stock} = Z \times \sigma \times \sqrt{\text{period}}

Z comes from the service level you want; for 95% it is 1.65. σ is the standard deviation of weekly sales over the last eight weeks. The period is one week, because the next decision is a week later. This is the textbook answer.

We did not pick the parameters by eye. We tuned them in the same season a year earlier, without looking at the game period at all. The statistical family has no parameter to tune; Z is fixed. So we ran it first, with no warehouse constraint, and took its availability as the target: 67.11%. (That is the figure for the period a year earlier. The “no cap” row of the table in the third article also shows 67.11%, but that is a different run, in the game period.) Then for the other two families we looked for the parameter closest to this target: 4 units in the fixed family (67.16%), 6 days for ROS (67.14%). With all three meeting at the same target, we chose the one that gets there with the least stock: the fixed family, with 181,635 units. For the rest of the article, when I say “the rule” I mean this rule, with a floor of 4 units.

Choosing the parameter after seeing the result is like setting the exam questions yourself and then answering them.

Why we don’t add them up

You can write the target two ways:

target = forecast + safety stock
target = max(forecast, safety stock)

The first looks closer to the textbooks. We use the second. The reason comes from the shop floor: safety stock is a floor, not a cushion laid on top of the forecast. Saying “at least four units on the rail” is not saying “put four more units on top of the forecast”. A minimum display quantity is a lower bound.

We measured the size of the difference at target level. Had the target been built by adding the forecast and the floor, the targets of the first 17 Mondays would have been 23.1% bigger than those built with max: 678,840 units more. We did not measure what that does to availability and stock. We only know how much the target would swell.

How often does the floor come into play? On the first 17 Mondays, of the 14,572 pairs on sale on an average Monday, in 6,227 the safety stock is bigger than the forecast and sets the target: 42.7%. In 48.6% of those, the forecast is zero. These are pairs that sold nothing last week, or were never on the rail at all. So in more than two-fifths of the decisions, it is the floor that has the say, not the forecast.

The real problem: demand we cannot see

Now we come to the most important technical subject of the series.

The forecast looks at past sales. But what happens when the rail is empty? A customer comes in, cannot find the product and walks out. Nothing is recorded at the till. That day’s sales are written down as zero, and the system reads that as “there was no demand”. This is called censored demandDemand that arrives while the shelf is empty and is never recorded. Sales data show not demand but the smaller of demand and stock..

The result is a vicious circle. A store that ran out of stock looks slow. Because it looks slow, it gets little stock. Because it gets little stock, it runs out again. On the report everything looks fine, because the loss never gets into a table.

Remember Istanbul 8 from the first article. The Ruffle Blouse in XL was on its rail on only 30 of the 119 calendar days we counted. A system that divides sales by calendar days takes it for a store that sells 0.29 a day. Divide by the days it was on the rail and the rate is 1.13.

The fix: divide by in-stock days, not calendar days

The fix is simpler than you might think. When you work out the rate, take the days with an empty rail out of the denominator. In the code this takes three small functions:

# warehouse_to_store/need.py (rule_forecast's docstring shortened)

def in_stock_days(
    in_stock: np.ndarray, sales: np.ndarray, cell_map: CellMap, decision_day: int, days: int
) -> np.ndarray:
    """float[pairs]: the pair's number of in-stock days in `[decision−days, decision−1]` —
    days on which at least one of its cells was in stock or sold (a sale is never without
    stock). The part before the start of the data is not counted."""
    start = max(decision_day - days, 0)
    out = np.zeros(_pair_count(cell_map))
    for d in range(start, decision_day):
        seen_c = in_stock[d] | (sales[d] > 0)
        seen = np.zeros(_pair_count(cell_map), dtype=bool)
        seen[cell_map.pair[seen_c]] = True
        out += seen
    return out


def _rate(total: np.ndarray, days: np.ndarray) -> np.ndarray:
    """total / days; 0 if days is 0 (module note: a fully censored window)."""
    rate = np.zeros_like(total)
    np.divide(total, days, out=rate, where=days > 0)
    return rate


def rule_forecast(
    sales: np.ndarray,
    cell_map: CellMap,
    decision_day: int,
    factors: dict[str, float],
    in_stock: np.ndarray | None = None,
    *,
    calendar: pd.DataFrame,
) -> np.ndarray:
    """float[pairs]: sales of the last 7 days × the week factor; if `in_stock` is given,
    (sales of the last 7 days / in-stock days of the last 7 days) × 7 × the week factor."""
    last7 = _window(sales, cell_map, decision_day - 7, decision_day)
    if in_stock is not None:
        last7 = _rate(last7, in_stock_days(in_stock, sales, cell_map, decision_day, 7)) * 7.0
    return last7 * pair_week_factor(cell_map, calendar, decision_day, factors)

If a pair was in stock on only 2 of the last seven days and sold 2 units on those 2 days, the forecast is not 2 but 7 units: 1 a day, for seven days. The ROS floor makes the same correction with the last 28 days’ sales. A pair with no in-stock day at all is given a rate of zero: that window says nothing about demand, and the code does not make a number up. That pair’s target is set by the floor.

Note the code’s definition of an “in-stock day”. For a store–option pair, an in-stock day is a day on which at least one of its sizes was on the rail or sold. If there was a sale, the rail cannot have been empty. The definition has a limit too: if the M has sold out but the other sizes are on the rail, the day counts as in stock. This correction does not see gaps at size level. Istanbul 8’s 1.13 in the first article was the rate of a single size, the XL; working at store–option level, this correction does not produce that number, because it counts a day as in stock when the XL has sold out but the other sizes are on the rail.

Let me underline that this is not cheating. We do not touch the lost sales table. Only the referee sees that table; the method making the decision does not. The only thing we use is the store’s own daily stock record.

We measured the effect at target level. On the first 17 Mondays the correction makes the forecast 6.7% bigger and the target 5.3% bigger. We did not measure its effect on availability separately, because we made no rule run without the correction.

One step further: the Lost Sales series’ estimator

Dividing by in-stock days is a rough correction. The Lost Sales series built a method that estimates the demand on a day out of stock more carefully: Simple. It looks at the in-stock days either side of the day out of stock and estimates that day’s loss. At the moment of decision, though, it only sees the past side, because the days after have not happened yet.

We replaced the rule’s forecast with the Simple estimate worked out at the moment of decision: the last seven days’ sales plus the loss Simple writes for those days, again with the week factor. The floor, the pack and the cap stayed the same:

RuleRule + SimpleDifference
Availability65.10%68.07%+2.97 points
Lost sales rate38.89%35.52%−3.37 points
Store stock at the end of the four months311,819333,931+22,112 units
Picking costTRY 7,673,800TRY 8,002,030+TRY 328,230

Simple gives higher availability, but with more stock. We did not separate how much of the gain comes from the stock and how much from the better estimate. We measured this on the published customer stream, in a single scenario. Still, this is where the two series meet: the loss estimate is an input to replenishment.

The three families race

Now we replayed the same four months with the warehouse constraints of the third article (packs and the loose picking cap), changing only the safety stock family:

FamilyAvailabilityStore stock at the end of the four months
Fixed, 4 units65.10%311,819
Statistical, Z = 1.6564.99%324,526
ROS, 6 days64.00%317,083

Fixed and statistical are neck and neck, ROS about a point behind. I am not drawing a lesson from this: we tuned all three to the same target in calibration, and tuned to the same target, the families end up close to each other. The real dial is somewhere else: the height of the floor. We will come to it shortly.

And it is still not enough

First let us look at the rule itself. On the first 17 Mondays the rule set targets totalling 2,936,365 units. In the weeks those targets had to cover, real demand was 3,507,584 units.

So even after the censoring correction, the target is only 83.7% of real demand. The forecast on its own stops at 74.8%; it is the floor that lifts the target to 83.7%.

There is one way to make the target bigger: raise the floor.

The real lever: how much stock

In the first article I made a promise: Lumoda’s current method is a rule too, and we would race the two in the same warehouse. In the second article I made another: the most surprising finding of the series would come from how we define the safety margin. Both are now due.

Let us recall Lumoda’s rule. The sales the plan writes for that store for the next four weeks, minus the stock on the rail and in transit. A store that has not sold the product at all in the last four weeks gets no request. We ran this rule under the same warehouse constraints too: the same pack rule, the same loose picking cap. And when sharing out scarce stock we used Lumoda’s current method: pro rata to the request.

The result: availability is 73.87% under Lumoda’s rule and 65.10% under ours. A gap of 8.77 points. In five different customer streams over the same four months Lumoda is ahead too; the gap is between 7.54 and 8.77 points.

But look at the price. At the end of the four months Lumoda’s stores hold 428,097 units and ours 311,819. Lumoda’s store stock is 37.3% higher than ours. Stock reaching a store sells in 16.5 days on average at Lumoda and in 7.5 days with us. The picking cost is TRY 943,300 higher too. Lumoda sells more by holding more stock.

That is why comparing the two methods with a single number is misleading. The right question is: with the same stock, which one gives more availability?

To make the rule hold more stock, we did not need to touch its code. We changed the floor: we raised the ROS family’s days of cover to 14, 21 and 28 days. That way the target becomes the bigger of a week’s forecast and two, three or four weeks of sales. A rule that looks like Lumoda’s four-week target.

MethodAvailabilityStore stock at the end of the four monthsDays to sale
Rule, floor 4 units65.10%311,8197.5 days
Rule, floor 14 days’ sales69.34%397,03313.8 days
Rule, floor 21 days’ sales70.44%419,69616.7 days
Lumoda73.87%428,09716.5 days
Rule, floor 28 days’ sales70.75%443,41518.0 days

Days to sale is the average number of days from a unit reaching the store to its sale, counted over the units sold only.

As the floor goes up, so does the rule: 65.10% with a 4-unit floor, 70.44% with a 21-day floor. At Lumoda’s stock level (428,097 units) we read the rule’s availability by straight-line interpolation between the 21-day and 28-day floors: 70.55%. Lumoda is at 73.87%. At equal stock the gap is 3.32 points.

So when we raise the floor and give the rule as much stock as Lumoda, 5.45 points of the 8.77-point gap close. That part comes not from the rule’s sums but from how much stock it is willing to carry.

This was the promise from the second article. Define the safety margin as “at least four units on the rail” and the rule works with lean, fast-turning stock but misses part of the demand. Define it as “three weeks of sales” and it comes close to Lumoda. The families sit close to each other because they were tuned to the same target; the real dial is the height of the floor. That dial closes 5.45 points of the gap to Lumoda.

This is a choice: how much stock do you want to carry? The right answer varies from chain to chain. But when you decide, compare the two methods not with a single number but on the curve between availability and stock.

That leaves 3.32 points. Even with the same stock, Lumoda’s rule gives higher availability. We will look at where that gap opens up in the last article.

What is hard in your data

The part of this article people will talk about most is probably the safety stock families. But what is hard in your data is most likely two other things.

The first is the in-stock day. The censoring correction needs an answer, for every store, every product and every day, to the question “was the rail empty?”. At Lumoda that record is complete. In a real chain, building daily stock is a job in itself: count variances, transfers booked late, returns. Wherever you count in-stock days wrong, the rate comes out wrong too.

The second is the comparison itself. We could compare the rule with Lumoda’s method at the same stock because we could play both methods on the same customer stream and measure availability. In your chain you cannot run two methods side by side in the same season, and the customer who comes in while the rail is empty is not written down anywhere. Taking your current rule as the baseline and comparing the new one at the same stock level is the hardest step. It is also the most necessary.

In the next article we move on to forecasting. We will build a store–option level forecast with LightGBM and play the same four months with it. I expected the model to do better. The result did not turn out as I expected.

By Sabri Suyunu