Price elasticity with regression in Python: from a year of sales to the price that pays

TL;DR

Difficulty: Intermediate

An elasticity in Python takes 30 lines. Whether it means anything depends on everything around them.

  • Leave out the season and the same year of data says minus 0.46 instead of minus 1.62, and the pricing advice flips.
  • The model only learns from price moves nothing else explains: check the share of price variation left after the controls before you trust the number.
  • Check residuals, pick robust standard errors before you look, and hold out weeks that contain every situation.
  • The price ladder shows a flat hill around €49 to €52, and the regret table caps what perfect knowledge is worth at about €37 a week.
  • Buyer groups differ, so one list price is the wrong instrument, and a test against a control group is the proof.

How much volume do you lose for every 1% you add to a price? This chapter estimates that number in Python on a year of weekly sales for one invented gift hamper, with every line of code and its output. It rebuilds the Marketing Analytics chapter on demand and price elasticity and adds the checks that decide whether the number can carry a pricing decision.

Leave out Christmas and the hamper looks like it sells better when it costs more

Here is the trap this whole chapter is built around, in one line of numbers. Take a year of weekly sales for one gift hamper and regress units on price alone, and Python reports an elasticity of minus 0.46. Read literally, that says demand barely reacts to price, so raise it. Add three columns the shop already had, a promotion flag, a Christmas flag and the competitor's price, and the same data says minus 1.62. Now a price rise loses more volume than it gains in margin, and the advice flips.

Nothing about the hamper changed between the two runs. What changed is that the second model knows the shop charged its highest price, €59, in the six Christmas weeks, when demand doubles anyway. Without that column, the regression credits the high price with the Christmas crowd.

The Marketing Analytics chapter on modelling demand and price elasticity with regression explains the concepts behind all of this: the log log model, reading a regression table, why revenue peaks where elasticity is minus one, the markup rule and the test that proves it. Here you build it, line by line, in Python. Same shop, same question, same numbers, as close as generated data allows.

The example is invented. Priya runs Northgate Hampers, an online hamper shop in Cork at northgatehampers.example. Her Afternoon Tea Hamper has sat at €49 for so long that the price feels like a fact of nature, and she wants to know whether it should be €54. Over the past year the price moved seven times between €39 and €59, with 11 promotion weeks, six Christmas weeks and a competitor wandering between €52 and €58. The data below is generated to resemble the example in the Marketing Analytics chapter, so every line runs on your own machine.

If you only read one section

For the person who commissions this analysis, five points.

  • An elasticity is the percentage of volume you lose for each 1% you add to price. Northgate Hampers comes out at minus 1.62, with a plausible range of about minus 1.2 to minus 2.1.
  • The model can only learn from price moves that the other columns do not already explain. In the example a third of the price variation went to Christmas and the competitor, and the remaining two thirds set the precision. Ask your analyst how much was left over. It is the single best predictor of whether the number is worth anything.
  • The best price on paper is about €50. The real finding is that contribution is flat between €45 and €55: €49 against €54 is worth about €6 a week. Do not spend more on proving the elasticity than the decision is worth, and the code below puts a number on that ceiling: about €37 a week.
  • Elasticity differs by buyer. Corporate buyers come out inelastic, private gift buyers at minus 1.9. One list price is the wrong instrument.
  • Price is rarely set at random, so the regression is the hypothesis. A test against a control group is the proof. In the example the test agreed with the model within its error.

The rest of the chapter shows each step in code, with the output it produces.

What you need, and the versions this chapter uses

You need the setup from why Python for data analysis, and how to set it up, and you should be comfortable with statistical models in Python with statsmodels and scikit learn, where the formula interface and the regression table are introduced. This chapter goes deeper on one model and on the checks around it.

As of February 2026 I ran every block on Python 3.14, pandas 3.0, NumPy 2.4, statsmodels 0.14.6 and matplotlib 3.10. Two points matter.

First, pandas 3.0 arrived on 21 January 2026 with two changes you will notice: text columns now get a dedicated string data type by default, and copy on write is always on, so a chained assignment such as df["units"][3] = 0 no longer changes df. Use .loc instead.1 Nothing in this chapter depends on the old behaviour.

Second, statsmodels 0.14.6, released in December 2025, is the release that fixes an import problem with NumPy 2.4 and pandas 3.2 If you upgraded pandas and statsmodels refuses to import, that is the reason.

python -m pip install "pandas>=3.0" "numpy>=2.4" "statsmodels>=0.14.6" "matplotlib>=3.10"

Wes McKinney's Python for Data Analysis introduces statsmodels and its formula language in chapter 12.3 His edition predates pandas 3, but the formula syntax he shows is the one statsmodels 0.14 still uses.4

Step 1: generate the year of hamper sales

The first block builds the context of every week: the price Priya charged, whether a promotion ran, whether it was a Christmas week, and the competitor's price. These are the columns a real shop pulls from its order database and its marketing calendar.

Example: the weekly context.

import numpy as np
import pandas as pd

rng = np.random.default_rng(82659)   # fixed seed: the same year on every run

weeks = pd.date_range("2025-01-06", periods=52, freq="W-MON")   # each row starts on a Monday

# Priya's price: seven moves, seven levels between €39 and €59
price = np.repeat([39, 45, 49, 52, 42, 55, 59, 49], [3, 6, 14, 8, 3, 11, 6, 1])

promo = np.zeros(52, dtype=int)       # 1 = free delivery code live that week
promo[[2, 7, 10, 16, 19, 25, 30, 35, 39, 42, 47]] = 1
christmas = np.zeros(52, dtype=int)   # 1 = one of the six Christmas weeks
christmas[45:51] = 1
competitor = np.repeat([55, 52, 54, 56, 58, 56, 57], [7, 6, 9, 8, 7, 9, 6])

weekly = pd.DataFrame({"week": weeks, "price": price, "promo": promo,
                       "christmas": christmas, "competitor_price": competitor})

The second block creates the units. In the Marketing Analytics chapter Priya's buyers fall into three groups: corporate buyers ordering on an invoice, private gift buyers and private self buyers. I generate each group with its own true elasticity, add them up, and later check whether the regression finds the truth again. That is the great advantage of generated data: you know the right answer.

Example: three buyer groups, one weekly total.

# What nobody measured: a weekly shock that lingers a little into the next week
shock = rng.normal(0, 0.10, 52) * np.where(promo == 1, 1.6, 1.0)
lingering = np.zeros(52)
for t in range(52):
    lingering[t] = (0.35 * lingering[t - 1] if t > 0 else 0) + shock[t]

# Three buyer groups: share of units at €49, own elasticity, cross elasticity
segments = {"corporate": (0.31, -0.7, 0.1),
            "private gift": (0.54, -1.9, 0.6),
            "private self": (0.15, -2.4, 0.9)}

rows = []
for name, (share, own, cross) in segments.items():
    expected = np.exp(np.log(60 * share)
                      + own * np.log(price / 49)
                      + 0.28 * promo + 0.74 * christmas
                      + cross * np.log(competitor / 55)
                      + lingering + rng.normal(0, 0.04, 52))
    rows.append(pd.DataFrame({"week": weeks, "segment": name,
                              "units": rng.poisson(expected)}))
by_segment = pd.concat(rows, ignore_index=True)

# The weekly table: all buyers added up, joined to price and context
totals = by_segment.groupby("week", as_index=False)["units"].sum()
weekly = weekly.merge(totals, on="week")
print(weekly.head(3))
#         week  price  promo  christmas  competitor_price  units
# 0 2025-01-06     39      0          0                55     81
# 1 2025-01-13     39      0          0                55     94
# 2 2025-01-20     39      1          0                55    102

The group by and the merge are the moves from group by and pivot tables in pandas and joining and reshaping data. The rng.poisson call turns an expected number of hampers into a whole number, the way real weeks come in.

Where the weekly table comes from in a real shop

Generated data starts clean. A real weekly table is built from an order export, and four traps decide whether the elasticity means anything. None of them is in the tutorials, because tutorials start from a clean table.

  1. Order times in UTC. Most shop systems export timestamps in UTC. An order at 00:30 on a Monday in Irish summer time is 23:30 on Sunday in UTC, so it lands in the wrong week.
  2. Test and staff orders. They carry real prices and fake demand. Filter them out by email domain or customer flag.
  3. Refunds as separate rows. A refund is a reaction to the product or the courier, not to the price. Keep refunds aside for the demand model. Netting them into the week they were processed in shifts units into the wrong week.
  4. The price column. The average price actually paid moves with who bought. One corporate order with a volume discount pulls the weekly average down, although Priya changed nothing. Keep two columns, the price on the product page and the realised price, and check that they tell the same story.

Example: six orders, four traps.

orders = pd.DataFrame({
    "order_id": ["N1041", "N1042", "N1043", "N1044", "N1045", "N1046"],
    "created_at": ["2025-06-15 23:30", "2025-06-16 08:15", "2025-06-17 12:02",
                   "2025-06-18 09:30", "2025-06-19 14:00", "2025-06-20 10:45"],
    "email": ["aoife@example.ie", "test@northgatehampers.example", "ciaran@example.ie",
              "office@example.ie", "aoife@example.ie", "niamh@example.ie"],
    "kind": ["sale", "sale", "sale", "sale", "refund", "sale"],
    "quantity": [1, 1, 1, 6, -1, 1],
    "list_price": [49.0, 49.0, 49.0, 49.0, 49.0, 49.0],
    "discount": [0.0, 0.0, 4.90, 29.40, 0.0, 0.0],
})
print(orders.dtypes["email"])   # str: the new default string type in pandas 3

# 1. Times arrive in UTC: convert to shop time before cutting weeks
orders["created_at"] = (pd.to_datetime(orders["created_at"])
                        .dt.tz_localize("UTC")
                        .dt.tz_convert("Europe/Dublin"))
# 2. and 3. Test orders out, refunds kept aside
sales = orders[(orders["kind"] == "sale")
               & ~orders["email"].str.endswith("@northgatehampers.example")].copy()
# Monday based weeks in shop time
sales["week"] = sales["created_at"].dt.tz_localize(None).dt.to_period("W-SUN").dt.start_time
# 4. Two prices: the one on the page, and the one actually paid
sales["paid"] = sales["list_price"] * sales["quantity"] - sales["discount"]
week = sales.groupby("week").agg(units=("quantity", "sum"),
                                 list_price=("list_price", "mean"),
                                 paid=("paid", "sum"))
week["realised_price"] = week["paid"] / week["units"]
print(week.round(2))
#             units  list_price   paid  realised_price
# week
# 2025-06-16      9        49.0  406.7           45.19

Order N1041 was placed at 00:30 on Monday 16 June in Cork. In UTC it was still Sunday, and without the conversion it would have counted in the previous week. The six hamper corporate order with its 10% volume discount drags the realised price from €47.37 for the three private orders to €45.19 for the week. In a regression on realised price, that week looks like a price cut that sold nine hampers. It was not a price cut. It was a different buyer.

My rule: regress on the price the customer saw on the page, put discount codes in as a promotion flag, and model corporate buyers separately. The Marketing Analytics chapter's query uses the realised price, which is right when every buyer sees the same discount. With volume discounts in the mix, the list price is the safer decision variable. Loading and cleaning exports is covered in depth in loading business data into pandas, cleaning data in pandas and, for time zones and weeks, time series in pandas.

Step 2: look at the data before you fit anything

Two questions come before any model. How much did the price actually move? And what moved together with it? A price that changed twice in a year gives you two points and a line through them.

Example: price levels and what travels with them.

print("distinct prices:", weekly["price"].nunique())
print(weekly[["price", "promo", "christmas", "competitor_price"]].corr().round(2).loc["price"])

ordinary = weekly.query("promo == 0 and christmas == 0")
print(ordinary.groupby("price")["units"].agg(["count", "mean"]).round(1))
# distinct prices: 7
# price 1.00, promo 0.04, christmas 0.57, competitor_price 0.35
#        count  mean
# price
# 39         2  87.5
# 42         3  86.7
# 45         5  76.4
# 49        12  60.0
# 52         6  53.5
# 55         8  53.6

Seven price levels is enough to say something. The correlation of 0.57 between price and Christmas is the warning light: the highest price coincided with the strongest weeks. The ordinary weeks, without promotion and outside Christmas, show the shape of demand plainly. At €49 Priya sold 60 hampers in an average ordinary week, exactly the figure in the Marketing Analytics chapter. There is no ordinary week at €59 at all, because that price only ever ran at Christmas.

Average weekly units in ordinary weeks against the log log model's prediction, at six prices. Observed: 87.5 at €39, 86.7 at €42, 76.4 at €45, 60.0 at €49, 53.5 at €52 and 53.6 at €55. Model: 89.1, 79.0, 70.7, 61.6, 55.9 and 51.1. Both fall as price rises and the model runs through the middle of the observed averages. Tap or click to enlarge

The horizontal axis is the price, the vertical axis the hampers sold in an average ordinary week. The observed line wobbles because each price has only two to twelve weeks behind it. The model line is the curve fitted in step 3 below. A chart like this belongs in every elasticity analysis, before the table, for the reasons set out in exploring data with charts before you present anything.

Step 3: the log log model in statsmodels

Take natural logarithms of units and of both prices, and regress one on the others. This is the model from the Marketing Analytics chapter:

ln⁡Qt=α+ηln⁡Pt+γ1Dt+γ2St+θln⁡Ct+εt\ln Q_t = \alpha + \eta \ln P_t + \gamma_1 D_t + \gamma_2 S_t + \theta \ln C_t + \varepsilon_t

Here QtQ_t is the hampers sold in week tt, PtP_t is Priya's price and CtC_t the competitor's price. DtD_t is 11 in a promotion week and 00 otherwise, StS_t is 11 in a Christmas week. α\alpha is the intercept, η\eta the own price elasticity, θ\theta the cross price elasticity with the competitor, and γ1\gamma_1 and γ2\gamma_2 the effects of promotion and Christmas on log units. εt\varepsilon_t is everything about week tt the model does not know. Logs turn changes into percentages, which is why the price coefficient reads directly as an elasticity.5 The groundwork is in Foundations: logarithms and Foundations: regression.

First the version that leaves the context out.

Example: price alone.

import statsmodels.formula.api as smf

weekly["ln_units"] = np.log(weekly["units"])
weekly["ln_price"] = np.log(weekly["price"])
weekly["ln_comp"] = np.log(weekly["competitor_price"])

naive = smf.ols("ln_units ~ ln_price", data=weekly).fit()
print(f"price alone: {naive.params['ln_price']:.2f} (std error {naive.bse['ln_price']:.2f})")
# price alone: -0.46 (std error 0.33)

Then the full model. In the formula string, ~ separates what you explain from what explains it, and statsmodels adds the intercept itself.

Example: the full demand model.

model = smf.ols("ln_units ~ ln_price + promo + christmas + ln_comp", data=weekly)
fit = model.fit()
print(fit.summary().tables[1])
print(f"R squared {fit.rsquared:.3f}, residual std error {np.sqrt(fit.scale):.3f}, n = {int(fit.nobs)}")
# ==============================================================================
#                  coef    std err          t      P>|t|      [0.025      0.975]
# ------------------------------------------------------------------------------
# Intercept      8.5569      2.714      3.153      0.003       3.097      14.017
# ln_price      -1.6193      0.225     -7.196      0.000      -2.072      -1.167
# promo          0.2837      0.050      5.674      0.000       0.183       0.384
# christmas      0.6881      0.076      9.024      0.000       0.535       0.842
# ln_comp        0.4654      0.688      0.676      0.502      -0.919       1.850
# ==============================================================================
# R squared 0.713, residual std error 0.147, n = 52
Absolute own price elasticity estimated from the same data. Price alone gives 0.46, which looks inelastic. With promotion, Christmas and the competitor's price in the model it is 1.62, clearly elastic. The true value used to generate the data is close to 1.6. Tap or click to enlarge

The horizontal axis shows the two models, the vertical axis the size of the elasticity with the minus sign dropped. Below one means inelastic, above one elastic. The bar on the left would tell Priya to raise prices. The bar on the right tells her she is close to the best price already. Only the right one is near the truth that generated the data.

Reading the output, line by line

The method of reading is the same as in the Marketing Analytics chapter: sign first, then size, then the standard error, then the fit. Here is how to pull each piece out of the result object rather than copying numbers off the printed table.

Example: the numbers a decision needs.

eta = fit.params["ln_price"]
low, high = fit.conf_int().loc["ln_price"]
print(f"elasticity {eta:.2f}, 95% interval {low:.2f} to {high:.2f}")

# A dummy in a log model: the lift is e to the coefficient, minus one
lifts = np.exp(fit.params[["promo", "christmas"]]) - 1
print(lifts.round(3))
print(f"typical miss: {np.exp(np.sqrt(fit.scale)) - 1:.0%}")
# elasticity -1.62, 95% interval -2.07 to -1.17
# promo        0.328
# christmas    0.990
# typical miss: 16%

Read it in this order.

  • Own price, minus 1.62. A 1% price rise loses about 1.6% of hampers, holding promotion, season and the competitor constant. The 95% interval runs from minus 2.07 to minus 1.17. The whole interval is below minus one, so demand is elastic with some confidence, but whether it is minus 1.2 or minus 2.0 matters a lot for the price, and one year of data does not decide it. See Foundations: confidence intervals.
  • Promotion, 0.28. A dummy in a log model is not a percentage directly. The exact lift is e0.28−1=0.33e^{0.28} - 1 = 0.33, so a free delivery week sells about 33% more hampers at the same price.5
  • Christmas, 0.69. e0.69−1=0.99e^{0.69} - 1 = 0.99: demand doubles. The t statistic of 9 makes it the most certain number in the table.
  • Competitor, 0.47 with a standard error of 0.69. The sign is right for a substitute, and the size is unknowable from this year. The competitor only moved between €52 and €58, which is almost no information. In the Marketing Analytics chapter the table showed a narrower error for this line. With a competitor this steady, generated data cannot reproduce it, which makes that chapter's warning about this coefficient even stronger.
  • Intercept, 8.56. The log of units at a price of €1 against a competitor at €1. No business meaning. Ignore it.
  • R squared, 0.71, and a residual standard error of 0.147. The model explains 71% of the week to week ups and downs, and a typical week misses by about 16%. The Marketing Analytics chapter reported 0.81. Treat R squared as a description, not a grade: a high value with a wrong sign is worse than a modest one with a sensible coefficient.

The elasticity itself is defined in the same way as in the Marketing Analytics chapter:

η=∂Q∂P⋅PQ\eta = \frac{\partial Q}{\partial P} \cdot \frac{P}{Q}

Here η\eta is the elasticity, ∂Q/∂P\partial Q / \partial P is the slope of demand, the change in units for a small change in price, and P/QP/Q rescales that slope from euro and hampers into percentages.6 In the log log model the rescaling is built in, so η\eta is the same at every price. See Foundations: elasticity.

The elasticity only learns from price moves nothing else explains

This is the idea I would put on the wall of every pricing team. A regression with several columns does not use all of the price variation to estimate the elasticity. It first removes whatever part of the price the other columns can predict, and learns only from what is left. This is the Frisch Waugh Lovell theorem, and it has been known since 1933.78

For Priya, the part of price that the controls can predict is the Christmas premium: €59 always came with Christmas. The model cannot tell whether those weeks sold well because of the season or despite the price, so it sets them aside for the price question and leans on the moves in ordinary months.

The standard error of the elasticity follows directly from what is left over:

se⁡(η^)=σ^∑t=1nu~t2=σ^n su~\operatorname{se}(\hat\eta) = \frac{\hat\sigma}{\sqrt{\sum_{t=1}^{n} \tilde{u}_t^2}} = \frac{\hat\sigma}{\sqrt{n} \, s_{\tilde{u}}}

Here η^\hat\eta is the estimated elasticity and se⁡\operatorname{se} its standard error. σ^\hat\sigma is the residual standard error of the demand model, the typical miss in log units. u~t\tilde{u}_t is the leftover price in week tt: the residual when log price is regressed on all the other columns. nn is the number of weeks and su~s_{\tilde{u}} the spread of the leftover price. Three levers, then: less noise, more weeks, or more price movement that nothing else explains. See Foundations: spread and Foundations: sample size.

Example: the usable price variation, and what a tighter answer would cost.

# Step 1: how much of log price can the controls already explain?
aux = smf.ols("ln_price ~ promo + christmas + ln_comp", data=weekly).fit()
left_over = aux.resid                       # the price moves the model can learn from
print(f"price variation explained by the controls: {aux.rsquared:.0%}")
print(f"spread of log price: {weekly['ln_price'].std(ddof=0):.4f}, left over: {left_over.std(ddof=0):.4f}")

# Step 2: the elasticity's standard error, rebuilt by hand
sigma = np.sqrt(fit.scale)
print(f"std error by hand: {sigma / np.sqrt((left_over ** 2).sum()):.3f}")

# Step 3: how many weeks would a tighter answer need at today's price variation?
for target in [0.15, 0.10]:
    weeks_needed = (sigma / (target * left_over.std(ddof=0))) ** 2
    print(f"std error {target}: about {weeks_needed:.0f} weeks")
# price variation explained by the controls: 32%
# spread of log price: 0.1097, left over: 0.0903
# std error by hand: 0.225
# std error 0.15: about 117 weeks
# std error 0.1: about 263 weeks

Step by step, with the numbers from the output:

se⁡(η^)=0.14752×0.0903=0.1470.651=0.225\operatorname{se}(\hat\eta) = \frac{0.147}{\sqrt{52} \times 0.0903} = \frac{0.147}{0.651} = 0.225

That is exactly the 0.2250.225 in the statsmodels table, with 7.21=527.21 = \sqrt{52}. Nothing in the standard error is magic: it is noise divided by usable price movement.

The planning question turns the formula round:

n=(σ^se⁡target⋅su~)2n = \left( \frac{\hat\sigma}{\operatorname{se}_{\text{target}} \cdot s_{\tilde{u}}} \right)^2

Here nn is the number of weeks needed, se⁡target\operatorname{se}_{\text{target}} the standard error you want, and σ^\hat\sigma and su~s_{\tilde{u}} are as before. For a standard error of 0.10 at Priya's current price variation, n=(0.147/(0.10×0.0903))2=16.32≈265n = (0.147 / (0.10 \times 0.0903))^2 = 16.3^2 \approx 265 weeks, and the code with unrounded inputs prints 263: five years. The logic of sample size is set out in Foundations: sample size. Or she doubles the price movement that is not tied to the season, which on the same formula brings one year down to a standard error of about 0.11. My rule of thumb: before you collect more data, move the price more, outside the peak season, in both directions. It is the one lever fully under your control that does not cost years of waiting.

My check for any elasticity someone hands me: ask for the share of price variation the controls explain. Below about 50% the estimate stands on reasonable ground. Above about 80%, the price moved almost only when something else moved too, and the elasticity is a guess with decimals, whatever the t statistic says.

Step 4: check the misses before you trust the coefficients

The residuals are the week by week misses: actual log units minus predicted. Their pattern tells you whether the model is missing something. Plot them against time and against the prediction, as in charts in Python.

Example: two residual plots.

import matplotlib.pyplot as plt

weekly["fitted"] = fit.fittedvalues
weekly["resid"] = fit.resid

fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
left.scatter(weekly["week"], weekly["resid"], s=14)
left.axhline(0, linewidth=1)
left.set_title("Misses over the year")
left.set_ylabel("Residual, log units")
right.scatter(weekly["fitted"], weekly["resid"], s=14)
right.axhline(0, linewidth=1)
right.set_title("Misses against the prediction")
right.set_xlabel("Fitted log units")
fig.tight_layout()
plt.show()

What you want to see is a cloud without shape: no trend over the year, no wave, no funnel that widens on the right. Priya's residuals look like that. The largest miss is minus 0.40 in a September week at €55, a third fewer hampers than predicted, which is the kind of week you look up in the calendar before you ignore it.

Then the formal tests. Three of them answer three questions.

  • Breusch Pagan asks whether the spread of the misses grows with the columns of the model, which is called heteroskedasticity.9
  • Durbin Watson asks whether this week's miss resembles last week's. Values near 2 mean no; well below 2 means the misses run in streaks.10
  • Ljung Box asks the same for several weeks at once.11

Example: the three tests.

from statsmodels.stats.diagnostic import het_breuschpagan, acorr_ljungbox
from statsmodels.stats.stattools import durbin_watson

bp_stat, bp_p, _, _ = het_breuschpagan(fit.resid, fit.model.exog)
print(f"Breusch Pagan p value: {bp_p:.2f}")
print(f"Durbin Watson: {durbin_watson(fit.resid):.2f}")
print(f"Ljung Box p value, 4 weeks: {acorr_ljungbox(fit.resid, lags=[4])['lb_pvalue'].iloc[0]:.2f}")
# Breusch Pagan p value: 0.42
# Durbin Watson: 2.05
# Ljung Box p value, 4 weeks: 0.46

None of the three raises an alarm here. A p value of 0.42 is no evidence of changing spread, and a Durbin Watson of 2.05 is as close to "no streaks" as data gets. The data was generated with a little of both, and with 52 weeks the tests cannot see it. That is the honest lesson: a passed test means "no evidence of a problem in this sample", not "no problem". See Foundations: hypothesis tests.

Robust standard errors: decide before you look

Because tests on 52 weeks are weak, it is good practice to report standard errors that stay valid even if the spread changes or the misses run in streaks. statsmodels offers them through cov_type in fit.12 HC3 is robust to changing spread and behaves well in small samples.1314 HAC, after Newey and West, is also robust to streaks up to a chosen number of weeks.15 Neither changes the coefficients, only their error bars.

Example: three sets of standard errors for the same model.

hc3 = model.fit(cov_type="HC3")
hac = model.fit(cov_type="HAC", cov_kwds={"maxlags": 4})
errors = pd.DataFrame({"classical": fit.bse, "HC3": hc3.bse,
                       "HAC, 4 weeks": hac.bse}).round(3)
print(errors)
#            classical    HC3  HAC, 4 weeks
# Intercept      2.714  2.929         1.928
# ln_price       0.225  0.227         0.215
# promo          0.050  0.046         0.035
# christmas      0.076  0.059         0.055
# ln_comp        0.688  0.701         0.427

For the elasticity all three agree: 0.215 to 0.227. That agreement is itself a result worth one sentence in the report. Look at the competitor line, though. HAC shrinks its standard error from 0.69 to 0.43. With 52 weeks and four lags, HAC is itself estimated from very little and can understate the uncertainty. If an analyst tries all three and reports the smallest, the error bars are chosen to please.

My view: decide the type of standard error before you see the results, and write it down. For weekly shop data I default to HC3. I switch to HAC when the residual plot or the Ljung Box test shows streaks, with the number of lags set by the business, such as four weeks for a monthly rhythm, not by whichever value gives the nicest table.

Step 5: a test on weeks the model has not seen

A model is fitted to the weeks it has seen. The real question is how it does on weeks it has not. The Marketing Analytics chapter suggests refitting on the first 40 weeks and predicting the last 12. In Python, doing exactly that walks into a trap that is worth seeing once.

Example: the silent Christmas column.

formula = "ln_units ~ ln_price + promo + christmas + ln_comp"
first40 = smf.ols(formula, data=weekly.iloc[:40]).fit()
print(first40.params.round(3))
print(np.exp(first40.predict(weekly.iloc[45:51])).round(0).tolist())
print(weekly["units"].iloc[45:51].tolist())
# Intercept    9.398
# ln_price    -1.788
# promo        0.293
# christmas    0.000
# ln_comp      0.416
# [44.0, 44.0, 59.0, 44.0, 44.0, 44.0]
# [89, 90, 121, 89, 102, 92]

The first 40 weeks contain no Christmas week, so the Christmas column is all zeros. statsmodels does not stop. Its default solver, the pseudoinverse, quietly sets the coefficient to zero,16 and the model then predicts 44 hampers for weeks that sold 89 to 121. No warning, no error. A holdout period must contain every situation the model will be asked about, or the coefficient for the missing situation is not estimated at all.

The sound version holds out a block of ordinary weeks from the middle of the year, which still contains prices of €42, €52 and €55 and three promotion weeks.

Example: a fair holdout.

holdout = weekly.index[29:41]                   # 28 July to 13 October: no Christmas inside
train = weekly.drop(index=holdout)
part = smf.ols(formula, data=train).fit()

miss = weekly.loc[holdout, "ln_units"] - part.predict(weekly.loc[holdout])
print(f"elasticity without these weeks: {part.params['ln_price']:.2f}")
print(f"promised typical miss {np.sqrt(part.scale):.3f}, actual {np.sqrt((miss ** 2).mean()):.3f}")
# elasticity without these weeks: -1.43
# promised typical miss 0.137, actual 0.176

Without those 12 weeks the elasticity is minus 1.43, comfortably inside the full model's interval. The misses on the unseen weeks are about 28% larger than the model promised, which is normal: every model flatters itself on the data it was fitted to. My rule of thumb: if the misses on unseen weeks are more than about one and a half times the promised residual standard error, something is missing from the model, and I go looking for it before anyone sets a price on it. Here the ratio is 0.176/0.137=1.280.176 / 0.137 = 1.28.

Step 6: from elasticity to a price ladder

Now the part the meeting wants. Revenue peaks where elasticity is minus one, but nobody should maximise revenue. Contribution, price minus the cost of selling one more hamper times units, pays the bills. In the example that cost is €19: goods, box, ribbon and courier. Under constant elasticity the contribution maximising price follows from the markup rule:17

P∗=MC1+1/ηP^{*} = \frac{MC}{1 + 1/\eta}

Here P∗P^{*} is the best price for contribution, MCMC is the marginal cost per hamper, €19 here, and η\eta is the elasticity, which must be below minus one for the rule to give an answer. The derivation is in the Marketing Analytics chapter, and the same rule appears with the elasticity as a positive number in optimisation under uncertainty for budgets and prices. See Foundations: marginal versus average and Foundations: elasticity.

The ladder is more useful than the single number, because it shows how much is at stake between prices. The code predicts units for an ordinary week at each price Priya has charged, using the fitted model directly rather than a hand formula.

Example: the price ladder and the markup rule.

cost = 19          # goods, box, ribbon and courier per hamper

# Model units in an ordinary week: no promotion, not Christmas, competitor at €55
ladder = pd.DataFrame({"price": [39, 42, 45, 49, 52, 55, 59],
                       "promo": 0, "christmas": 0, "competitor_price": 55})
ladder["ln_price"] = np.log(ladder["price"])
ladder["ln_comp"] = np.log(ladder["competitor_price"])
ladder["units"] = np.exp(fit.predict(ladder))
ladder["revenue"] = ladder["price"] * ladder["units"]
ladder["contribution"] = (ladder["price"] - cost) * ladder["units"]
print(ladder[["price", "units", "revenue", "contribution"]].round(1))

print(f"markup rule: €{cost / (1 + 1 / eta):.2f}")
print(f"at the interval's ends: €{cost / (1 + 1 / low):.0f} and €{cost / (1 + 1 / high):.0f}")

The output, tidied into a table:

PriceModel units per ordinary weekRevenueContribution at €19 cost
€3989.1€3,474€1,782
€4279.0€3,319€1,817
€4570.7€3,180€1,837
€4961.6€3,016€1,847
€5255.9€2,907€1,845
€5551.1€2,808€1,838
€5945.6€2,689€1,823

The markup rule gives €49.68, and at the two ends of the 95% interval €37 and €133. Worked through for the point estimate: 1/η=1/(−1.62)=−0.6181/\eta = 1/(-1.62) = -0.618, then 1−0.618=0.3821 - 0.618 = 0.382, then 19/0.382≈€49.719 / 0.382 \approx €49.7.

Revenue falls all the way down the ladder, as an elastic demand says it must. Contribution hardly moves: €1,847 at €49 and €1,845 at €52. The shop stands on the top of a broad, flat hill. That flatness is the finding, the same one the Marketing Analytics chapter reached with its own numbers.

The €59 row deserves a word. No ordinary week ever ran at €59, so this row is the model's guess outside the conditions it has seen. It is still inside the price range, which is why I show it, but it is the least certain row of the table.

Choose the price by expected regret, not by the point estimate

The markup rule answers "what is the best price if the elasticity is exactly minus 1.62?" The honest question is different: "which price do I regret least, given that I do not know the elasticity exactly?" With a standard error, Python can answer that directly. Draw many plausible elasticities, compute the contribution at every price for each, and see how much each price falls short of the best one in each case. That shortfall is the regret.

Regret⁡(p)=Eη ⁣[ max⁡qπ(q,η)−π(p,η) ]\operatorname{Regret}(p) = \mathbb{E}_{\eta}\!\left[\, \max_{q} \pi(q, \eta) - \pi(p, \eta) \,\right]

Here pp is the price you choose, qq runs over all candidate prices, π(p,η)\pi(p, \eta) is the weekly contribution at price pp if the elasticity is η\eta, and Eη\mathbb{E}_{\eta} is the average over all plausible elasticities. The expected value is explained in Foundations: expected value. I restrict qq to the prices Priya has actually charged, €39 to €59, because the model says nothing reliable outside them.

Example: 20,000 plausible elasticities.

# 20,000 plausible elasticities, drawn from the estimate and its standard error
draws = np.random.default_rng(7).normal(eta, fit.bse["ln_price"], 20_000)
prices = np.arange(39, 60)                        # only prices Priya has actually charged
units_49 = ladder.loc[ladder["price"] == 49, "units"].iloc[0]

# Contribution for every plausible elasticity (rows) at every price (columns)
contrib = (prices - cost) * units_49 * (prices / 49) ** draws[:, None]
regret = contrib.max(axis=1, keepdims=True) - contrib

choice = pd.DataFrame({"price": prices,
                       "expected_contribution": contrib.mean(axis=0),
                       "expected_regret": regret.mean(axis=0)}).round(1)
print(choice.query("price in [39, 45, 49, 50, 54, 59]"))

best_each = prices[contrib.argmax(axis=1)]
print(f"best price is €59 in {np.mean(best_each == 59):.0%} of draws, €44 or less in {np.mean(best_each <= 44):.0%}")
#     price  expected_contribution  expected_regret
# 0      39                 1784.6             99.2
# 6      45                 1837.7             46.2
# 10     49                 1846.8             37.1
# 11     50                 1846.9             37.0
# 15     54                 1841.1             42.8
# 20     59                 1823.9             60.0
# best price is €59 in 27% of draws, €44 or less in 29%

The broadcast in (prices / 49) ** draws[:, None] builds a table of 20,000 rows and 21 columns in one line, the NumPy habit from NumPy explained.

Expected contribution per ordinary week, averaged over 20,000 plausible elasticities, at every price from €39 to €59. It rises from €1,785 at €39 to a flat top of €1,847 at €49 and €50, then falls gently to €1,824 at €59. Between €45 and €55 the difference is under €10 a week. Tap or click to enlarge

The horizontal axis is the price, the vertical axis the expected weekly contribution in an ordinary week. The axis starts well above zero on purpose, to make a difference of a few euro visible at all. Read it as the shape of the hill, not as the size of the stakes.

Three findings come out of this block, and they are the most useful numbers in the chapter.

First, the price with the least regret is €50, the same as the markup rule. With a symmetric uncertainty and a flat hill, the point estimate is a fine guide. That is reassuring, and not guaranteed: with a lopsided cost of being wrong, the two can differ.

Second, the best price in any single draw jumps around. In 27% of the plausible worlds it is €59, in 29% it is €44 or lower. A report that names one "optimal price" hides that this number is not stable. The ladder and the regret are.

Third, the expected regret at €49 is €37 a week. This is the expected value of perfect information: even an oracle who told Priya the exact elasticity could, on average, add only about €37 a week, about €1,900 a year, to this hamper's contribution in ordinary weeks. That is the ceiling on what any study, test or consultant is worth for this one decision. €49 against €54 is worth 1,846.8−1,841.1≈€61{,}846.8 - 1{,}841.1 \approx €6 a week. The finance instinct to go to €54 is defensible, and there is no rush on it.

Elasticity is not one number: three buyer groups

The minus 1.62 is an average over everyone who bought. In the example, the shop's export says whether an order came on an invoice, so the data can be split. The same model fitted per group, with HC3 standard errors, shows how different the groups are. A long table with one row per week and group, plus groupby, does it in a loop.

Example: one model per buyer group.

seg = by_segment.merge(weekly[["week", "ln_price", "promo", "christmas", "ln_comp"]], on="week")
seg["ln_units"] = np.log(seg["units"])

rows = []
for name, group in seg.groupby("segment"):
    f = smf.ols(formula, data=group).fit(cov_type="HC3")
    rows.append({"segment": name,
                 "share": group["units"].sum() / seg["units"].sum(),
                 "elasticity": f.params["ln_price"],
                 "std_error": f.bse["ln_price"]})
by_group = pd.DataFrame(rows)
# The markup rule only has an answer for elastic demand (below minus one)
by_group["best_price"] = (cost / (1 + 1 / by_group["elasticity"])).where(by_group["elasticity"] < -1)
print(by_group.round(2))
print(f"weighted by share: {(by_group['share'] * by_group['elasticity']).sum():.2f}")
#         segment  share  elasticity  std_error  best_price
# 0     corporate   0.30       -0.70       0.57         NaN
# 1  private gift   0.56       -1.90       0.23       40.18
# 2  private self   0.15       -2.42       0.48       32.36
# weighted by share: -1.62
Buyer groupShare of unitsElasticityStd error (HC3)Best price by the markup rule
Corporate30%minus 0.700.57none, demand is inelastic
Private gift56%minus 1.900.23€40.18
Private self15%minus 2.420.48€32.36, below the tested range
All buyers100%minus 1.620.23€49.68

The model finds the three true values used to generate the data, minus 0.7, minus 1.9 and minus 2.4, almost exactly, and the share weighted average reproduces the overall minus 1.62. The split adds up to the whole.

Read the standard errors before the elasticities. Corporate buyers at minus 0.70 have a standard error of 0.57, so their true elasticity could be anywhere from roughly minus 1.8 to plus 0.4. Inelastic is likely and not proven. Private gift buyers are the solid line: minus 1.90 with 0.23, and a best price around €40. The private self buyers' €32 is below anything Priya has charged, so it is a direction, not a price.

What it means for the decision is the same as in the Marketing Analytics chapter, now with code behind it: a corporate price list above the web price, and a web price tested downwards for the gift buyer. To test formally whether two groups differ, fit one model with interaction terms, C(segment):ln_price, and use t_test on the difference. In this data the gap between corporate and private gift has a p value of about 0.015.

The test against a control group settles it

Every number above is observational. Priya set the prices for reasons, and some of those reasons were related to demand. The economist's name for that is endogeneity: when prices rise in strong weeks and fall in weak ones, OLS pulls the elasticity towards zero. A meta analysis of 1,851 published price elasticities found that methods which deal with endogeneity report noticeably larger elasticities in absolute value,18 and the classic marketing treatment of the problem is Villas Boas and Winer.19 Season dummies absorb some of it. A randomised test removes it.

In the Marketing Analytics chapter Priya ran eight ordinary autumn weeks in which half of the web sessions, chosen at random, saw €54 and the other half €49. The analysis takes a few lines. Sample sizes and test design have their own chapter later in this series, on A/B tests in Python.

Example: €49 against €54.

from statsmodels.stats.proportion import confint_proportions_2indep

control_orders, control_sessions = 268, 4_400     # €49
test_orders, test_sessions = 216, 4_400           # €54
rate_c = control_orders / control_sessions
rate_t = test_orders / test_sessions
low_gap, high_gap = confint_proportions_2indep(control_orders, control_sessions,
                                               test_orders, test_sessions, method="wald")
print(f"orders per 1,000 sessions: {rate_c * 1000:.1f} at €49, {rate_t * 1000:.1f} at €54")
print(f"gap {(rate_c - rate_t) * 1000:.1f}, 95% interval {low_gap * 1000:.1f} to {high_gap * 1000:.1f}")
print(f"fall {1 - rate_t / rate_c:.0%}, the private gift elasticity predicted {1 - (54 / 49) ** -1.9:.0%}")
print(f"contribution per 1,000 sessions: €{rate_c * 1000 * (49 - cost):,.0f} against €{rate_t * 1000 * (54 - cost):,.0f}")
# orders per 1,000 sessions: 60.9 at €49, 49.1 at €54
# gap 11.8, 95% interval 2.3 to 21.3
# fall 19%, the private gift elasticity predicted 17%
# contribution per 1,000 sessions: €1,827 against €1,718

The function confint_proportions_2indep gives the interval for the difference between two rates.20 The test saw a fall of 19%, the model predicted 17% for the gift buyers who dominate the web shop, and the interval for the gap runs from 2.3 to 21.3 orders per thousand sessions. The direction is confirmed, the size is consistent with the model, and on the web €49 earned more contribution than €54. The regression said where to look and how big an effect to expect. The test said it was real.

The whole workflow on one page

Tap or click to enlarge

The flow runs top to bottom. The only loop is the residual check: when the misses show a pattern, the model is missing a driver, and no coefficient is read until it is in. Put the whole thing in a script with a test for each step, as in a reproducible Python analysis workflow, and next quarter's rerun takes minutes.

Traps that make an elasticity lie

TrapWhat it doesThe check in Python
Price moves with the seasonThe high price borrows the season's demand, the elasticity shrinks towards zerocorr() between price and the season flags, and the share of price explained by the controls
Too few price levelsTwo or three levels give a line through a handful of pointsweekly["price"].nunique(), and fewer than five is a warning
A holdout without a situationThe missing column's coefficient is silently set to zeroCheck that every flag has both values in the training data
Realised price mixed with buyer mixA volume discount looks like a price cutKeep the list price and the realised price, model buyer groups separately
StockoutsA week with no stock looks like a week nobody wanted the hamperFlag days out of stock and drop or mark those weeks
Zero sales weeksThe log of zero is minus infinityCount zeros first, and switch to a count model if they are common
ExtrapolationThe constant elasticity curve happily predicts €29 or €79Restrict every ladder and simulation to prices you have charged
Constant elasticity assumedReal demand may kink at a threshold such as €50Add I(ln_price**2) and see whether it earns its place

The last check is one line. In Priya's data the squared term has a p value of 0.98 and the adjusted R squared falls slightly, so constant elasticity is fine inside €39 to €59. Two later chapters in this series take the next steps: distributed lags in Python, for promotions whose effect lingers for weeks, and Poisson regression in Python, for products that sell so few units that zero weeks are common. The endogeneity problem gets its full treatment in the chapter on simultaneous equations and two stage least squares.

My view

Most elasticity work fails before the first regression, in two places: a weekly table built from UTC timestamps, test orders and a realised price that moves with the buyer mix, and a price history in which every rise happened in November. Python fixes neither. It makes both visible, if you look, and that is a good few hours saved before anyone argues about a coefficient.

So I would rank the steps of this chapter by value, not by sophistication. The plot of units by price and the share of price variation left after the controls tell you within ten minutes whether an elasticity is possible at all. The log log model with HC3 errors gives you the number. The ladder and the regret table turn it into a decision with its stakes attached. Fancier models come last, and usually only once the shop has moved its prices on purpose for a few months.

The regret calculation deserves more use than it gets. It answers the question the person paying for the analysis actually has, how much is this decision worth, and it often shows that the honest answer is "less than the meeting about it". In this example the ceiling is about €37 a week. That is useful to know before anyone commissions a six week study.

If you want help building this on your own shop's data, it is a core part of my Data Science work. The free workshop is where we check whether your price history can carry an elasticity at all, and the prices are published.

Conclusion

A price elasticity in Python takes about 30 lines: build a weekly table, take logs, fit smf.ols, and read the coefficient on log price. The work is everything around those lines. Leave out the season and the same year of data says minus 0.46 instead of minus 1.62. The model only learns from the price moves nothing else explains, so the share of price variation left after the controls decides the precision, and moving the price outside the peak season is the least expensive way to sharpen it. Residual plots and robust standard errors keep the error bars honest, and a fair holdout keeps the model honest about weeks it has not seen. From the elasticity, the price ladder shows a flat hill around €49 to €52, the regret table puts the value of perfect knowledge at about €37 a week, and the buyer groups show that one list price is the wrong instrument. The test against a control group then confirms what the model predicted. The concepts behind every step are in the Marketing Analytics chapter on demand and price elasticity, and the basics of means, spread and intervals in Python are in descriptive statistics for marketers in Python.

If you have a year of sales and a price you have been afraid to touch, bring it to my free workshop: we check whether your price history can carry an elasticity at all and which decision it would change. Then the first two weeks of work are on me.

Sources

  1. 1.

    pandas development team, What's new in 3.0.0 (January 21, 2026), pandas documentation, 2026, https://pandas.pydata.org/docs/whatsnew/v3.0.0.html

  2. 2.

    statsmodels developers, Release 0.14.6, statsmodels 0.14.6 documentation, December 2025, https://www.statsmodels.org/v0.14.6/release/version0.14.6.html

  3. 3.

    Wes McKinney, Python for Data Analysis, 3rd edition, chapter 12: Introduction to Modeling Libraries in Python, O'Reilly, 2022, free online edition, https://wesmckinney.com/book/modeling

  4. 4.

    statsmodels developers, Fitting models using R style formulas, statsmodels 0.14.6 documentation, https://www.statsmodels.org/v0.14.6/example_formulas.html

  5. 5.

    Clay Ford, Interpreting Log Transformations in a Linear Model, University of Virginia Library StatLab, 2018, https://library.virginia.edu/data/articles/interpreting-log-transformations-in-a-linear-model

  6. 6.

    Steven A. Greenlaw, David Shapiro and others, Principles of Economics 3e, section 5.1 Price Elasticity of Demand and Price Elasticity of Supply, OpenStax, 2022, https://openstax.org/books/principles-economics-3e/pages/5-1-price-elasticity-of-demand-and-price-elasticity-of-supply

  7. 7.

    Ragnar Frisch and Frederick V. Waugh, Partial Time Regressions as Compared with Individual Trends, Econometrica 1(4), 387 to 401, 1933, https://doi.org/10.2307/1907330

  8. 8.

    Michael C. Lovell, Seasonal Adjustment of Economic Time Series and Multiple Regression Analysis, Journal of the American Statistical Association 58(304), 993 to 1010, 1963, https://doi.org/10.1080/01621459.1963.10480682

  9. 9.

    T. S. Breusch and A. R. Pagan, A Simple Test for Heteroscedasticity and Random Coefficient Variation, Econometrica 47(5), 1287 to 1294, 1979, https://doi.org/10.2307/1911963

  10. 10.

    J. Durbin and G. S. Watson, Testing for Serial Correlation in Least Squares Regression I, Biometrika 37(3/4), 409 to 428, 1950, https://doi.org/10.1093/biomet/37.3-4.409

  11. 11.

    G. M. Ljung and G. E. P. Box, On a Measure of Lack of Fit in Time Series Models, Biometrika 65(2), 297 to 303, 1978, https://doi.org/10.1093/biomet/65.2.297

  12. 12.

    statsmodels developers, RegressionResults.get_robustcov_results, statsmodels 0.14.6 documentation, https://www.statsmodels.org/v0.14.6/generated/statsmodels.regression.linear_model.RegressionResults.get_robustcov_results.html

  13. 13.

    Halbert White, A Heteroskedasticity Consistent Covariance Matrix Estimator and a Direct Test for Heteroskedasticity, Econometrica 48(4), 817 to 838, 1980, https://doi.org/10.2307/1912934

  14. 14.

    James G. MacKinnon and Halbert White, Some Heteroskedasticity Consistent Covariance Matrix Estimators with Improved Finite Sample Properties, Journal of Econometrics 29(3), 305 to 325, 1985, https://doi.org/10.1016/0304-4076%2885%2990158-7

  15. 15.

    Whitney K. Newey and Kenneth D. West, A Simple, Positive Semi Definite, Heteroskedasticity and Autocorrelation Consistent Covariance Matrix, Econometrica 55(3), 703 to 708, 1987, https://doi.org/10.2307/1913610

  16. 16.

    statsmodels developers, OLS.fit (method "pinv" uses the Moore Penrose pseudoinverse), statsmodels 0.14.6 documentation, https://www.statsmodels.org/v0.14.6/generated/statsmodels.regression.linear_model.OLS.fit.html

  17. 17.

    Robert S. Pindyck, Lecture Notes on Pricing, 15.013 Industrial Economics for Strategic Decisions, MIT Sloan School of Management, 2010, https://www.mit.edu/~rpindyck/Courses/Pricing_10.pdf

  18. 18.

    Tammo H. A. Bijmolt, Harald J. van Heerde and Rik G. M. Pieters, New Empirical Generalizations on the Determinants of Price Elasticity, Journal of Marketing Research 42(2), 141 to 156, 2005, https://doi.org/10.1509/jmkr.42.2.141.62296

  19. 19.

    J. Miguel Villas Boas and Russell S. Winer, Endogeneity in Brand Choice Models, Management Science 45(10), 1324 to 1338, 1999, https://doi.org/10.1287/mnsc.45.10.1324

  20. 20.

    statsmodels developers, confint_proportions_2indep, statsmodels 0.14.6 documentation, https://www.statsmodels.org/v0.14.6/generated/statsmodels.stats.proportion.confint_proportions_2indep.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter