Skip to content

frac_nodemog_estimate module

FRAC estimation on macro-BLP, without demographics.

nodemog_estimate(frac_data, degree_Z=2, degree_X1=2, optimal_instruments=True, run_projections=True)

Estimate FRAC parameters without demographics using two-stage least squares.

Parameters:

Name Type Description Default
frac_data FracNoDemogData

Data container with regressors, instruments, and simulated or empirical shares.

required
degree_Z int

Degree of polynomial expansion for instruments. Default is 2.

2
degree_X1 int

Degree of polynomial expansion for exogenous regressors in X1. Default is 2.

2
optimal_instruments bool

If True, use optimal instruments. Default is True.

True
run_projections bool

If True, print the R-squared values of the first-stage projections on the instruments. Default is True.

True

Returns:

Name Type Description
TwoArrays TwoArrays

Tuple (betas_sigmas_est, stderrs_est): the estimated fixed

TwoArrays

coefficients followed by the estimated variances of the random coefficients,

TwoArrays

and their standard errors.

Raises:

Type Description
SystemExit

If one of the estimated variances is negative.

Source code in frac_blp/frac_nodemog_estimate.py
 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
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def nodemog_estimate(
    frac_data: FracNoDemogData,
    degree_Z: int = 2,
    degree_X1: int = 2,
    optimal_instruments: bool = True,
    run_projections: bool = True,
) -> TwoArrays:
    """
    Estimate FRAC parameters without demographics using two-stage least squares.

    Args:
        frac_data (FracNoDemogData): Data container with regressors, instruments, and
            simulated or empirical shares.
        degree_Z (int): Degree of polynomial expansion for instruments. Default is 2.
        degree_X1 (int): Degree of polynomial expansion for exogenous regressors in X1.
            Default is 2.
        optimal_instruments (bool): If True, use optimal instruments. Default is True.
        run_projections (bool): If True, print the R-squared values of the first-stage
            projections on the instruments. Default is True.

    Returns:
        TwoArrays: Tuple ``(betas_sigmas_est, stderrs_est)``: the estimated fixed
        coefficients followed by the estimated variances of the random coefficients,
        and their standard errors.

    Raises:
        SystemExit: If one of the estimated variances is negative.
    """
    X1_exo = frac_data.X1_exo
    X1, X2 = frac_data.X1.astype(np.float64), frac_data.X2.astype(np.float64)
    J, T = frac_data.J, frac_data.T
    Z = frac_data.Z
    names_X1 = frac_data.names_X1
    names_X2 = frac_data.names_X2
    shares = frac_data.shares

    # print(f"{shares.min()=}, {shares.max()=}")

    y = make_y(shares, J)

    # term2 = X * (X / 2 - e1), with e1 = sum_j S_j X_j, computed for all markets at once
    S_all = shares.reshape((T, J))
    X2_all = X2.reshape((T, J, -1))
    e1 = np.einsum("tj,tjk->tk", S_all, X2_all)
    K = (X2_all * (X2_all / 2.0 - e1[:, None, :])).reshape(X2.shape)

    n_X1 = X1.shape[1]
    n_X2 = X2.shape[1]

    # combine exogenous regressors and instruments
    Z_full = make_Z_full(Z, X1_exo, degree_Z=degree_Z, degree_X1=degree_X1).astype(
        np.float64
    )

    # combine covariates and artificial regressors
    X = np.column_stack((X1, K))

    # project X on the full set of instruments, once: used for the R2s and by TSLS
    X_proj, _, r2_X = proj_on_Z(X, Z_full)

    if run_projections:
        _, _, r2_y = proj_on_Z(y.reshape((frac_data.n_obs, 1)), Z_full)
        r2_X1, r2_K = r2_X[:n_X1], r2_X[n_X1:]

        console.rule(
            f"First stage R2s on the full set of {Z_full.shape[1]} instruments"
        )
        r2_table = Table(show_header=True, header_style="bold")
        r2_table.add_column("Variable", style="cyan", no_wrap=True)
        r2_table.add_column("R2", justify="right")
        r2_table.add_row("y", f"{r2_y[0]:.3f}")
        for ix in range(n_X1):
            r2_table.add_row(names_X1[ix], f"{r2_X1[ix]:.3f}")
        for ix in range(n_X2):
            r2_table.add_row(f"K_{names_X2[ix]}", f"{r2_K[ix]:.3f}")
        console.print(r2_table)

    # run TSLS
    console.rule("Running TSLS")
    betas_sigmas_est, beta_sigmas_varest, xi_est = tsls_estimate(
        y,
        X,
        Z_full,
        J,
        optimal_instruments,
        prev_residuals=None,
        X_proj=X_proj,
    )
    sigmas_squared_est = betas_sigmas_est[n_X1:]
    if np.min(sigmas_squared_est) < 0.0:
        console.print("The variance estimates are:")
        console.print(sigmas_squared_est)
        console.print("[bold red]We have a negative variance estimate![/]")

    stderrs_est = np.sqrt(np.diag(beta_sigmas_varest))

    print_tsls_results(
        betas_sigmas_est,
        stderrs_est,
        names_coeffs=names_X1 + ["sigma2_" + name for name in names_X2],
        title="The FRAC second-order estimates are:",
    )

    return betas_sigmas_est, stderrs_est