Price Elasticity with Python

In Economics, Price Elasticity of Demand (PED) is used to measure the responsiveness or elasticity of the quantity demanded of a product or service due to the increase or decrease in the price of the product. In simple terms Price Elasticity of Demand gives the percentage change in the quantity demanded of a product due to a percentage change in the price of the product.

Price Elasticity

In economics, Price Elasticity is a measure of how much sensitive the demand or supply of a product is to the change in the price. But in marketing, Price Elasticity is a measure of how much sensitive the consumers are due to the change in price of a product.

Measuring of Price Elasticity is a very important aspect of every business, as it gives the answers to possibly these questions:

  • If you will lower the price of a product, how much more will you sell?
  • If you raise the price of one product, how will that affect the sales of the other products?
  • If the market price of a product goes down, how much will that affect in the amount that firms will be willing to supply to the market?

In this article, I will use a linear regression model to estimate the price elasticity of demand, I will also use statistical modelling to estimate our models using python. Let’s start with the data exploration:

Data Exploration

The dataset I am using for this article is based on the demand and price of beef which can be easily downloaded below.

Now let’s import the some standard libraries and have a look at the dataset:

from __future__ import print_function from statsmodels.compat import lzip import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.formula.api import ols beef = pd.read_csv('beef.csv') beef.head(10)
Image for post

Regression Analysis

Ordinary Least Squares (OLS) Estimation

beef_model = ols("Quantity ~ Price", data=beef).fit() print(beef_model.summary())
                            OLS Regression Results                            
Dep. Variable:               Quantity   R-squared:                       0.901
Model:                            OLS   Adj. R-squared:                  0.900
Method:                 Least Squares   F-statistic:                     811.2
Date:                Mon, 13 Jul 2020   Prob (F-statistic):           1.69e-46
Time:                        17:18:46   Log-Likelihood:                -77.493
No. Observations:                  91   AIC:                             159.0
Df Residuals:                      89   BIC:                             164.0
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
                 coef    std err          t      P>|t|      [0.025      0.975]
Intercept     30.0515      0.413     72.701      0.000      29.230      30.873
Price         -0.0465      0.002    -28.482      0.000      -0.050      -0.043
Omnibus:                        3.453   Durbin-Watson:                   1.533
Prob(Omnibus):                  0.178   Jarque-Bera (JB):                2.460
Skew:                           0.237   Prob(JB):                        0.292
Kurtosis:                       2.349   Cond. No.                     1.74e+03
  • The small P values indicate that we can reject the null hypothesis that Price has no effect on Quantity.
  • Hight r squared indicates that our model explains a lot of the response variability.
  • In regression analysis, I would like our regression model to have significant variables and to produce a high R-squared value.
  • Now I will show graphs to help interpret regression analysis results more intuitively.
fig = plt.figure(figsize=(12,8)) fig =, fig=fig)
Price Elasticity

The trend indicates that the predictor variables (Price) provides information about the response (Quantity), and data points do not fall further from the regression line, and the predictions are very precise given a prediction interval that extends from about 29 to 31.

CCPR Plots

The CCPR plot provides a way to judge the effect of one regressor on the response variable by taking into account the effects of the other independent variables.

fig = plt.figure(figsize=(12, 8)) fig =, fig=fig)
price elasticity

Regression plots for Price Elasticity

We use plot_regress_exog function to quickly check model assumptions with respect to a single regressor, Price in our case.

fig = plt.figure(figsize=(12,8)) fig =, 'Price', fig=fig)

Recursive Least Square (RLS)

Finally we apply Recursive Least Square (RLS) filter to investigate parameter instability.

beef['Year'] = pd.to_datetime(beef['Year'], format="%Y") beef.head()
Image for post
from pandas.tseries.offsets import * beef['Date'] = beef.apply(lambda x:(x['Year'] + BQuarterBegin(x['Quarter'])), axis=1) beef.drop(['Year', 'Quarter'], axis=1, inplace=True) beef.set_index('Date', inplace=True) beef.head(10)
Image for post
endog = beef['Quantity'] # To the regressors in the dataset, we add a column of ones for an intercept exog = sm.add_constant(beef['Price'])

RLS Estimation

mod = sm.RecursiveLS(endog, exog) res = print(res.summary())
Image for post

The RLS model calculates the Regression parameters, providing as much estimates as data points. The summary only shows the regression parameters which are estimated on the entire samples.

RLS Plots for Price Elasticity

We can generate the recursively estimated coefficients plot on a given variable.

res.plot_recursive_coefficient(range(mod.k_exog), alpha=None, figsize=(10,6));
price elasticity

For convenience, we can visually check for parameter stability using the plot_cusum function.

fig = res.plot_cusum(figsize=(10,6));
image for post

In the plot above, the CUSUM statistic does not move outside of the 5% significance bands, so we fail to reject the null hypothesis of stable parameters at the 5% level.

Also, read – Learn PySpark in Machine Learning.

I hope you liked this article on measuring Price Elasticity of Demand using Python. Feel free to ask your valuable questions in the comments section. Don’t forget to subscribe for my daily newsletter below to get email notifications, if you like my work.

Follow Us:

Default image
Aman Kharwal

I am a programmer from India, and I am here to guide you with Data Science, Machine Learning, Python, and C++ for free. I hope you will learn a lot in your journey towards Coding, Machine Learning and Artificial Intelligence with me.

One comment

Leave a Reply