Skip to main content
v2026.11,986 entries · CC-BY 4.0

PyBLP: BLP Demand Estimation in Python

PyBLP is a Python package for BLP random-coefficients demand estimation: model, share inversion example, code, output and citation.

Written and maintained by CASRAI Editorial Board

Published

On this page

PyBLP is an open-source Python 3 package that estimates demand for differentiated products with the BLP random coefficients logit model, and then uses the estimates for elasticities, diversion ratios, markups and merger simulation. It is written by Jeff Gortmaker in collaboration with Chris Conlon, released under the MIT license, and installed with pip install pyblp. This guide explains what the model does, shows a hand-checkable share-inversion example, gives starter code in Excel, R and Python, and lists what to report and cite.

What is PyBLP?

PyBLP implements the estimation approach of Berry, Levinsohn and Pakes (BLP) for markets in which consumers choose among many similar products (cars, breakfast cereal, smartphones). A researcher supplies market-level data (product shares, prices, product characteristics, instruments) and, optionally, simulated or observed consumer demographics. The package returns taste parameters and, through post-estimation methods, the economic quantities that industrial-organization and antitrust work needs. The documentation on Read the Docs describes the main object as pyblp.Problem, with results returned as ProblemResults and further classes for bootstrapped results, optimal-instrument results, simulation and micro moments.

BLP is the method; PyBLP is one implementation of it. The search results for the same query also list MATLAB code, an R package (BLPestimatoR) and Julia code (BLPDemand.jl), so a replication package that says only “BLP” does not tell a reader which software, version or numerical settings produced the estimates. The Python package states the version it was run with on its PyPI page, which is why a citation should include it (see the reporting section).

The BLP model behind PyBLP

Utility, shares and what the symbols mean

The PyBLP background page writes the utility that consumer i receives from product j in market t as the sum of three parts: U = δ + μ + ε. Utility from the outside good (not buying any product in the data) is normalised to zero.

  • δ (mean utility) equals X1β + ξ: the linear characteristics X1 (including price) times coefficients β, plus an unobserved product-level demand shock ξ.
  • μ (heterogeneous taste) equals X2(Σν′ + Πd′) in the documentation’s notation: characteristics X2 whose coefficients vary across consumers through random draws ν scaled by Σ and through demographics d scaled by Π.
  • ε is a Type I extreme-value idiosyncratic term, which gives logit choice probabilities sijt = exp(Vijt) / (1 + Σk exp(Vikt)).

Market shares are the average of these individual probabilities over consumers. Because that average has no closed form once Σ or Π is non-zero, PyBLP integrates it numerically, by Monte Carlo draws or quadrature. A random coefficients nested logit (RCNL) variant adds nesting parameters ρ, and an optional supply side adds multiproduct Bertrand-Nash pricing, in which markups are η = Δ-1s and marginal cost is c = p − η.

How estimation proceeds

According to the same background page, PyBLP minimises a generalized method of moments (GMM) objective q(θ) = g′Wg. Three ideas keep this tractable:

  1. Invert shares. For any trial values of the nonlinear parameters, a contraction mapping δ ← δ + log s − log s(δ, θ) finds the mean utilities that reproduce the observed shares.
  2. Concentrate out linear parameters. Given δ, the linear coefficients are recovered by instrumental-variables GMM, so the optimizer searches only over the nonlinear parameters (Σ, Π, ρ). The optimizer uses an analytic gradient.
  3. Weight in steps. The first-stage weighting matrix is two-stage least squares, (Z′Z/N)-1; the two-step estimator then uses W = S-1.

The instruments Z matter because price is correlated with the unobserved shock ξ. If that idea is new, read the CASRAI guides on endogeneity and its remedies and on instrumental variables and weak-instrument diagnostics first.

Worked example: inverting shares by hand

This is an illustrative composite with invented numbers, chosen so that the arithmetic can be checked by hand; it is not data from any study. The documentation states that when Σ = 0 (plain logit, no random coefficients) the share inversion has a closed form, δj = log sj − log s0, where s0 is the outside-good share.

Suppose one market has two products with observed shares s1 = 0.20 and s2 = 0.10, so the outside good has s0 = 1 − 0.20 − 0.10 = 0.70.

  • δ1 = ln(0.20 / 0.70) = ln(0.2857) = −1.2528
  • δ2 = ln(0.10 / 0.70) = ln(0.1429) = −1.9459
  • The difference δ1 − δ2 = ln(0.20 / 0.10) = ln 2 = 0.6931

Now run the contraction instead, starting from δ = (0, 0). Model shares at the start are exp(0) / (1 + 1 + 1) = 0.3333 for each product. One update gives δ1 = 0 + ln 0.20 − ln 0.3333 = −1.6094 + 1.0986 = −0.5108 and δ2 = 0 + ln 0.10 − ln 0.3333 = −2.3026 + 1.0986 = −1.2040. Repeating the update gives (−0.9676, −1.6607), then (−1.1584, −1.8515), then (−1.2235, −1.9166), and after eight iterations (−1.2525, −1.9457), which is within 0.001 of the closed-form answer. In a real BLP problem Σ is not zero, no closed form exists, and PyBLP relies on exactly this kind of iteration inside every optimizer step. Because the loop runs for every market and every trial parameter vector, the choice of iteration tolerance affects the final estimates, which is one reason published BLP work reports numerical settings.

Install and run a minimal workflow in Python

The README gives pip install pyblp (and pip install --upgrade pyblp to update). PyPI lists release 1.3.0 as the latest when checked on 2026-11-19 and requires Python 3.6 or newer.

The tutorial notebook that replicates the original automobile application builds the problem this way (the data files ship with the package):

import numpy as np
import pandas as pd
import pyblp

product_data = pd.read_csv(pyblp.data.BLP_PRODUCTS_LOCATION)
agent_data = pd.read_csv(pyblp.data.BLP_AGENTS_LOCATION)

product_formulations = (
    pyblp.Formulation('1 + hpwt + air + mpd + space'),                  # X1: linear demand
    pyblp.Formulation('1 + prices + hpwt + air + mpd + space'),         # X2: random coefficients
    pyblp.Formulation('1 + log(hpwt) + air + log(mpg) + log(space) + trend'),  # X3: supply side
)
agent_formulation = pyblp.Formulation('0 + I(1 / income)')

problem = pyblp.Problem(product_formulations, product_data, agent_formulation, agent_data, costs_type='log')

results = problem.solve(
    np.diag([3.612, 0, 4.628, 1.818, 1.050, 2.056]),   # starting values for Sigma
    np.c_[[0, -43.501, 0, 0, 0, 0]],                   # starting values for Pi
    costs_bounds=(0.001, None),
    W_type='clustered', se_type='clustered', initial_update=True,
)
print(results)

Each Formulation is a patsy-style formula. The Problem signature in the API reference is Problem(product_formulations, product_data, agent_formulation=None, agent_data=None, integration=None, rc_types=None, epsilon_scale=1.0, costs_type='linear', add_exogenous=True). Required product_data columns are market_ids, shares and prices; excluded instruments are supplied as columns named demand_instruments0, demand_instruments1 and so on. The data table below lists every product-data field named in the reference.

The same share inversion in Excel, R and Python

The closed-form logit inversion from the worked example is the quickest sanity check on a data file before any call to solve. With shares in B2:B3 and the outside share computed in B4 as =1-SUM(B2:B3):

Excel:  =LN(B2/B$4)    (fill down for each product in the market)
# R
shares = c(0.20, 0.10)
s0 = 1 - sum(shares)
delta = log(shares) - log(s0)
delta   # -1.2528 -1.9459
# Python (pandas)
import numpy as np, pandas as pd
df = pd.DataFrame({'market_ids': [1, 1], 'shares': [0.20, 0.10]})
df['outside'] = 1 - df.groupby('market_ids')['shares'].transform('sum')
df['delta'] = np.log(df['shares']) - np.log(df['outside'])
print(df['delta'].round(4).tolist())   # [-1.2528, -1.9459]

What PyBLP can do after estimation

The ProblemResults reference lists post-estimation methods that the other top results for this query do not describe as a set. They fall into four groups, and the PyBLP tutorial has matching notebooks for elasticities and diversion ratios, markups, mergers, bootstrapping and optimal instruments.

  • Demand responses: compute_elasticities, compute_aggregate_elasticities, compute_diversion_ratios, compute_long_run_diversion_ratios, compute_demand_jacobians, compute_demand_hessians, compute_probabilities and compute_shares.
  • Supply side and market power: compute_costs, compute_markups, compute_profits, compute_profit_hessians, compute_passthrough and compute_hhi (Herfindahl-Hirschman indices).
  • Counterfactuals and welfare: compute_prices (equilibrium prices after firm or cost changes such as a merger), compute_approximate_prices and compute_consumer_surpluses.
  • Inference and instruments: bootstrap for a parametric bootstrap, and compute_optimal_instruments for feasible optimal or efficient instruments. Micro-moment methods (compute_micro_values, compute_micro_scores, compute_agent_scores) let you bring in consumer-level data.

Counterfactual quantities such as a post-merger price change inherit every assumption of the demand and supply model, so they should be reported with the estimation settings that produced them.

How to read the output

The printed ProblemResults summary is organised into sections. The table gives reading guidance for each, based on the documentation’s definitions and the tutorial’s printed output.

Output section What it contains How to read it
Problem Results Summary GMM step, objective value, projected gradient norm, reduced Hessian eigenvalues, clipped shares and costs, condition numbers Check the gradient norm and Hessian eigenvalues to see whether the optimizer reached a minimum; check the clipped counts for numerical trouble
Cumulative Statistics Computation time, optimizer convergence, iterations, contraction evaluations Confirm that the optimizer reports convergence; the tutorial’s own printout shows a run that did not after 56 iterations
Nonlinear Coefficient Estimates Σ and Π with standard errors Σ measures the spread of taste for a characteristic across consumers; Π measures how taste shifts with a demographic
Beta Estimates Linear demand coefficients Average taste for each characteristic in X1, including price
Gamma Estimates Linear supply (cost) coefficients Present only when a supply side was specified

The tutorial’s automobile run uses T = 20 markets, N = 2,217 products, F = 26 firms and I = 4,000 simulated agents, with standard errors clustered over 999 clusters. The page itself notes that the replicated results differ somewhat from the original paper but are similar, which is a useful reminder that two correct implementations rarely match to the last digit.

Assumptions and common mistakes

  • The outside good is part of the model. Shares must be computed over the whole potential market, so that s0 = 1 − Σsj is positive; the definition of market size is a modelling choice that the data alone do not settle.
  • Instruments carry the identification. Price is endogenous in the model, so excluded instruments in demand_instruments0, demand_instruments1 and so on, are not optional in practice. Check instrument strength before trusting a Σ estimate.
  • Nesting needs ρ. If nesting_ids are supplied, the solve call requires rho; forgetting this is a setup error, not an estimation problem.
  • Supply-side requires ownership information. firm_ids are required when a supply side (X3) is specified, and the supply side assumes Bertrand-Nash pricing by multiproduct firms. If that is not a credible conduct assumption for the market, estimate demand alone.
  • Importance-sampling warnings can be expected. The tutorial notes that a warning that integration weights do not sum to one is expected when draws come from importance sampling.
  • Simulation noise is not zero. Σ and Π are estimated with numerically integrated shares, so the number and type of draws and the optimizer and iteration tolerances belong in the replication package.

When no random coefficients are needed, a simpler logit or nested logit is the cleaner choice. Researchers who want the underlying choice model without the supply and pricing layer may find the CASRAI guides on multinomial logistic regression and discrete choice experiments a useful starting point, and Monte Carlo simulation explains the integration idea in general terms. For the discipline context, see what econometrics is.

How to report and cite PyBLP

The README asks users to cite Conlon and Gortmaker’s paper on best practices for PyBLP. An APA 7th-style reference is:

Conlon, C., & Gortmaker, J. (2020). Best practices for differentiated products demand estimation with PyBLP. RAND Journal of Economics, 51(4), 1108-1161.

Users of the micro moments functionality are asked to cite the authors’ micro-moments paper listed in the README as well. A methods sentence might read: “We estimate a random coefficients logit model of demand with PyBLP (version 1.3.0; Conlon and Gortmaker, 2020), using two-step GMM with clustered weighting and standard errors.” Then report, in a table or appendix: the version, the integration type and number of draws, the optimizer and its tolerances, the starting values, the instruments, the weighting-matrix type and whether the optimizer reported convergence. These are the items the printed summary exposes and the ones a reader needs to rerun the estimates.

Sources

Data: PyBLP product_data fields and when each is needed

Compiled from the pyblp.Problem API reference and the PyBLP random coefficients tutorial: for each product_data field named in the reference, whether it is required, optional or conditional, and what the documentation says it is used for.

Period covered: 2026.

PyBLP product_data fields and when each is needed
FieldRequirementDocumented role
market_idsRequiredIdentifies the market each product row belongs to
sharesRequiredObserved market shares of the inside products
pricesRequiredProduct prices
firm_idsRequired if a supply side (X3) is specifiedIdentifies the firm that sells each product
demand_instruments0, demand_instruments1, ...Excluded instruments (supplied as numbered columns)Demand-side excluded instruments
supply_instruments0, supply_instruments1, ...Excluded instruments (supplied as numbered columns)Supply-side excluded instruments
nesting_idsOptional; rho is then required in solveDefines nests for nested logit and RCNL models
clustering_idsOptionalUsed for clustered weighting and standard errors (W_type and se_type set to clustered in the tutorial)
ownershipOptionalListed as an optional product_data field in the API reference
product_idsOptionalListed as an optional product_data field in the API reference

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about PyBLP: BLP Demand Estimation in Python

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →