PyBLP

repository·master·Indexed 43 days ago

https://github.com/jeffgortmaker/pyblp

A Python 3 implementation of routines for estimating the demand for differentiated products using BLP-type random coefficients logit models. It provides tools for complex demand estimation, counterfactual simulations, and GMM estimation of demand and supply parameters, including support for high-dimensional fixed effects and parallel processing.

Tokens
21.9K
Snippets
59
Records
87
Agent score
55%

What's inside PyBLP

  1. Overview of PyBLP features

    master

    PyBLP is a Python 3 implementation for estimating demand for differentiated products using BLP-type random coefficients logit models.

    Key capabilities include:

    • Estimation Frameworks: R-style formula interface, Multiple equation GMM, Bertrand-Nash supply-side moments, and support for various instruments (Classic BLP, Differentiation, Optimal).
    • Micro Data Integration: Flexible micro moments (survey data, second choice data, or optimal micro moments matching micro data scores).
    • Model Flexibility: Random coefficient nested logit (RCNL), demographic interactions, product-specific demographics, and flexible random coefficient distributions.
    • Advanced Analysis: Merger simulation, custom counterfactual simulation, elasticity and diversion ratio calculations, and profit/consumer surplus analysis.
    • Optimization & Computation: Support for SciPy or Artleys Knitro, Newton and fixed point methods for pricing equilibria, and market-by-market parallelization.
  2. Use the Random Coefficients Nested Logit (RCNL) model

    master

    The RCNL model incorporates parameters ($\rho$) that measure correlation within nesting groups. Each product $j$ is assigned to a nesting group $h(j)$.

    Model Structure

    Idiosyncratic preferences are partitioned as: $$\epsilon_{ijt} = \bar{\epsilon}{ih(j)t} + (1 - \rho{h(j)})\bar{\epsilon}_{ijt}$$

    Key Parameters and Behavior

    • Nesting Parameter $\rho$: Can be a vector (one $\rho_h$ per group) or a scalar (same $\rho$ for all groups).
    • Limits:
      • As $\rho \to 0$, the model converges to the standard BLP model.
      • As $\rho \to 1$, the model results in division by zero errors.
    • Choice Probabilities: The inclusion of nesting parameters makes the choice probability expression $s_{ijt}$ more complex, involving inclusive values $V_{iht}$ for each nesting group.
    • Contraction: The contraction for $\delta(\theta)$ is modified to: $$\delta_{jt} \leftarrow \delta_{jt} + (1 - \rho_{h(j)})[\log s_{jt} - \log s_{jt}(\delta, \theta)]$$
  3. Handle high-dimensional fixed effects

    master

    While small numbers of fixed effects can be included as dummy variables in the instrument and regressor matrices ($X_1, X_3, Z_D, Z_S$), this is computationally infeasible for high-dimensional fixed effects due to the matrix inversion required in the IV step.

    Absorption Method: PyBLP handles high-dimensional fixed effects by "absorbing" them into the $X, Z,$ and $Y(\theta)$ matrices.

    • For $E=1$ (Single Fixed Effect): Matrices are de-meaned within each level of the fixed effect. $X$ and $Z$ can be de-meaned once, but $Y(\theta)$ must be de-meaned for every iteration of $\theta$.
    • For $E > 1$ (Multiple Fixed Effects): Matrices are residualized using more complex algorithms.

    This approach is mathematically equivalent to including dummy variables, as guaranteed by the Frisch-Waugh-Lovell (FWL) theorem.

  4. Understand PyBLP test organization

    master

    The test suite is organized into functional modules to verify both BLP-specific logic and generic mathematical utilities:

    Core Testing Logic

    • tests.conftest: Defines fixtures that configure the testing environment and simulate specific problem specifications.
    • tests.test_blp: Verifies BLP-specific properties, such as ensuring estimated parameters are close to true values in reasonable formulations, verifying that cosmetic changes (like process counts) don't affect estimates, and checking that optimization routines and derivatives behave as expected.

    Utility Testing Logic

    Generic mathematical and computational utilities are verified in the following modules:

    • tests.test_formulation: Matrix formulation.
    • tests.test_integration: Integral approximation (e.g., comparing Gauss-Hermite quadrature vs. Monte Carlo).
    • tests.test_iteration: Fixed point iteration (e.g., verifying SQUAREM efficiency).
    • tests.test_optimization: Nonlinear optimization routines.
  5. Configure BLP models using Configuration Classes

    master

    PyBLP uses specific configuration classes to define how to approximate integrals, solve fixed point problems, and solve optimization problems. You should use these classes to set up the parameters for your model estimation.

    Key configuration classes include:

    • Formulation: Defines the functional forms.
    • Integration: Configures how integrals are approximated.
    • Iteration: Configures fixed-point iteration settings.
    • Optimization: Configures the optimization routines.

    For custom optimization debugging or adding ad-hoc moments, you can use OptimizationProgress to access information about the optimization progress.

  6. Configure micro datasets and moments

    master

    Micro-level data configurations follow a hierarchical structure that is passed into the Problem.solve method:

    1. MicroDataset: The base micro data.
    2. MicroPart: Configurations for specific micro parts.
    3. MicroMoment: Configurations for micro moments.

    These are passed through the hierarchy to define how micro-level information is incorporated into the BLP model.

  7. Compare Logit, Nested Logit, and RCNL models

    master

    Depending on the complexity of the correlation structure required, you can choose between different model specifications:

    1. Logit Model:

      • Assumes $\Sigma = 0$.
      • Has a closed-form solution for $\delta$: $\delta_{jt} = \log s_{jt} - \log s_{0t}$.
      • Often does not require nonlinear optimization because there are no nonlinear parameters.
    2. Nested Logit Model:

      • Requires optimizing over the nesting parameter $\rho$.
      • Has a closed-form solution for $\delta$: $\delta_{jt} = \log s_{jt} - \log s_{0t} - \rho_{h(j)}[\log s_{jt} - \log s_{h(j)t}]$, where $s_{ht} = \sum_{j \in J_{ht}} s_{jt}$.
    3. Random Coefficients Nested Logit (RCNL):

      • The most complex version, incorporating within-nesting group correlation via $\rho$.
      • Requires more complex choice probability calculations and a modified contraction for $\delta$.
  8. Understand the BLP model supply-side components

    master

    The supply side of the BLP model assumes firms maximize profits by choosing prices. Key components include:

    • Supply Characteristics:
      • $X_3$: A matrix of supply-side product characteristics (size $N imes K_3$). Note that prices cannot be included in $X_3$.
      • $\omega$: A vector of unobserved supply-side product characteristics.
    • Marginal Costs:
      • You must specify a functional form for marginal costs $\tilde{c} = f(c)$. Common choices are $f(c) = c$ or $f(c) = \log(c)$.
      • The cost structure is typically modeled as $\tilde{c} = X_3\gamma + \omega$.
    • Pricing and Markups:
      • Firms solve a multi-product differentiated Bertrand first-order condition. The markup $\eta$ depends on the matrix $\Delta$, which represents intra-firm demand derivatives.
      • $\Delta = -\mathscr{H} \odot \frac{\partial s}{\partial p}'$, where $\mathscr{H}$ is the market-level ownership or product holdings matrix. $\mathscr{H}_{jk}$ is typically $1$ if the same firm produces products $j$ and $k$, and $0$ otherwise.
  9. Understand Micro Moments in BLP-style estimation

    master

    Micro moments ($\bar{g}_M$) supplement standard demand- and supply-side moments by using detailed micro data (e.g., survey data) on individual choices.

    Key Concepts

    • Micro Moment: The difference between an observed value $f_m(\bar{v})$ and its simulated analogue $f_m(v)$.
    • Micro Moment Part ($p$): A component of a micro moment defined by a specific dataset $d_p$ and micro values $v_{pijt}$. Each part is an average over observations in its associated micro dataset.
    • Micro Dataset ($d$): Defined by survey weights $w_{dijt}$. Different micro datasets are treated as independent.
    • Function $f_m$: Maps micro moment parts into a micro statistic.
      • Simple Average: $f_m(v) = v_p$ (matches the mean of a micro moment part).
      • Non-simple Averages: Functions like $f_m(v) = v_1 / v_2$ can be used to match conditional means, covariances, correlations, or regression coefficients.

    Implementation Details

    • Estimation Type: If micro moments are not simple averages, the estimator becomes a generic minimum distance estimator rather than a standard GMM estimator (though the package uses GMM terminology).
    • Covariance: The covariance between standard moments and micro moments is zero, resulting in a block-diagonal covariance matrix. The covariance for micro moments is derived via the delta method.
    • Second Choice Moments: Micro moments can also be based on second choices (e.g., the probability of choosing $k$ when $j$ is removed), using datasets defined by weights $w_{dijkt}$.
  10. Calculate standard errors in PyBLP

    master

    Standard errors are derived from the asymptotic covariance matrix of $\sqrt{N}(\hat{\theta} - \theta_0)$.

    The general formula for the covariance matrix is: $(\bar{G}'W\bar{G})^{-1}\bar{G}'WSW\bar{G}(\bar{G}'W\bar{G})^{-1}$

    Where:

    • $\bar{G}$ is the averaged Jacobian of the moments.
    • $W$ is the weighting matrix.
    • $S$ is the covariance of the moments.

    Unadjusted Standard Errors: If the weighting matrix is chosen such that $W = S^{-1}$, the expression simplifies to $(\bar{G}'W\bar{G})^{-1}$. Standard errors extracted from this simplified version are referred to as "unadjusted".

    Standard errors are calculated as the square root of the diagonal elements of the resulting matrix, divided by $\sqrt{N}$ (or $\sqrt{N}$ is already accounted for in the matrix scaling depending on implementation context).

  11. Understand the BLP model demand-side components

    master

    The BLP (Berry, Levinsohn, and Pakes) model in PyBLP describes how agents choose products based on utility. The demand side is defined by several key components:

    • Product Characteristics:
      • $X_1$: A matrix of linear characteristics (size $N imes K_1$). This is partitioned into $X_1^{\text{en}}$ (endogenous characteristics, typically prices $p$) and $X_1^{\text{ex}}$ (exogenous characteristics).
      • $X_2$: A matrix of nonlinear characteristics (size $N imes K_2$), usually a subset of $X_1$.
      • $\xi$: A vector of unobserved demand-side product characteristics.
    • Agent Characteristics:
      • $d$: A matrix of observed demographics (size $I_t imes D$).
      • $\nu$: A matrix of unobserved agent characteristics (size $I_t imes K_2$).
    • Utility Structure:
      • The mean utility $\delta$ is determined by $X_1\beta + \xi$, where $\beta$ contains parameters for both endogenous ($\alpha$) and exogenous ($\beta^{\text{ex}}$) characteristics.
      • The agent-specific utility $\mu$ is modeled as $X_2(\Sigma \nu' + \Pi d')$, where $\Sigma$ is the Cholesky root of the covariance matrix for unobserved taste heterogeneity and $\Pi$ measures how tastes vary with demographics.
    • Market Shares:
      • The model uses a logit link function. Aggregate market shares are approximated using Monte Carlo integration or quadrature rules with integration nodes $\nu$ and weights $w$.
  12. Understand PyBLP notation and indices

    master

    PyBLP uses a specific mathematical notation for describing products, markets, agents, and firms. When reading documentation or interpreting model results, use the following index mappings:

    • j: Products
    • t: Markets
    • i: Agents/individuals
    • f: Firms
    • h: Nests
    • c: Clusters
    • m: Micro moments