Demand Forecasting Meets Price Optimization

📊 A Data-Driven Python Approach

In today’s fast-paced e-commerce and retail environment, finding the optimal price that balances demand and revenue is a cornerstone of profitability.
But this is no longer a guessing game.
Thanks to machine learning and optimization, we can forecast demand based on historical data and optimize pricing accordingly.

In this post, we’ll walk through a concrete example of this integration using Python, forecasting demand with linear regression and then using that to maximize revenue through optimization.


🔍 Problem Overview

We have historical data containing:

  • Prices at which a product was sold
  • Corresponding units sold

We want to:

  1. Forecast demand based on price using linear regression.
  2. Optimize price to maximize expected revenue.

The Revenue Function

Let:

  • $p$ be the price
  • $D(p)$ be the demand at price $p$

Then:

$$
\text{Revenue}(p) = p \cdot D(p)
$$

We’ll forecast $D(p)$ with a simple linear regression:

$$
D(p) = a - b \cdot p
$$

Where $a, b$ are learned from data.


📁 Step 1: Python Code – Forecasting + Optimization

Let’s start with the full code, then break it down step-by-step.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from scipy.optimize import minimize_scalar

# Step 1: Simulated historical data (price vs demand)
np.random.seed(0)
prices = np.linspace(5, 20, 30)
true_a = 100
true_b = 3
demand = true_a - true_b * prices + np.random.normal(0, 5, size=prices.shape)

# Step 2: Fit linear regression: D(p) = a - b * p
X = prices.reshape(-1, 1)
y = demand
model = LinearRegression()
model.fit(X, y)
a = model.intercept_
b = -model.coef_[0] # reverse sign to match D(p) = a - b*p

# Step 3: Revenue function R(p) = p * D(p) = p * (a - b * p)
def revenue(p):
return -(p * (a - b * p)) # Negative for minimization

# Step 4: Find optimal price
result = minimize_scalar(revenue, bounds=(5, 20), method='bounded')
optimal_price = result.x
optimal_revenue = -result.fun
optimal_demand = a - b * optimal_price

# Step 5: Plot results
p_range = np.linspace(5, 20, 100)
predicted_demand = a - b * p_range
revenue_curve = p_range * predicted_demand

plt.figure(figsize=(12, 5))

# Demand curve
plt.subplot(1, 2, 1)
plt.scatter(prices, demand, label='Observed Demand')
plt.plot(p_range, predicted_demand, color='green', label='Predicted Demand')
plt.axvline(optimal_price, color='red', linestyle='--', label=f'Optimal Price = ${optimal_price:.2f}')
plt.xlabel('Price')
plt.ylabel('Demand')
plt.title('Demand vs. Price')
plt.legend()

# Revenue curve
plt.subplot(1, 2, 2)
plt.plot(p_range, revenue_curve, color='blue', label='Revenue Curve')
plt.axvline(optimal_price, color='red', linestyle='--', label=f'Optimal Revenue = ${optimal_revenue:.2f}')
plt.xlabel('Price')
plt.ylabel('Revenue')
plt.title('Revenue vs. Price')
plt.legend()

plt.tight_layout()
plt.show()

🧠 Code Breakdown

🏗️ Simulating Historical Data

1
2
3
4
prices = np.linspace(5, 20, 30)
true_a = 100
true_b = 3
demand = true_a - true_b * prices + np.random.normal(0, 5, size=prices.shape)

We simulate demand with noise, assuming a negative linear relationship between price and demand.


📈 Linear Regression for Demand Estimation

1
2
3
X = prices.reshape(-1, 1)
model = LinearRegression()
model.fit(X, y)

We fit a linear model: $\hat{D}(p) = a - b \cdot p$

Note: b is extracted as -model.coef_[0] since sklearn learns $y = a + b \cdot p$.


🧮 Revenue Function and Optimization

1
2
def revenue(p):
return -(p * (a - b * p)) # for minimization

We define the negative revenue function because minimize_scalar finds the minimum, and we want the maximum revenue.


🔎 Finding the Optimal Price

1
result = minimize_scalar(revenue, bounds=(5, 20), method='bounded')

We restrict the price to the range $5–$20 and find the price that yields the highest revenue.


📊 Visualization & Explanation

The first plot shows:

  • Observed demand (scatter)
  • Predicted demand curve (green line)
  • Optimal price (red dashed line)

The second plot:

  • Revenue curve over price
  • Optimal price with corresponding maximum revenue

This helps managers visualize:

  • How demand drops as price increases
  • Where revenue peaks — the sweet spot

🎯 Conclusion

With just a few lines of Python, we’ve:

  • Learned demand behavior from data
  • Built a revenue model
  • Optimized pricing to maximize profit

This is a basic framework, but in production systems, you could extend this with:

  • Time series forecasting (seasonality)
  • Price elasticity models
  • Multi-product optimization
  • Bayesian or probabilistic models

Let data guide your pricing decisions — because guessing is expensive.