# 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

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

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```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

### 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
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 = sm.graphics.plot_partregress_grid(beef_model, fig=fig)``````

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 = sm.graphics.plot_ccpr_grid(beef_model, fig=fig)``````

### 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 = sm.graphics.plot_regress_exog(beef_model, '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")
``````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)
``````endog = beef['Quantity']

# To the regressors in the dataset, we add a column of ones for an intercept

### RLS Estimation

``````mod = sm.RecursiveLS(endog, exog)
res = mod.fit()
print(res.summary())``````

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));``

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

``fig = res.plot_cusum(figsize=(10,6));``

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.