Skip to content

twosls module

TSLS function that can be iterated.

print_tsls_results(estimated_coeffs, estimated_stderrs, names_coeffs=None, title=None)

Print the estimated coefficients and their standard errors.

Parameters:

Name Type Description Default
estimated_coeffs ndarray

Estimated coefficients.

required
estimated_stderrs ndarray

Estimated standard errors.

required
names_coeffs list[str] | None

Coefficient names. If None, the coefficients are labeled coeff_0, coeff_1, ...

None
title str | None

Header printed above the results. If None, "Two-stage least squares estimates:" is used.

None
Source code in frac_blp/twosls.py
 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
def print_tsls_results(
    estimated_coeffs: np.ndarray,
    estimated_stderrs: np.ndarray,
    names_coeffs: list[str] | None = None,
    title: str | None = None,
) -> None:
    """
    Print the estimated coefficients and their standard errors.

    Args:
        estimated_coeffs (np.ndarray): Estimated coefficients.
        estimated_stderrs (np.ndarray): Estimated standard errors.
        names_coeffs (list[str] | None): Coefficient names. If None, the
            coefficients are labeled ``coeff_0``, ``coeff_1``, ...
        title (str | None): Header printed above the results. If None,
            ``"Two-stage least squares estimates:"`` is used.
    """
    n_coeffs = estimated_coeffs.size
    if names_coeffs is None:
        names_coeffs = [f"coeff_{i}" for i in range(n_coeffs)]
    if title is None:
        title = "Two-stage least squares estimates:"
    console.rule(title)
    table = Table(show_header=True, header_style="bold")
    table.add_column("Coefficient", style="cyan", no_wrap=True)
    table.add_column("Estimate", justify="right")
    table.add_column("Std err", justify="right")
    for name, coeff, stderr in zip(names_coeffs, estimated_coeffs, estimated_stderrs):
        table.add_row(name, f"{coeff:.3f}", f"{stderr:.3f}")
    console.print(table)

tsls_estimate(y, X, Z, J, optimal_instruments=True, prev_residuals=None, X_proj=None)

Estimate \(E(y - X heta | Z) = 0\) by 2SLS with optimal instruments and weighting matrix.

The previous residuals are used to estimate the within-market covariance of the errors, which gives the optimal instruments and the weighting matrix.

Parameters:

Name Type Description Default
y ndarray

Dependent variable, a (T*J,) vector.

required
X ndarray

Regressors, a (T*J, K) matrix.

required
Z ndarray

Instruments, a (T*J, L) matrix.

required
J int

Number of products in each market.

required
optimal_instruments bool

If True, use optimal instruments. Default is True.

True
prev_residuals ndarray | None

Previous residuals, a (T*J,) vector. If None, the OLS residuals of y on X are used.

None
X_proj ndarray | None

Projection of X onto Z, a (T*J, K) matrix. If None, it is computed here. Pass it in to avoid recomputing it.

None

Returns:

Type Description
ndarray

tuple[np.ndarray, np.ndarray, np.ndarray]: The estimated coefficients

ndarray

(a K-vector), their estimated variance (a (K, K) matrix), and the new

ndarray

residuals (a (T*J,) vector).

Source code in frac_blp/twosls.py
12
13
14
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
def tsls_estimate(
    y: np.ndarray,
    X: np.ndarray,
    Z: np.ndarray,
    J: int,
    optimal_instruments: bool = True,
    prev_residuals: np.ndarray | None = None,
    X_proj: np.ndarray | None = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Estimate $E(y - X\theta | Z) = 0$ by 2SLS with optimal instruments and weighting matrix.

    The previous residuals are used to estimate the within-market covariance
    of the errors, which gives the optimal instruments and the weighting matrix.

    Args:
        y (np.ndarray): Dependent variable, a (T*J,) vector.
        X (np.ndarray): Regressors, a (T*J, K) matrix.
        Z (np.ndarray): Instruments, a (T*J, L) matrix.
        J (int): Number of products in each market.
        optimal_instruments (bool): If True, use optimal instruments. Default is True.
        prev_residuals (np.ndarray | None): Previous residuals, a (T*J,) vector.
            If None, the OLS residuals of ``y`` on ``X`` are used.
        X_proj (np.ndarray | None): Projection of ``X`` onto ``Z``, a (T*J, K) matrix.
            If None, it is computed here. Pass it in to avoid recomputing it.

    Returns:
        tuple[np.ndarray, np.ndarray, np.ndarray]: The estimated coefficients
        (a K-vector), their estimated variance (a (K, K) matrix), and the new
        residuals (a (T*J,) vector).
    """
    if prev_residuals is None:  # we use the OLS residuals
        ols_est = np.linalg.lstsq(X, y, rcond=None)[0]
        prev_residuals = y - X @ ols_est

    # First stage: project X onto Z
    if X_proj is None:
        X_proj = proj_on_Z(X, Z)[0]

    n_obs, n_x = X.shape

    if optimal_instruments:
        D_mat = -X_proj
        Z_opt = D_mat
    else:
        Z_opt = Z

    # and the W weighting matrix
    Z_opt_moments = Z_opt * prev_residuals.reshape((-1, 1))
    W_mat = make_centered_covariance(Z_opt_moments)
    W_inv = np.linalg.pinv(W_mat)

    # W_inv: np.ndarray[tuple[Any, ...], np.dtype[np.float64]] = np.eye(n_x)  # --- IGNORE --- for testing only

    ZX = Z_opt.T @ X / n_obs
    ZXT = ZX.T
    Zy = Z_opt.T @ y / n_obs
    theta_est = np.linalg.solve(ZXT @ W_inv @ ZX, ZXT @ W_inv @ Zy)

    new_residuals = y - X @ theta_est

    theta_est_var = np.linalg.inv(ZXT @ W_inv @ ZX) / n_obs

    return theta_est, theta_est_var, new_residuals