Home▸Articles▸Optimization and Decision Systems

Dynamic Pricing

ML-driven pricing optimization - demand estimation, price elasticity, competitive pricing, and production pricing systems.

mysimulator teamUpdated 2026-01≈ 6 min read▶ Open the simulation

Dynamic pricing adjusts prices in real-time based on demand, competition, inventory, and customer characteristics. ML enables moving from rule-based pricing to data-driven optimization. The goal: maximize revenue (or profit) by finding the price each customer segment will bear for each product at each moment.

Where It Is Used

Dynamic pricing powers revenue optimization across industries:

Products: Uber surge pricing, Amazon repricing, airline revenue management, hotel booking platforms.

The Pricing Problem

Objective: Maximize revenue (or profit)

Revenue = Price × Demand(Price)

The challenge: Demand decreases as price increases (usually). Find the sweet spot.

Price elasticity:

Elasticity = % change in demand / % change in price

Typical Data You Will See

Aspect Typical Values
Products 100 to 1M SKUs
Price changes Hourly to weekly
Price range ±20-50% from base
Demand data Transaction history
Competition Competitor prices (if available)

Data sources: - Transaction data: Price, quantity, timestamp, customer - Inventory: Stock levels, costs, constraints - Competition: Competitor prices, market position - Context: Time, season, events, weather - Customer: Segment, history, willingness to pay

What You Do in Practice

  1. Define objectives - Revenue, profit, market share, inventory clearance?
  2. Collect pricing data - Historical prices and demand
  3. Estimate demand function - How demand varies with price
  4. Model price elasticity - By product, segment, time
  5. Add constraints - Min/max prices, margin requirements
  6. Optimize prices - Find revenue-maximizing prices
  7. Handle competition - React or lead on pricing
  8. Test carefully - A/B test pricing changes
  9. Monitor cannibalization - Cross-product effects
  10. Iterate continuously - Market conditions change

Baseline First

Start with simple demand modeling:

import numpy as np
from sklearn.linear_model import LinearRegression

class SimplePricingModel:
    def __init__(self):
        self.demand_model = LinearRegression()

    def fit(self, prices, quantities, features=None):
        # Log-log model for constant elasticity
        X = np.log(prices).reshape(-1, 1)
        if features is not None:
            X = np.hstack([X, features])
        y = np.log(quantities + 1)
        self.demand_model.fit(X, y)

        # Elasticity is coefficient on log(price)
        self.elasticity = self.demand_model.coef_[0]

    def predict_demand(self, price, features=None):
        X = np.log(price).reshape(-1, 1)
        if features is not None:
            X = np.hstack([X, features])
        log_demand = self.demand_model.predict(X)
        return np.exp(log_demand)

    def optimal_price(self, cost, features=None, price_range=(0.5, 2.0)):
        # Grid search for revenue-maximizing price
        prices = np.linspace(cost * price_range[0], cost * price_range[1], 100)
        revenues = []
        for p in prices:
            demand = self.predict_demand(p, features)
            revenue = p * demand
            revenues.append(revenue)
        return prices[np.argmax(revenues)]

Why simple demand model baseline: - Interpretable elasticity estimates - Fast to implement and iterate - Works for many products - Foundation for more complex models

Pricing Approaches

Approach Description Best For
Cost-plus Cost + fixed margin Simple, guaranteed margin
Competition-based Match/undercut competitors Commodity products
Demand-based Price by willingness to pay Differentiated products
Segmented Different prices by segment Diverse customer base
Time-based Vary by time/demand Perishable inventory
Personalized Individual-level pricing High-value customers

Demand estimation with ML:

import xgboost as xgb

class MLPricingModel:
    def __init__(self):
        self.demand_model = xgb.XGBRegressor()

    def fit(self, df):
        # Features: price, product attributes, time, competition
        features = ['price', 'competitor_price', 'day_of_week',
                    'inventory_level', 'category_encoded']
        X = df[features]
        y = df['quantity_sold']
        self.demand_model.fit(X, y)

    def optimize_price(self, product_context, cost, min_price, max_price):
        # Simulate different prices
        best_price, best_profit = min_price, 0

        for price in np.linspace(min_price, max_price, 50):
            context = product_context.copy()
            context['price'] = price
            demand = self.demand_model.predict([context])[0]
            profit = (price - cost) * demand

            if profit > best_profit:
                best_profit = profit
                best_price = price

        return best_price

Constraints and Business Rules

Real pricing has many constraints:

def apply_pricing_constraints(optimal_price, constraints):
    price = optimal_price

    # Minimum margin
    if price < constraints['cost'] * (1 + constraints['min_margin']):
        price = constraints['cost'] * (1 + constraints['min_margin'])

    # Price bounds
    price = max(constraints['min_price'], price)
    price = min(constraints['max_price'], price)

    # Price ending rules (e.g., $X.99)
    if constraints.get('price_ending'):
        price = round(price) - 0.01

    # Maximum change from current price
    if constraints.get('max_change_pct'):
        current = constraints['current_price']
        max_change = current * constraints['max_change_pct']
        price = max(current - max_change, min(current + max_change, price))

    return price

Evaluation and Metrics

Metric Description Target
Revenue Total revenue Maximize
Profit Revenue - Cost Often primary
Conversion rate Sales / Views Monitor
Price perception Customer surveys Don't harm brand
Competitive position vs competitors Maintain or improve

A/B testing for pricing:

# Careful: pricing A/B tests can be risky
def run_price_test(control_price, test_price, traffic_split=0.1):
    """
    Only test with small traffic to limit revenue loss.
    Use statistical significance carefully.
    """
    # Randomly assign visitors
    # Measure revenue per visitor, not conversion alone
    # Account for selection effects
    pass

Failure Modes and Debugging Checklist

Production Checklist

Before deployment: - [ ] Demand model validated on holdout - [ ] Elasticity estimates reasonable - [ ] Constraints implemented correctly - [ ] Price change limits in place - [ ] A/B test infrastructure ready - [ ] Monitoring dashboards built - [ ] Legal review completed

After deployment: - [ ] Revenue impact tracked - [ ] Price changes monitored - [ ] Customer complaints tracked - [ ] Competitive response monitored - [ ] Model retraining scheduled - [ ] Circuit breakers for anomalies

Business alignment: - [ ] Stakeholder buy-in obtained - [ ] Escalation process defined - [ ] Manual override capability - [ ] Communication plan ready

Tools and Stack

Category Tools
Demand modeling scikit-learn, XGBoost, PyTorch
Optimization scipy.optimize, cvxpy, Gurobi
A/B testing Custom, Optimizely
Competitive data Price scraping, APIs
Deployment Real-time pricing service

Example Mini-Case

Scenario: E-commerce retailer wants to optimize pricing for 10K products.

Approach: 1. Demand estimation: XGBoost model with price, competition, seasonality 2. Elasticity calculation: Per-category price sensitivity 3. Optimization: Constrained revenue maximization 4. Testing: 5% traffic A/B test per product 5. Rollout: Gradual expansion with monitoring

Results:

Metric Before After Change
Revenue $10M/mo $10.8M/mo +8%
Margin 25% 26.5% +1.5pp
Conversion 3.2% 3.1% -0.1pp

Architecture:

Competitor prices → Price optimization service →
Demand model → Optimal price calculation →
Constraint application → Price update API → Storefront

Key learnings: - Elasticity varies 10x across categories - Competition tracking essential for commodity items - Price perception matters - avoid frequent changes - A/B testing caught 2 demand model errors

Related Pages

Further Reading

Try it live

Everything above runs in your browser — open Dynamic Pricing Engine — Demand Elasticity in Real Time and change the parameters while it is running. Nothing is installed, nothing is uploaded, the whole model lives in one tab.

▶ Open Dynamic Pricing Engine — Demand Elasticity in Real Time simulation

What did you find?

Add reproduction steps (optional)