Inventory 4: A Price That Reacts
Requires Pro (SharedState; ServiceCall in the optional last section)
Problem statement
Lesson 5.2 gave the store a loop of its own: the stock decides the order, the order changes the stock, and every trip around the loop goes through a cell and takes one row. This lesson adds a second loop on top of it, and the second loop reaches the customers. The shelf price follows the stock (it rises when the shelf runs low and falls when the shelf is full), and the demand follows the price (a higher price sells less). Now a change in demand moves the stock, the stock moves the price, and the price moves the demand. Whether that settles down depends on how hard the price reacts, and a loop made of delayed reads can overreact.
The store is the one of lesson 5.2, with every choice unchanged: one row is one day; the reorder point is R = 16 and the order quantity Q = 40; an order takes 2 days; unmet demand is lost; it starts with 40 units and nothing on order. Its four measures are the ones of lessons 5.1 and 5.2 (stockout day, fill rate, average stock, orders a year), and two more are added because there is now a price: units sold a year, and revenue a year, which is the sum over days of the shelf price times the units sold that day.
The new parts, with every choice made once:
- The demand law. At the base price of 10, demand is the
NegativeBinomialof the earlier lessons (r = 8, mean 8, variance 16). At another price the mean follows a constant-elasticity law, mean demand = 8 (price / 10)^-1.5: 1% more on the price sells 1.5% less. The shaper = 8stays fixed, so the demand stays overdispersed. - The price rule. The price moves a little every day, by G dollars for every unit by which the (smoothed) stock is below the target of 21, and by the same amount downward for every unit above it. G is the response strength: dollars of price per unit of shortage per day. The price is kept between 8 and 12. The stock the rule looks at is smoothed: each day it moves a tenth of the way towards the day’s stock, which averages out the saw-tooth of 40-unit deliveries.
- The price the customers see is the price the rule has set, shown to the nearest 25 cents.
The questions:
- How does the demand follow a price when the distribution’s parameters are fixed when the model loads, and how can a lesson say exactly what the mean is?
- As G grows, what does the price do? Does it settle to a steady band, and when does it start to oscillate or swing?
- Can the onset be predicted, with the one-row delays of the cells worked out by hand?
- What does the reacting price do to stockouts, fill rate and revenue, against the lesson 5.2 store at a fixed price?
- Can the pricing rule live outside the model, in a small program on this machine, and give the same result?
The model
Four cells now. stock and due are the cells of lesson 5.2. avg holds the smoothed stock, and price holds the price the rule has set. The two loops, drawn through the cells:
The model is samples/pro/inventory-price-feedback.xml. It is lesson 5.2’s store with the new nodes added, and it is shown here with 14 of its 17 demand nodes left out (they are the same line with another price and another p):
<dataset columns="stock, lost, demand, priceCharged, orderDue, priceSet, smoothedStock" seed="701">
<root node="Day"/>
<nodes>
<SharedState name="Store" cells="stock=40, due=0, lost=0, demand=0, charged=10, price=10, avg=21"/>
<StateRead name="ShelfForPolicy" collaborate.state="Store" cells="stock, due"/>
<Calculate name="Policy" dimension="1" expression="y[0] = if(x[0] + x[1] <= 16, 40, 0)">
<input name="ShelfForPolicy"/>
</Calculate>
<StateWrite name="PlaceOrder" collaborate.state="Store" cells="due" mode="set">
<input name="Policy"/>
</StateWrite>
<StateRead name="ShelfForAvg" collaborate.state="Store" cells="stock, avg"/>
<Calculate name="Smooth" dimension="1" expression="y[0] = round(1000 * (x[1] + 0.1 * (x[0] - x[1]))) / 1000">
<input name="ShelfForAvg"/>
</Calculate>
<StateWrite name="SetAvg" collaborate.state="Store" cells="avg" mode="set">
<input name="Smooth"/>
</StateWrite>
<StateRead name="ShelfForPrice" collaborate.state="Store" cells="avg, price"/>
<Calculate name="Reprice" dimension="1" expression="y[0] = round(100 * min(12, max(8, x[1] + 0.05 * (21 - x[0])))) / 100">
<input name="ShelfForPrice"/>
</Calculate>
<StateWrite name="SetPrice" collaborate.state="Store" cells="price" mode="set">
<input name="Reprice"/>
</StateWrite>
<StateRead name="ShelfForSales" collaborate.state="Store" cells="stock, due, price"/>
<Calculate name="Shelf" dimension="3" expression="y[2] = 8 + round((x[2] - 8) * 4) / 4">
<input name="ShelfForSales"/>
</Calculate>
<NegativeBinomial name="At800" r="8" p="0.417094..."/>
<NegativeBinomial name="At825" r="8" p="0.428357..."/>
<!-- At850 to At1175: the same line, one per 25 cents -->
<NegativeBinomial name="At1200" r="8" p="0.567948..."/>
<Switch name="Morning" key="2">
<input name="Shelf" role="input"/>
<input name="At800" value="8"/>
<input name="At825" value="8.25"/>
<!-- the other branches: value 8.5 to 11.75 -->
<input name="At1200" value="12"/>
</Switch>
<Calculate name="Sales" dimension="4"
expression="y[0] = max(0, x[0] + x[1] - x[3]); y[1] = max(0, x[3] - x[0] - x[1]); y[2] = x[3]; y[3] = x[2]">
<input name="Morning"/>
</Calculate>
<StateWrite name="Close" collaborate.state="Store" cells="stock, lost, demand, charged" mode="set">
<input name="Sales"/>
</StateWrite>
<Append name="Day">
<input name="Close"/>
<input name="PlaceOrder"/>
<input name="SetPrice"/>
<input name="SetAvg"/>
</Append>
</nodes>
</dataset>
(The three dots stand for the digits the file has, twelve decimals each; the comments are shown only here, since the file has none for those lines.) The model has 33 nodes in the file. What the parts are:
| Node | What it is |
|---|---|
Store | The cells, with their starting values: stock 40, due 0, lost and demand as in lesson 5.2, charged (the shelf price that today’s customers paid), price (the price the rule has set, from the next row on) starting at 10, and avg (the smoothed stock) starting at 21. |
ShelfForPolicy, Policy, PlaceOrder | The reorder rule of lesson 5.2, unchanged. |
ShelfForAvg, Smooth, SetAvg | The smoothing: avg moves a tenth of the way towards the stock, kept to three decimals so the output reads cleanly. A one-line Calculate of its own. |
ShelfForPrice, Reprice, SetPrice | The price rule: the old price plus 0.05 times how far the smoothed stock is below the target 21, kept between 8 and 12 and rounded to the cent. 0.05 is G, a plain number in a 68-character expression, so that the sweep below changes one number in the file. |
ShelfForSales, Shelf | Reads stock, due and price for today’s sales, and turns the price into the shelf price: the nearest 25 cents. |
At800 to At1200, Morning | The demand: 17 NegativeBinomial nodes, one for each shelf price from 8.00 to 12.00, and a Switch that reads the shelf price (column 2) and draws from the node whose value is that price. Its output is the three columns it was given plus the demand. |
Sales, Close | As in lesson 5.2, plus the shelf price passes into the cell charged, so the row carries the price the day’s customers paid. |
Day | The row: stock, lost, demand, the price charged, the order, the price set, the smoothed stock. |
The demand law, and why it takes 17 nodes
A node’s parameters are fixed when the model loads, so the price cannot be fed into p. Switch is the tool for “pick one of several generators from a column”: it advances only the branch it picks, so each day draws one number. The price is first rounded to a shelf price (25 cents) so that there are 17 possible prices and not infinitely many; the demand of the day then comes from the node for that price.
The mean can be made exact. A negative binomial with r fixed has mean r (1 - p) / p and variance m + m^2 / r for its mean m. So to get the mean m(price) = 8 (price / 10)^-1.5, set p = 8 / (8 + m). That is exact, up to the twelve decimals written in the file (the largest gap between the written mean and the law is 2e-11), and the variance follows: it is 16 at the base price and larger at lower prices, where the mean is larger. (A second way is to draw the demand at a high price and thin it with a Binomial: thinning a negative binomial keeps r and scales the mean exactly. It cannot be used here because the thinning probability would have to come from the price, and it can only lower demand, so a price below the base could not raise it.)
| Shelf price | Mean demand | Variance | p |
|---|---|---|---|
| 8 | 11.1803 | 26.805 | 0.417094 |
| 9 | 9.3697 | 20.344 | 0.460572 |
| 10 | 8.0000 | 16.000 | 0.500000 |
| 11 | 6.9343 | 12.945 | 0.535681 |
| 12 | 6.0858 | 10.715 | 0.567948 |
One row at a time
Run one year with the model’s own seed:
grind --count 365 inventory-price-feedback.xml
The first ten rows (seed 701):
| Day | Demand | Stock at end | Price charged | Order (arrives tomorrow) | Price set | Smoothed stock |
|---|---|---|---|---|---|---|
| 1 | 8 | 32 | 10.00 | 0 | 10.00 | 22.9 |
| 2 | 11 | 21 | 10.00 | 0 | 9.90 | 23.81 |
| 3 | 8 | 13 | 10.00 | 0 | 9.76 | 23.529 |
| 4 | 9 | 4 | 9.75 | 40 | 9.63 | 22.476 |
| 5 | 5 | 39 | 9.75 | 0 | 9.56 | 20.628 |
| 6 | 10 | 29 | 9.50 | 0 | 9.58 | 22.465 |
| 7 | 8 | 21 | 9.50 | 0 | 9.51 | 23.119 |
| 8 | 7 | 14 | 9.50 | 0 | 9.40 | 22.907 |
| 9 | 7 | 7 | 9.50 | 40 | 9.30 | 22.016 |
| 10 | 15 | 32 | 9.25 | 0 | 9.25 | 20.514 |
Row 1 reads the starting cells (stock 40, avg 21, price 10): the price charged is 10.00, the smoothed stock moves from 21 to 21 + 0.1 (40 - 21) = 22.9, and the price rule sees the old smoothed stock, 21, and the old price, 10, so it keeps 10.00. Row 2 reads the smoothed stock of row 1, 22.9, which is above the target by 1.9: the price falls by 0.05 x 1.9 = 0.095, to about 9.905, which the rule rounds to 9.90. The price charged on day 3 is still 10.00, because the price set on day 2 (9.90) is within 12.5 cents of 10; the price charged on day 4 is 9.75, the nearest quarter to the 9.76 set on day 3. Every column of a row is a function of the cells as they stood at the end of the row before. That is the double-buffered rule of lesson 5.2, and it is what turns the price loop into a delayed one (below).
All six of those relations were recomputed in Python from the previous row’s columns for all 365 rows of seed 701 and for 100,000 rows of seed 7: the price set, the smoothed stock, the price charged, the stock, the lost units and the order each equal what the rule says in every row (0 differences). The price never leaves 8.00 to 12.00 in the 100,000 rows, and all 17 shelf prices occur.
The year of seed 701: 19 stockout days, 2,847 of 2,918 units demanded sold (fill rate 97.57%), revenue 29,605.25, and a price that averages 10.54 (sd 0.73, from 8.04 to 11.97). A single year is one draw from a price that wanders slowly, as the sections below show: the long-run mean price at G = 0.05 is 10.08.
Check first: the store at a fixed price
Before the loop is closed, the pieces can be tested with G = 0, where the price stays where it starts. Five prices (the starting price is the only change), 40 runs of 250,000 days each (the first 1,000 days of each run dropped), set beside the exact answer of a Markov chain over (stock, order due) for a store with negative binomial demand of that mean (the chain of lessons 5.1 and 5.2 with a different p). Each cell is measured (exact):
| Price | Mean demand | Variance | Stockout days a year | Fill rate | Average stock | Units sold | Revenue |
|---|---|---|---|---|---|---|---|
| 8 | 11.1818 (11.1803) | 26.82 (26.81) | 51.84 (51.80) | 91.745% (91.753%) | 16.415 (16.419) | 3,744.4 (3,744.3) | 29,955 (29,954) |
| 9 | 9.3683 (9.3697) | 20.32 (20.34) | 29.84 (29.88) | 95.449% (95.444%) | 18.850 (18.850) | 3,263.8 (3,264.1) | 29,374 (29,377) |
| 10 | 7.9998 (8.0000) | 15.99 (16.00) | 16.11 (16.11) | 97.617% (97.614%) | 21.001 (21.003) | 2,850.3 (2,850.3) | 28,503 (28,503) |
| 11 | 6.9354 (6.9343) | 12.95 (12.95) | 8.23 (8.23) | 98.798% (98.801%) | 22.855 (22.857) | 2,501.0 (2,500.7) | 27,511 (27,507) |
| 12 | 6.0842 (6.0858) | 10.71 (10.72) | 4.03 (4.03) | 99.418% (99.415%) | 24.430 (24.428) | 2,207.8 (2,208.3) | 26,494 (26,500) |
The demand has the mean and the variance the law says, and the store’s service follows. The base price reproduces lesson 5.2: 16.11 stockout days a year, fill rate 97.617%, 21.001 average stock, all equal to the exact values of that lesson (16.113, 97.614%, 21.003). Revenue is units sold times the price, so it is exact too: the model’s price times the units sold, 10 x 2,850.33 = 28,503. Note what the table says about the economics before any feedback: with an elasticity above 1, a higher price earns less (29,954 at 8 against 26,500 at 12), because the units sold fall faster than the price rises. Nothing in this lesson claims the price rule earns money. It is a loop to be studied.
The same table gives the number the loop’s prediction will need. The average stock at the end of the day rises with the price, because a higher price means less demand. Near the base price, the exact chain gives a slope of K = 2.004 units of stock per dollar of price (a central difference over prices 9.95 and 10.05; between the prices 9 and 11 above, 18.850 and 22.857, it is 2.004 as well).
Settle, oscillate, swing
Now close the loop. The sweep: eleven response strengths, from G = 0 (no response, the lesson 5.2 store) to 1, with 20 runs of 100,000 days for each (the first 1,000 days dropped, a different seed in each run). The sample ships with G = 0.05. Every other G is the same file with that one number changed. A first look at three of them, the same days of a seed-701 run:
The stock (blue) looks the same in all three. The price (rust) does not. What it does is measured by its autocorrelation: the correlation between the price today and the price k days later. A price that wanders slowly has an autocorrelation that falls slowly from 1 and stays positive. A price that cycles has one that dips below zero: if the first dip is at lag L, the cycle is about 2 L days long, and the depth of the dip says how regular the cycle is. The table (mean of 20 runs; the standard errors of the means are about 0.003 for the price, 0.03 to 0.06 days for the stockout days, 0.01 percentage points for the fill rate, 1 for the units sold and 6 to 10 for the revenue):
| G | Price mean | Price sd | Range, mean of the runs | Days at a limit | Dip of the autocorrelation | Cycle (days) | Stockout days | Fill rate | Units sold | Revenue |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 10.000 | 0 | 10.00 to 10.00 | 0% | none | none | 16.07 | 97.63% | 2,850 | 28,502 |
| 0.002 | 9.993 | 0.21 | 9.26 to 10.71 | 0% | none | none | 16.30 | 97.57% | 2,855 | 28,507 |
| 0.005 | 10.013 | 0.34 | 8.80 to 11.22 | 0% | none | none | 16.32 | 97.55% | 2,851 | 28,498 |
| 0.01 | 10.017 | 0.49 | 8.20 to 11.80 | 0% | none | none | 16.60 | 97.46% | 2,851 | 28,463 |
| 0.02 | 10.032 | 0.69 | 8.00 to 12.00 | 0.2% | 0.04 (4 of 20 runs at 0.05 or more) | about 160 | 17.20 | 97.29% | 2,851 | 28,418 |
| 0.05 | 10.082 | 1.06 | 8.00 to 12.00 | 5.4% | 0.23 | 67 | 18.49 | 96.88% | 2,855 | 28,353 |
| 0.1 | 10.122 | 1.31 | 8.00 to 12.00 | 16.9% | 0.33 | 45 | 19.85 | 96.48% | 2,859 | 28,281 |
| 0.2 | 10.150 | 1.50 | 8.00 to 12.00 | 31.9% | 0.35 | 32 | 21.00 | 96.13% | 2,865 | 28,227 |
| 0.3 | 10.165 | 1.57 | 8.00 to 12.00 | 40.6% | 0.34 | 28 | 21.50 | 95.98% | 2,869 | 28,209 |
| 0.5 | 10.185 | 1.65 | 8.00 to 12.00 | 51.0% | 0.31 | 22 | 22.08 | 95.83% | 2,868 | 28,166 |
| 1 | 10.212 | 1.73 | 8.00 to 12.00 | 63.4% | 0.25 | 18 | 22.63 | 95.63% | 2,867 | 28,123 |
The measured autocorrelation, as a function of G, with the 20 runs behind each point:
Three regimes:
It settles for G of 0.01 and below. The price wanders slowly around 10 and never cycles: the autocorrelation stays positive out to 140 days in every run. It is not a point, because the stock keeps sending noise into the price. The price sd grows like the square root of G (sd divided by the square root of G is 4.65, 4.77, 4.86 and 4.91 for G = 0.002, 0.005, 0.01 and 0.02): each day’s stock error pushes the price by G times that error, and the loop’s restoring force, which is also proportional to G, pulls it back, so the band is wide in proportion to the square root. At G = 0.005 the sd is 0.34, so on most days the price is between about 9.3 and 10.7 (the ranges in the table are the extremes over 100,000 days).
It oscillates from about G = 0.02 up to about G = 0.2. A dip appears (4 of 20 runs at G = 0.02, all 20 from G = 0.05) and deepens, the cycle shortens from about 160 days to 32, and the price starts to touch its limits (5% of days at G = 0.05, 32% at 0.2).
It swings above G = 0.256, which is where the loop below stops being stable. The price is at 8 or at 12 on 41% of days at G = 0.3 and 63% at G = 1; the trace at G = 0.5 is a square-ish wave between the limits, with a cycle of 22 days. The cycle gets shorter with a stronger response (28, 22, 18 days at G = 0.3, 0.5, 1) and its dip gets a little shallower, because with the limits on, a faster reaction cannot make the swings bigger, only quicker.
Why: the linearised loop
A round trip around the price loop takes three rows. Follow a price. The price set at the end of row t - 1 is the price of the shelf in row t, so it changes the demand of row t and with it the stock at the end of row t. The smoothing node reads that stock in row t + 1 and writes it into avg at the end of that row. The price rule reads avg in row t + 2, and the new price it writes is charged from row t + 3. Three reads, each one row behind, and between the first and the second the smoothing spreads the stock over about ten days. A feedback that corrects late corrects too much: that is the mechanism of the oscillation.
For small movements around the base price the loop can be written down. Let p be the price minus 10, a the smoothed stock minus 21 and s the stock minus its mean, and let the weight of the smoothing be 0.1:
- the price rule:
p(t+1) = p(t) - G a(t); - the smoothing:
a(t+1) = 0.9 a(t) + 0.1 s(t); - the stock follows the price with the gain
Kand the one-row delay:s(t) = K p(t-1), plus noise.
The third line treats the plant as if it responded at once to a price change, with the static gain K = 2.004 that the exact chain gave above. It is an approximation: a change in demand shows in the stock the same day and is partly undone by the reorder policy over the next two to five days, so the plant is not static. The smoothing, with its time constant of ten days, makes that fast enough to ignore. This is a reading, and the comparison below is the test of it.
Eliminating a and s, a price movement behaves like z to the power of its row number, where z is a root of
z^3 - 1.9 z^2 + 0.9 z + 0.1 G K = 0.
The loop is stable while the roots stay inside the unit circle, and it starts to cycle without damping when a pair of roots reaches it. With K = 2.004 that happens at G = 0.2558, and at that G the cycle is 28.4 days long. Without the smoothing (weight 1, the price rule reading the stock directly) the polynomial is z^3 - z^2 + G K, the three-row loop alone, which is stable below G K = 2 sin(pi / 10) = 0.618, G = 0.308, with a cycle of exactly 10 days. The smoothing lowers the critical response strength by a sixth and stretches the cycle almost threefold.
Below that G the loop is stable but not still: noise keeps ringing it, and it rings more the nearer the roots are to the unit circle. The linearised loop gives the period and the shape of that ringing without any simulation. Against the measurements:
| G | Slowest root, modulus | Cycle, predicted | Cycle, measured | Dip, predicted | Dip, measured (sd over runs) | Days at a limit |
|---|---|---|---|---|---|---|
| 0.01 | 0.971 | none | none | 0 | 0 | 0% |
| 0.02 | 0.953 | 145 | about 160 | 0.03 | 0.04 (0.02) | 0.2% |
| 0.05 | 0.960 | 68 | 67 | 0.25 | 0.23 (0.01) | 5.4% |
| 0.1 | 0.970 | 46 | 45 | 0.50 | 0.33 (0.01) | 16.9% |
| 0.2 | 0.990 | 32 | 32 | 0.85 | 0.35 (0.01) | 31.9% |
| 0.3 | unstable | (28.4 at the critical G) | 28 | none | 0.34 (0.01) | 40.6% |
The cycle matches at every G where it exists: 68 against 67 days at G = 0.05, 46 against 45, 32 against 32, and the whole autocorrelation of the price at G = 0.05 follows the prediction closely (the measured and predicted values at lags 5, 10, 20, 33, 50, 70 and 100 are 0.881 and 0.889, 0.616 and 0.631, 0.055 and 0.062, -0.227 and -0.247, -0.055 and -0.065, 0.047 and 0.060, -0.008 and -0.015). The depth of the dip matches up to G = 0.05, and then the prediction runs ahead: 0.50 against 0.33 at G = 0.1 and 0.85 against 0.35 at G = 0.2. The linearised loop has no limits at 8 and 12, and the simulated price has: it is at a limit on 17% and 32% of days at those G, which flattens the swings and cuts their autocorrelation. Past G = 0.256 the loop is unstable and the linearised prediction has nothing to say about the amplitude, which is set by the limits. It does say something about the period: the cycle at G = 0.3 is 28 days, the cycle of the loop at its critical G (28.4).
How far to trust that? As a prediction of where the cycle starts and how long it is, well: the onset the model predicts is a gradual one (the roots approach the circle slowly, so the dip grows from 0 at G = 0.01 to 0.25 at 0.05), and the simulation does exactly that. As a prediction of a sharp threshold at G = 0.256, only roughly: nothing in the simulated price changes abruptly at that G, because demand noise keeps the loop excited on both sides and the limits take over the amplitude on the far side. The measured quantity that does change near it is the share of days at a limit, which passes 40% at G = 0.3.
What does the loop do without the noise? With the demand set to its mean at every price (no random draws, the price not rounded), the same loop gives a price range, over days 3,001 to 4,000, of 0.31 at G = 0.005, 0.46 at 0.01, 1.79 at 0.02 and 3.06 at 0.05 (reaching the limit 12.00); the same four settings with the noise have price sds of 0.34, 0.49, 0.69 and 1.06. So the noise-free loop is not a cleaner version of the same story: it wanders less at the smallest G and swings far more at 0.05. This exercise did not isolate the cause; a likely one is that with demand fixed at 8 the orders come every 5 days exactly, so the average stock is not a smooth function of the price but a staircase (an order cycle is a whole number of days), and the static gain K does not describe it. It is the demand noise that smooths the plant, which is why K comes from the Markov chain over the noisy demand and not from a deterministic calculation.
What the reacting price does to the business
The baseline is the lesson 5.2 store at a fixed price of 10: the G = 0 row of the sweep, and the shipped store of lesson 5.2 run the same way (40 runs of 100,000 days: 16.14 stockout days a year, exact 16.11; fill rate 97.60%; 21.007 average stock, exact 21.003; revenue 28,491, exact 28,503). Beside it, from the table above and the rest of the sweep:
| G = 0 | G = 0.005 | G = 0.05 | G = 0.5 | |
|---|---|---|---|---|
| Stockout days a year | 16.07 | 16.32 | 18.49 | 22.08 |
| Fill rate | 97.63% | 97.55% | 96.88% | 95.83% |
| Days that end with an empty shelf | 5.44% | 5.53% | 6.10% | 7.08% |
| Sd of the end-of-day stock | 12.49 | 12.50 | 12.61 | 12.74 |
| Average stock | 21.01 | 21.00 | 20.99 | 20.89 |
| Orders a year | 71.26 | 71.26 | 71.38 | 71.70 |
| Units sold a year | 2,850 | 2,851 | 2,855 | 2,868 |
| Mean shelf price | 10.000 | 10.013 | 10.082 | 10.186 |
| Mean price paid per unit sold | 10.000 | 9.997 | 9.930 | 9.821 |
| Revenue a year | 28,502 | 28,498 | 28,353 | 28,166 |
In this model the reacting price does not pay. Every response strength above zero gives more stockout days and a lower fill rate than the fixed price, and revenue falls by 0.5% at G = 0.05 and 1.2% at G = 0.5, while the average stock does not change. The units sold go up slightly (2,855 against 2,850 at G = 0.05). The mean shelf price goes up (10.08 against 10), but the mean price paid per unit sold goes down (9.93), because the days with a low price are the days with more customers. The likely reason for the worse service is that the price moves the mean demand over several days at a time, by about 1.5% for every 1% of price, and the reorder policy, with its two days of lead time and its fixed R, was sized for the steady demand of 8; it does not know that demand has moved. That is a reading, and it is not measured here: what is measured is that the stock’s spread and the share of empty days grow with G while the average stock stays at 21. The target of 21 was chosen so that the average price would stay at 10, which it nearly does (10.08 at G = 0.05).
The point is not that a pricing rule has to do worse. The point is that the rule above is a controller, with a delay, and a controller with a delay has to be tuned. Lesson 5.5 comes back to this kind of question for the reorder policy itself, with a cost function and a fair way of comparing.
Pricing outside the model: ServiceCall
The price rule is twelve words of arithmetic here, but in a real business it might be a table, a program, or another team’s service. The Pro component ServiceCall calls out to a program over HTTP for each row, and puts what it answers into the row. This section replaces Reprice with a call to a program on this machine and runs the same year. It is optional: nothing else in the lesson uses it, and everything above ran without it.
What ServiceCall is, and is not. It speaks its own small protocol, spicegrinder.servicecall/v1, to a URL: the model POSTs a JSON request; the service answers either that it needs one of the model’s inputs ({"action": "need", "inputs": ["ShelfForPrice"]}), which SpiceGrinder then draws and sends back in the next request, or with the result ({"action": "result", "values": ["9.9"]}). So each row costs two requests to the service. It is not the ModelService that serves SpiceGrinder models over HTTP: that one answers requests to run a model, in a different format, and cannot be the other end of a ServiceCall. The other end is any program that speaks the protocol. Convert is a separate component for bringing a whole object into the model from a text value; it is not needed when the service returns a number, which is the case here, so this model does not use it.
The files are two: samples/pro/inventory-price-service.py, a 50-line Python 3 script that holds the price rule (standard library only; it is the pricing “model” here, as a program), and samples/pro/inventory-price-service.xml, which is the model above with Reprice replaced by
<ServiceCall name="Reprice" url="http://127.0.0.1:8765/price" outputs="numeric">
<input name="ShelfForPrice"/>
</ServiceCall>
Three steps run it (paths relative to the folder that holds the samples).
- Allow the address.
ServiceCallis off until an operator allows an address, so that a model file cannot reach out to any URL it likes. Add one line to~/.spicegrinder/preferences.properties(create the file if it is not there; it is read at the start of each run):
The URL is matched against each entry by scheme, host, port and path (not as a raw text prefix), an empty list disablesservice.url.allowlist=http://127.0.0.1:8765/ServiceCallentirely, and the setting applies to every model you run as that user, so it is worth removing when you are done. Without it the run stops before any row withERROR: Service calls disabled: service.url.allowlist is empty in /home/you/.spicegrinder/preferences.properties. Add entries (e.g. http://localhost:9000/).(with your own home folder in the path) - Start the service, in its own terminal:
It bindspython3 samples/pro/inventory-price-service.py127.0.0.1only, so nothing outside this machine can reach it, and it keeps no state: its answer depends only on the request. Stop it with Ctrl+C. - Run the model, in another terminal:
grind --seed 701 --count 365 samples/pro/inventory-price-service.xml
The result is the model’s own output, to the byte. The 365 rows of seed 701 through the service are identical to the rows of inventory-price-feedback.xml with the same seed, and so are 20,000 rows of seed 7. A second run of the 365 rows is byte for byte the first. The price rule in the Python script rounds to the cent the way the model’s round does, so the two agree exactly, and the in-model version is the reference. One year takes 1.1 seconds including the JVM start; 20,000 rows take 6.9 seconds (about 2,900 rows a second, two requests each), which makes the service practical for a run or a year and slow for the 20 x 100,000-day sweeps above, which ran in-model.
Three things to know. First, SpiceGrinder’s exact replay covers the model, not the service: this run repeats because the script is a pure function of what it is sent, and a service with its own random numbers or a clock would not repeat. This lesson’s check is the equality above. Second, the script keeps its HTTP connection open (protocol_version = "HTTP/1.1"); the first version, on Python’s default of closing the connection after each answer, failed at row 2,680 of a long run with HTTP/1.1 header parser received no bytes, because the Java client was reusing a connection the server had closed. Third, a service that is not running gives ERROR: ServiceCall 'Reprice': request to http://127.0.0.1:8765/price failed: null, which names the node and the URL but not the cause. The service model is not in the golden-output gate or a recorded CSV, because it needs the service running.
Check: do the numbers match the math?
What was checked, and what the check can and cannot say.
The demand law and the service at fixed prices. The table above has 35 comparisons of a measured value with the exact chain (7 measures at 5 prices; the orders, the units sold and the revenue are the same comparison, since units sold are 40 times the orders). The largest |z| is 2.11 (the sd of the stock at price 10); one comparison is beyond 2, which is about what chance gives for 35, and none beyond 3. The mean demand at the five prices has z values +0.89, -1.02, -0.15, +0.96 and -1.59, and the variances agree to within about 0.1%. A first pass with 20 runs per price had one outlier (the orders at price 9, z -4.1); with 40 runs it is -0.8. The standard errors here come from the spread of 20 or 40 run means, and a spread estimated from 20 values is itself noisy.
The base case against lesson 5.2. The model at G = 0 gives 16.07 stockout days, 97.63% fill rate and 21.01 average stock (20 runs), against the exact 16.11, 97.61% and 21.00 of lesson 5.2’s store; they are the same store with the demand drawn through a Switch. Run row for row they are not identical: the demand comes from a different node, which draws from its own stream, so the same seed gives a different demand. The two models agree in distribution, which is what the chain test checks.
The row relations. Six relations (price, smoothed stock, shelf price, stock, lost units, order) hold in 365 of 365 and in 100,000 of 100,000 rows, as stated above.
The linearised loop. Compared with the simulation above: periods within 1 day for G = 0.05 to 0.2 (68 against 67, 46 against 45, 32 against 32), 145 against about 160 at G = 0.02 (where the dip is 0.04 deep and the lag poorly determined: the 20 runs have a lag sd of 21 days), the autocorrelation at G = 0.05 within 0.02 at seven lags, and the dip depth matching up to G = 0.05 and over-predicted beyond it, because the limits of the price are not in the linearisation. The critical G of 0.256 has no sharp counterpart in the noisy simulation, as said above.
Conservation. Revenue is the sum of the price charged times the units sold (demand minus lost): 29,605.25 for the seed-701 year, computed two ways. The long-run orders a year times 40 equal the units sold (71.26 x 40 = 2,850 at G = 0) and tend to the mean demand times 365 when the stock keeps up.
What the model leaves out
Everything lessons 5.1 and 5.2 left out is still out: a fixed lead time, orders that arrive whole, demand independent from day to day, customers lost for good, no costs. What this lesson adds is a demand law with a constant elasticity and nothing else about customers: no customer who waits for a lower price, no competitors, no memory of yesterday’s price, and no difference between a price rise and a price fall. The price rule has a floor and a ceiling, a target stock chosen so the average price stays near 10, and one smoothing weight; none of these were tuned. The price is quantized to 25 cents on the shelf, which makes the demand steps of about 3.8% at the base price. And the stability analysis is of a linearisation with a static gain: it is the first thing to check against a simulation and it does not replace one.
What this gives you: a second feedback loop, through the same four-cell idiom as lesson 5.2: a smoothing node that keeps a running average in a cell, a price rule that is a 68-character Calculate, and a demand that follows the price through 17 NegativeBinomial nodes picked by a Switch, with a mean that is exactly 8 (price / 10)^-1.5 and a variance of m + m^2 / 8, checked at five prices against an exact Markov chain (35 comparisons, none beyond 3 standard errors). The loop has three regimes, measured over 11 response strengths and 20 runs each: for G up to 0.01 the price settles into a band that widens like the square root of G; from about 0.02 to 0.2 it cycles with a period that falls from about 160 to 32 days; above 0.256 it swings between the limits (41% to 63% of days at a limit). A linearised loop, with a gain of 2.004 units of stock per dollar taken from the exact chain and the three one-row delays, predicts the period to within a day (68 against 67 days at G = 0.05) and the critical response strength of 0.256 with a 28.4-day cycle; it over-predicts the depth of the dip once the price limits matter. In this model the reacting price costs service (18.5 stockout days against 16.1 at G = 0.05) and a little revenue (28,353 against 28,502). An optional ServiceCall run takes the price rule out into a 50-line program on 127.0.0.1 behind an allowlist, and gives the same rows to the byte. The companion page lets you pick the response strength and see the price, the stock and the autocorrelation.
The store now has a price loop and a policy, and a policy has numbers to choose: a reorder point, an order quantity, a smoothing and a response, each with a cost the model so far ignores. Lesson 5.5 closes the module, and the track, by choosing a policy for the two-store system of lesson 5.3 on purpose: common random numbers so that two policies are compared on the same demand, enough replications for a stated precision, a warm-up, a sweep over reorder point and order quantity with a cost function whose assumptions are written down, and a recommendation that says how sure it is.