# API Documentation¶

The majority of the package consists of classes, which compartmentalize different aspects of the BLP model. There are some convenience functions as well.

## Configuration Classes¶

Various components of the package require configurations for how to approximate integrals, solve fixed point problems, and solve optimimzation problems. Such configurations are specified with the following classes.

 Formulation(formula[, absorb, …]) Configuration for designing matrices and absorbing fixed effects. Integration(specification, size[, …]) Configuration for building integration nodes and weights. Iteration(method[, method_options, …]) Configuration for solving fixed point problems. Optimization(method[, method_options, …]) Configuration for solving optimization problems.

## Data Manipulation Functions¶

There are also a number of convenience functions that can be used to construct common components of product and agent data, or manipulate other PyBLP objects.

 build_matrix(formulation, data) Construct a matrix according to a formulation. build_blp_instruments(formulation, product_data) Construct “sums of characteristics” excluded BLP instruments. Construct excluded differentiation instruments. build_id_data(T, J, F) Build a balanced panel of market and firm IDs. build_ownership(product_data[, …]) Build ownership matrices, $$O$$. build_integration(integration, dimensions) Build nodes and weights for integration over agent choice probabilities. data_to_dict(data[, ignore_empty]) Convert a NumPy record array into a dictionary. save_pickle(x, path) Save an object as a pickle file. read_pickle(path) Load a pickled object into memory.

## Problem Class¶

Given data and appropriate configurations, a BLP-type problem can be structured by initializing the following class.

 Problem(product_formulations, product_data) A BLP-type problem.

Once initialized, the following method solves the problem.

 Problem.solve([sigma, pi, rho, beta, gamma, …]) Solve the problem.

## Micro Moment Classes¶

Micro moment configurations can be passed to Problem.solve().

 DemographicExpectationMoment(product_ids, …) Configuration for micro moments that match expectations of demographics for agents who choose certain products. CharacteristicExpectationMoment(agent_ids, …) Configuration for micro moments that match expectations of characteristics of products chosen by certain agents. DemographicInteractionMoment(X2_index, …) Configuration for micro moments that match expectations of interactions between product characteristics and demographics. DiversionProbabilityMoment(product_id1, …) Configuration for micro moments that match second choice probabilities of certain products for agents whose first choices are certain other products. DiversionInteractionMoment(X2_index1, …[, …]) Configuration for micro moments that match expectations of interactions between product characteristics of first and second choices. CustomMoment(value, observations, compute_custom) Configuration for custom micro moments.

## Problem Results Class¶

Solved problems return the following results class.

 ProblemResults Results of a solved BLP problem.

The results can be pickled or converted into a dictionary.

 Save these results as a pickle file. ProblemResults.to_dict([attributes]) Convert these results into a dictionary that maps attribute names to values.

The following methods test the validity of overidentifying and model restrictions.

 Test the validity of overidentifying restrictions with the Hansen $$J$$ test. ProblemResults.run_distance_test(unrestricted) Test the validity of model restrictions with the distance test. Test the validity of model restrictions with the Lagrange multiplier test. ProblemResults.run_wald_test(restrictions, …) Test the validity of model restrictions with the Wald test.

In addition to class attributes, other post-estimation outputs can be estimated market-by-market with the following methods, which each return an array.

 Estimate aggregate elasticities of demand, $$\mathscr{E}$$, with respect to a variable, $$x$$. Estimate matrices of elasticities of demand, $$\varepsilon$$, with respect to a variable, $$x$$. Estimate matrices of diversion ratios, $$\mathscr{D}$$, with respect to a variable, $$x$$. Estimate matrices of long-run diversion ratios, $$\bar{\mathscr{D}}$$. ProblemResults.compute_probabilities([market_id]) Estimate matrices of choice probabilities. Extract diagonals from stacked $$J_t \times J_t$$ matrices for each market $$t$$. Extract means of diagonals from stacked $$J_t \times J_t$$ matrices for each market $$t$$. ProblemResults.compute_delta([agent_data, …]) Estimate mean utilities, $$\delta$$. ProblemResults.compute_costs([firm_ids, …]) Estimate marginal costs, $$c$$. Approximate equilibrium prices after firm or cost changes, $$p^*$$, under the assumption that shares and their price derivatives are unaffected by such changes. ProblemResults.compute_prices([firm_ids, …]) Estimate equilibrium prices after firm or cost changes, $$p^*$$. ProblemResults.compute_shares([prices, …]) Estimate shares. ProblemResults.compute_hhi([firm_ids, …]) Estimate Herfindahl-Hirschman Indices, $$\text{HHI}$$. ProblemResults.compute_markups([prices, …]) Estimate markups, $$\mathscr{M}$$. ProblemResults.compute_profits([prices, …]) Estimate population-normalized gross expected profits, $$\pi$$. Estimate population-normalized consumer surpluses, $$\text{CS}$$.

A parametric bootstrap can be used, for example, to compute standard errors for the above post-estimation outputs. The following method returns a results class with all of the above methods, which returns a distribution of post-estimation outputs corresponding to different bootstrapped samples.

 ProblemResults.bootstrap([draws, seed, …]) Use a parametric bootstrap to create an empirical distribution of results.

Optimal instruments, which also return a results class instead of an array, can be estimated with the following method.

 Estimate feasible optimal or efficient instruments, $$Z_D^\text{opt}$$ and $$Z_S^\text{opt}$$.

Importance sampling can be used to create new integration nodes and weights. Its method also returns a results class.

 ProblemResults.importance_sampling(draws[, …]) Use importance sampling to construct nodes and weights for integration.

## Bootstrapped Problem Results Class¶

Parametric bootstrap computation returns the following class.

 BootstrappedResults Bootstrapped results of a solved problem.

This class has all of the same methods as ProblemResults, except for ProblemResults.bootstrap(), ProblemResults.compute_optimal_instruments(), and ProblemResults.importance_sampling(). It can also be pickled or converted into a dictionary.

 Save these results as a pickle file. BootstrappedResults.to_dict([attributes]) Convert these results into a dictionary that maps attribute names to values.

## Optimal Instrument Results Class¶

Optimal instrument computation returns the following results class.

 OptimalInstrumentResults Results of optimal instrument computation.

The results can be pickled or converted into a dictionary.

 Save these results as a pickle file. OptimalInstrumentResults.to_dict([attributes]) Convert these results into a dictionary that maps attribute names to values.

They can also be converted into a Problem with the following method.

 Re-create the problem with estimated feasible optimal instruments.

This method returns the following class, which behaves exactly like a Problem.

 OptimalInstrumentProblem A BLP problem updated with optimal excluded instruments.

## Importance Sampling Results Class¶

Importance sampling returns the following results class:

 ImportanceSamplingResults Results of importance sampling.

The results can be pickled or converted into a dictionary.

 Save these results as a pickle file. ImportanceSamplingResults.to_dict([attributes]) Convert these results into a dictionary that maps attribute names to values.

They can also be converted into a Problem with the following method.

 Re-create the problem with the agent data constructed from importance sampling.

This method returns the following class, which behaves exactly like a Problem.

 ImportanceSamplingProblem A BLP problem updated after importance sampling.

## Simulation Class¶

The following class allows for evaluation of more complicated counterfactuals than is possible with ProblemResults methods, or for simulation of synthetic data from scratch.

 Simulation(product_formulations, …[, …]) Simulation of data in BLP-type models.

Once initialized, the following method replaces prices and shares with equilibrium values that are consistent with true parameters.

 Simulation.replace_endogenous([costs, …]) Replace simulated prices and market shares with equilibrium values that are consistent with true parameters.

A less common way to solve the simulation is to assume simulated prices and shares represent and equilibrium and to replace exogenous variables instead.

 Simulation.replace_exogenous(X1_name[, …]) Replace exogenous product characteristics with values that are consistent with true parameters.

## Simulation Results Class¶

Solved simulations return the following results class.

 SimulationResults Results of a solved simulation of synthetic BLP data.

The results can be pickled or converted into a dictionary.

 Save these results as a pickle file. SimulationResults.to_dict([attributes]) Convert these results into a dictionary that maps attribute names to values.

They can also be converted into a Problem with the following method.

 Convert the solved simulation into a problem.

Simulation results can also be used to compute micro moment values.

 Compute simulated micro moment values $$v_m$$.

## Structured Data Classes¶

Product and agent data that are passed or constructed by Problem and Simulation are structured internally into classes with field names that more closely resemble BLP notation. Although these structured data classes are not directly constructable, they can be accessed with Problem and Simulation class attributes. It can be helpful to compare these structured data classes with the data or configurations used to create them.

 Products Product data structured as a record array. Agents Agent data structured as a record array.

## Multiprocessing¶

A context manager can be used to enable parallel processing for methods that perform market-by-market computation.

 parallel(processes) Context manager used for parallel processing in a with statement context.

## Options and Example Data¶

In addition to classes and functions, there are also two modules that can be used to configure global package options and locate example data that comes with the package.

 options Global options. data Locations of example data that are included in the package for convenience.

## Exceptions¶

When errors occur, they will either be displayed as warnings or raised as exceptions.

 exceptions.MultipleErrors Multiple errors that occurred around the same time. exceptions.NonpositiveCostsError Encountered nonpositive marginal costs in a log-linear specification. exceptions.NonpositiveSyntheticCostsError Encountered nonpositive synthetic marginal costs in a log-linear specification. exceptions.InvalidParameterCovariancesError Failed to compute standard errors because of invalid estimated covariances of GMM parameters. exceptions.InvalidMomentCovariancesError Failed to compute a weighting matrix because of invalid estimated covariances of GMM moments. exceptions.DeltaNumericalError Encountered a numerical error when computing $$\delta$$. exceptions.CostsNumericalError Encountered a numerical error when computing marginal costs. exceptions.MicroMomentsNumericalError Encountered a numerical error when computing micro moments. exceptions.XiByThetaJacobianNumericalError Encountered a numerical error when computing the Jacobian (holding $$\beta$$ fixed) of $$\xi$$ (equivalently, of $$\delta$$) with respect to $$\theta$$. exceptions.OmegaByThetaJacobianNumericalError Encountered a numerical error when computing the Jacobian (holding $$\gamma$$ fixed) of $$\omega$$ (equivalently, of transformed marginal costs) with respect to $$\theta$$. exceptions.MicroMomentsByThetaJacobianNumericalError Encountered a numerical error when computing the Jacobian of micro moments with respect to $$\theta$$. exceptions.MicroMomentCovariancesNumericalError Encountered a numerical error when computing micro moment covariances. exceptions.SyntheticPricesNumericalError Encountered a numerical error when computing synthetic prices. exceptions.SyntheticSharesNumericalError Encountered a numerical error when computing synthetic shares. exceptions.SyntheticDeltaNumericalError Encountered a numerical error when computing the synthetic $$\delta$$. exceptions.SyntheticCostsNumericalError Encountered a numerical error when computing synthetic marginal costs. exceptions.SyntheticMicroMomentsNumericalError Encountered a numerical error when computing synthetic micro moments. exceptions.EquilibriumRealizationNumericalError Encountered a numerical error when solving for a realization of equilibrium prices and shares. exceptions.PostEstimationNumericalError Encountered a numerical error when computing a post-estimation output. exceptions.AbsorptionError A fixed effect absorption procedure failed to properly absorb fixed effects. exceptions.ClippedSharesError Shares were clipped during the final iteration of the fixed point routine for computing $$\delta$$. exceptions.ThetaConvergenceError The optimization routine failed to converge. exceptions.DeltaConvergenceError The fixed point computation of $$\delta$$ failed to converge. exceptions.SyntheticPricesConvergenceError The fixed point computation of synthetic prices failed to converge. exceptions.SyntheticDeltaConvergenceError The fixed point computation of the synthetic $$\delta$$ failed to converge. exceptions.EquilibriumPricesConvergenceError The fixed point computation of equilibrium prices failed to converge. exceptions.ObjectiveReversionError Reverted a problematic GMM objective value. exceptions.GradientReversionError Reverted problematic elements in the GMM objective gradient. exceptions.DeltaReversionError Reverted problematic elements in $$\delta$$. exceptions.CostsReversionError Reverted problematic marginal costs. exceptions.MicroMomentsReversionError Reverted problematic micro moments. exceptions.XiByThetaJacobianReversionError Reverted problematic elements in the Jacobian (holding $$\beta$$ fixed) of $$\xi$$ (equivalently, of $$\delta$$) with respect to $$\theta$$. exceptions.OmegaByThetaJacobianReversionError Reverted problematic elements in the Jacobian (holding $$\gamma$$ fixed) of $$\omega$$ (equivalently, of transformed marginal costs) with respect to $$\theta$$. exceptions.MicroMomentsByThetaJacobianReversionError Reverted problematic elements in the Jacobian of micro moments with respect to $$\theta$$. exceptions.HessianEigenvaluesError Failed to compute eigenvalues for the GMM objective’s (reduced) Hessian matrix. exceptions.FittedValuesInversionError Failed to invert an estimated covariance when computing fitted values. exceptions.SharesByXiJacobianInversionError Failed to invert a Jacobian of shares with respect to $$\xi$$ when computing the Jacobian (holding $$\beta$$ fixed) of $$\xi$$ (equivalently, of $$\delta$$) with respect to $$\theta$$. exceptions.IntraFirmJacobianInversionError Failed to invert an intra-firm Jacobian of shares with respect to prices when computing $$\eta$$. exceptions.LinearParameterCovariancesInversionError Failed to invert an estimated covariance matrix of linear parameters. exceptions.GMMParameterCovariancesInversionError Failed to invert an estimated covariance matrix of GMM parameters. exceptions.GMMMomentCovariancesInversionError Failed to invert an estimated covariance matrix of GMM moments.