10.8 Building and Viewing a Demand Curve in Python
For a lengthy time period, Lobster Land management adjusted the prices of Larry the Lobster stuffed animals on a day-by-day basis. The prices ranged from $5.00 to $10.00, in increments of $0.25, so 21 separate prices were used in the experiment. For each of the prices, the gift shop collected the average daily sales totals for the stuffed animals. These values, along with the daily prices, can be found in stuffed_animal_sales_data.csv, which can be found at lobsterland.net/datasets.
We will start here by reading this dataset into our environment and exploring its first five rows:


Image Source: Wikimedia Commons, “Everett And His New Lobster” by Joe Shlabotnik is licensed under CC BY-NC-SA 2.0
To build the demand curve, we will use the lmplot() function from seaborn, which will not only make a scatterplot of our data, but also generate and display a best-fit line using linear regression.

The graph confirms what we would expect to see — when the price for Larry goes higher, the quantity demanded goes down, and vice versa.
The gray band formed around the best-fit line shows a 95% confidence interval. Seaborn automatically generated this band, along with the x-axis and y-axis labels.
Seaborn’s lmplot() function will not display the regression statistics, so we will need to make a regression model in order to find the slope. There are several ways in which a regression model could be built in Python. We will build one here using statmodels.

While this model summary generates many separate metrics, the ones that we will focus on here are r-squared (0.984), and the p-value of the model’s F-statistic (1.23e-18). We have a very close linear fit here, and a very significant overall result. Using the params attribute, shown below, we can look at the model coefficients.

The equation for our best-fit line to predict demand is y =410.3 – 36.42x, with x representing the price for the stuffed animals.
Using this equation, we can take any x value from inside the range of our original dataset ($5.00 to $10.00) for the price of Larry the Lobster and then generate a demand estimate as our outcome. With a value on the lower end of the spectrum — $5.15, we would have an expected demand of:
y = -36.42(5.15) + 410.3
y = -187.56 + 410.3
y = 222.74
Of course, Lobster Land does not sell stuffed animal lobsters in 0.74 unit increments, so we would round our estimate up to the nearest whole value, 223.
With a value nearer to the high end of the range, we should expect to see a smaller level of predicted demand. Let’s see what the equation would predict for a price of $9.15.
y = -36.42(9.15) + 410.3
y = -333.242 + 410.3
y = 77.05
With a price of $9.15, we would expect daily demand of 77 stuffed animal lobsters.
With a unit cost of $3.50, the higher price would actually generate more profit for Lobster Land, even with the lower sales volume.