Systems, IV & GMM¶
The classes and functions of the row "Systems, IV & GMM" of Analytical tools, with what calls return (the results and their methods: forecasts, impulse responses, tests). Import them from pymetrix (from pymetrix import ...) unless a heading names another module. Parameters and return types are in each signature; the text says what each does.
Help topics: Instrumental variables, Systems of equations: SUR and 3SLS, Specification and diagnostic tests, Maximum likelihood, Least squares.
Classes¶
Endogeneity
dataclass
¶
Bases: Test
Durbin-Wu-Hausman test (regression form): are the instrumented regressors endogenous?
FIML
dataclass
¶
FIML(cov: Annotated[Cov, Widget('choice', help='classic; white: robust to heteroskedasticity; hac: and to serial correlation')] = 'classic', iterate: Annotated[bool, Widget('checkbox', help='re-estimate the residual covariance until the estimates settle')] = False, df_correction: Annotated[bool, Widget('checkbox', advanced=True, help='divide residual cross-products by sqrt((n-k_i)(n-k_j)), not n')] = False, hac_lags: Annotated[int | None, Widget('number', min=0, max=48, advanced=True, help='Newey-West lags; empty = 4(n/100)^(2/9)')] = None, tol: Annotated[float, Widget('number', advanced=True, help='convergence tolerance')] = 1e-08, max_iter: Annotated[int, Widget('number', min=1, max=10000, advanced=True, help='most iterations')] = 500)
Bases: _SystemMethod
Full-information maximum likelihood: the whole simultaneous system, identities included, by maximum likelihood under normal errors. Efficient when the model is right, but a misspecified equation can bias the others; needs as many equations (with identities) as endogenous variables, and no instruments.
FirstStage
dataclass
¶
Bases: Test
Instrument strength: partial F of the excluded instruments in each first stage.
GMM
dataclass
¶
GMM(instruments: Annotated[Sequence[str], Widget('', help='every instrument, exogenous regressors included (the constant is added): at least one per parameter')] = (), weights: Annotated[Literal['optimal', 'identity'], Widget('choice', help="optimal: weighted by the moments' covariance; identity: W = I, one step")] = 'optimal', steps: Annotated[Literal['two', 'iterated', 'cue'], Widget('choice', help='two-step, iterated until the estimates settle, or continuously updated (CUE)')] = 'two', cov: Annotated[str, Widget('', help='covariance S of the moments, which weights them and gives the standard errors: white, classic or hac')] = 'white', hac_lags: Annotated[int, Widget('number', min=0, max=100, advanced=True, help='Newey-West lags; 0 = automatic')] = 0, constant: Annotated[bool, Widget('checkbox', advanced=True, help='a constant among the instruments')] = True, start: Annotated[Mapping[str, float] | None, Widget('', help="starting values for explicit-form equations, e.g. beta=0.99, gamma=2; empty = 0.1 or the Param's")] = None, max_iter: Annotated[int, Widget('number', min=1, max=1000, advanced=True, help='iterations of the iterated estimator')] = 100, tol: Annotated[float, Widget('number', min=1e-14, max=0.01, advanced=True, help='iterated estimator: stop when the estimates change by less than this (relative)')] = 1e-08, endog: Annotated[Sequence[str], Widget('', help='not used by GMM: list the instruments in full instead')] = ())
Generalised method of moments: the equation's residual is orthogonal to the instruments (Hansen 1982).
List every instrument, the exogenous regressors included; the constant is added unless switched off. With as many instruments as parameters GMM is just IV; with more, the efficient weighting gives estimates asymptotically at least as precise as 2SLS when the errors are heteroskedastic or (hac) autocorrelated, and Hansen's J tests the over-identifying restrictions: a small p-value says some instruments are invalid or the model is wrong, but a large one cannot show that all are valid. The instruments must be relevant as well as valid: with weak instruments the estimates are biased and the standard errors too small. Many instruments, relative to the sample, make the two-step estimates biased towards least squares, weaken the J test and understate the standard errors; keep the set small. The continuously updated estimator (CUE) is less biased with many or weak instruments, but its objective can have several minima.
HansenJ
dataclass
¶
Bases: Test
Hansen's J test of overidentifying restrictions, from an IV-GMM fit.
IV
dataclass
¶
IV(endog: Sequence[str], instruments: Sequence[str], cov: str | Cluster = 'classic', hac_lags: int | None = None, start: Annotated[Mapping[str, float] | None, _START] = None, hac_correction: Annotated[bool, Widget('checkbox', advanced=True, help="HAC: multiply by n / (n - k), as EViews and Stata's newey; untick for statsmodels' default")] = True, restrictions: Annotated[str | Sequence[str] | None, _RESTRICTIONS] = None)
Two-stage least squares.
endog names the endogenous regressors (linear form: term labels such
as "y"; explicit form: variables whose current value is endogenous).
instruments lists the excluded instruments as expressions. Every other
regressor, and the constant, instruments itself.
The estimates are consistent when the excluded instruments are relevant (they move the endogenous regressors, given the exogenous ones) and valid (uncorrelated with the error, so rightly left out of the equation). At least as many excluded instruments as endogenous regressors are needed; more over-identify the equation. For the linear form the notes give each endogenous regressor's first-stage F of the excluded instruments: below about 10 the instruments are weak, 2SLS is biased towards OLS and its standard errors understate the uncertainty. Its diagnostics add the Sargan test of the over-identifying restrictions (it can detect invalid instruments only if some are valid) and a Durbin-Wu-Hausman test of whether the instrumented regressors are endogenous at all.
restrictions=[...] imposes linear restrictions on the coefficients as for OLS, with (Xhat'Xhat)^-1 in place
of (X'X)^-1 (Xhat: the regressors projected on the instruments); the first stage is unchanged.
IVGMM
dataclass
¶
IVGMM(endog: Sequence[str], instruments: Sequence[str], cov: str | Cluster = 'white', hac_lags: int | None = None, weight_type: Annotated[Literal['robust', 'unadjusted', 'kernel', 'clustered'], _adv('weighting matrix')] = 'robust', iter_limit: Annotated[int, _adv('GMM iterations (2 = two-step; large = iterated)', min=1, max=1000)] = 2, tol: Annotated[float, _adv('convergence tolerance for iterated GMM', min=1e-12, max=0.01, step=1e-06)] = 0.0001, debiased: Annotated[bool, _adv('small-sample (n-k) correction of the covariance')] = True, backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())
Bases: _Wrapped
Efficient GMM with instruments; reports Hansen's J test of overidentifying restrictions.
LIML
dataclass
¶
LIML(endog: Sequence[str], instruments: Sequence[str], cov: str | Cluster = 'classic', hac_lags: int | None = None, fuller: Annotated[float, _adv("Fuller's alpha (0 = LIML, 1 is common)", min=0, max=10, step=1)] = 0.0, kappa: Annotated[float | None, _adv('fixed k-class kappa; empty = estimate (LIML)')] = None, debiased: Annotated[bool, _adv('small-sample (n-k) correction of the covariance')] = True, backend_options: Annotated[BackendOptions, _BACKEND_OPTIONS] = dict())
Bases: _Wrapped
Limited-information maximum likelihood (or k-class with kappa; Fuller with fuller).
MinimumDistance
dataclass
¶
MinimumDistance(names: tuple[str, ...], values: ndarray, cov: ndarray, distance: float = 0.0, df: int = 0, provenance: Any = None)
Classical minimum distance: structural parameters fitted to reduced-form estimates.
MomentGMM
dataclass
¶
MomentGMM(moments: Any, start: Mapping[str, float], weights: Literal['optimal', 'identity'] = 'optimal', steps: Literal['two', 'iterated', 'cue'] = 'two', cov: Literal['white', 'hac'] = 'white', hac_lags: int = 0, center: bool = False, bounds: Mapping[str, tuple[float, float]] = dict(), max_iter: int = 100, tol: float = 1e-08)
GMM on moment conditions written as a Python function: moments(params, frame) returns each period's (or
unit's) contributions to the moments, an n x L array or DataFrame, one row per row of frame; GMM sets their
means to zero as closely as the weights allow (Hansen 1982).
def euler(p, d): # E[(beta (c/c[-1])^-gamma R - 1) z] = 0
u = p["beta"] * (d.c / d.c.shift(1)) ** -p["gamma"] * d.r - 1
return np.column_stack([u, u * d.c.shift(1) / d.c.shift(2), u * d.r.shift(1)])
MomentGMM(euler, start={"beta": 0.99, "gamma": 2.0}).fit(data)
The function gets the whole frame (so lags reach before the span); the rows used are those in span whose
moments are all finite at the starting values. The first step weights the moments equally (W = I, as statsmodels'
GMM); steps="two" re-weights once by the inverse of their covariance S, "iterated" until the estimates
settle, "cue" continuously updates S. S is robust (cov="white") or Newey-West ("hac"), from the
contributions as they are or center-ed. Derivatives are numerical. Hansen's J tests the over-identifying
restrictions. Written in code only: a function cannot be recorded as a dialog step.
SUR
dataclass
¶
SUR(cov: Annotated[Cov, Widget('choice', help='classic; white: robust to heteroskedasticity; hac: and to serial correlation')] = 'classic', iterate: Annotated[bool, Widget('checkbox', help='re-estimate the residual covariance until the estimates settle')] = False, df_correction: Annotated[bool, Widget('checkbox', advanced=True, help='divide residual cross-products by sqrt((n-k_i)(n-k_j)), not n')] = False, hac_lags: Annotated[int | None, Widget('number', min=0, max=48, advanced=True, help='Newey-West lags; empty = 4(n/100)^(2/9)')] = None, tol: Annotated[float, Widget('number', advanced=True, help='convergence tolerance')] = 1e-08, max_iter: Annotated[int, Widget('number', min=1, max=10000, advanced=True, help='most iterations')] = 500)
Bases: _SystemMethod
Seemingly unrelated regressions (Zellner): generalised least squares allowing for errors correlated across equations. More precise than equation-by-equation least squares when the equations have different regressors and their errors are correlated. Iterated, it is maximum likelihood.
System
dataclass
¶
System(equations: Sequence[Equation] | Mapping[str, Equation], instruments: Sequence[str] = (), endogenous: Sequence[str] = (), restrictions: str = '')
Equations estimated together. equations is a list (named by their targets) or a mapping of names.
instrument_list
¶
The constant is added separately; these are the regressors that are not endogenous, then instruments.
fit
¶
fit(data: Dataset, method: Any = None, span: tuple[Any, Any] | None = None, where: str | None = None, start: Mapping[str, float] | None = None, missing: Literal['drop', 'raise'] = 'drop') -> FittedSystem
Estimate the system over the sample common to all its equations.
SystemOLS
dataclass
¶
SystemOLS(cov: Annotated[Cov, Widget('choice', help='classic; white: robust to heteroskedasticity; hac: and to serial correlation')] = 'classic', iterate: Annotated[bool, Widget('checkbox', help='re-estimate the residual covariance until the estimates settle')] = False, df_correction: Annotated[bool, Widget('checkbox', advanced=True, help='divide residual cross-products by sqrt((n-k_i)(n-k_j)), not n')] = False, hac_lags: Annotated[int | None, Widget('number', min=0, max=48, advanced=True, help='Newey-West lags; empty = 4(n/100)^(2/9)')] = None, tol: Annotated[float, Widget('number', advanced=True, help='convergence tolerance')] = 1e-08, max_iter: Annotated[int, Widget('number', min=1, max=10000, advanced=True, help='most iterations')] = 500)
Bases: _SystemMethod
Each equation by least squares, but jointly, so that parameters can be shared or restricted across equations. Standard errors allow for errors correlated across equations.
ThreeSLS
dataclass
¶
ThreeSLS(cov: Annotated[Cov, Widget('choice', help='classic; white: robust to heteroskedasticity; hac: and to serial correlation')] = 'classic', iterate: Annotated[bool, Widget('checkbox', help='re-estimate the residual covariance until the estimates settle')] = False, df_correction: Annotated[bool, Widget('checkbox', advanced=True, help='divide residual cross-products by sqrt((n-k_i)(n-k_j)), not n')] = False, hac_lags: Annotated[int | None, Widget('number', min=0, max=48, advanced=True, help='Newey-West lags; empty = 4(n/100)^(2/9)')] = None, tol: Annotated[float, Widget('number', advanced=True, help='convergence tolerance')] = 1e-08, max_iter: Annotated[int, Widget('number', min=1, max=10000, advanced=True, help='most iterations')] = 500)
Bases: _SystemMethod
Three-stage least squares (Zellner and Theil): SUR on equations whose regressors are endogenous, using the system's instruments. Consistent with endogenous regressors, and efficient among instrumental-variable estimators of the system when the errors are homoskedastic.
TwoSLS
dataclass
¶
TwoSLS(cov: Annotated[Cov, Widget('choice', help='classic; white: robust to heteroskedasticity; hac: and to serial correlation')] = 'classic', iterate: Annotated[bool, Widget('checkbox', help='re-estimate the residual covariance until the estimates settle')] = False, df_correction: Annotated[bool, Widget('checkbox', advanced=True, help='divide residual cross-products by sqrt((n-k_i)(n-k_j)), not n')] = False, hac_lags: Annotated[int | None, Widget('number', min=0, max=48, advanced=True, help='Newey-West lags; empty = 4(n/100)^(2/9)')] = None, tol: Annotated[float, Widget('number', advanced=True, help='convergence tolerance')] = 1e-08, max_iter: Annotated[int, Widget('number', min=1, max=10000, advanced=True, help='most iterations')] = 500)
Bases: _SystemMethod
Each equation by two-stage least squares with the system's instruments, jointly (shared parameters and restrictions allowed).
Functions¶
anderson_rubin
¶
anderson_rubin(equation: Equation, data: Dataset, endog: str, instruments: Sequence[str], value: float, cov: str = 'classic', span: Any = None) -> Any
The Anderson-Rubin (1949) test that the coefficient on endog is value: regress y - value * endog on the
other regressors and the excluded instruments, and test that the instruments' coefficients are zero (an F test,
exact with normal errors; cov="white" for a robust Wald test). Valid however weak the instruments.
anderson_rubin_set
¶
anderson_rubin_set(equation: Equation, data: Dataset, endog: str, instruments: Sequence[str], grid: Sequence[float], alpha: float = 0.05, cov: str = 'classic', span: Any = None) -> DataFrame
The Anderson-Rubin confidence set by test inversion: the grid values not rejected at alpha (with each
p-value). It may be bounded, unbounded or empty, as weak identification allows.
c_test
¶
c_test(equation: Equation, data: Dataset, method: GMM, suspect: Sequence[str], span: Any = None) -> Any
The C (difference-in-Sargan) test that the suspect instruments are valid, given the others: Hansen's J with all
the instruments less J without the suspect ones, both minimised with the full set's S estimated from the two-step
residuals (the block of it for the subset), so C is never negative,
chi-squared with as many degrees of freedom as suspect instruments (Eichenbaum, Hansen and Singleton 1988; Hayashi
2000).
efficient_method_of_moments
¶
efficient_method_of_moments(data: Any, simulate: Callable[[ndarray, ndarray], Any], fit_auxiliary: Callable[[Any], Any], score: Callable[[Any, Any], Any], theta0: Sequence[float], length: int = 10, shocks: Callable[[Generator, int], ndarray] | None = None, names: Sequence[str] | None = None, lags: int | None = None, seed: int = 0, maxiter: int = 4000) -> SimulationEstimate
The efficient method of moments: the auxiliary model is fitted to the data (fit_auxiliary(y) gives beta), and
theta makes the mean of its per-period score (score(y, beta), periods by parameters) on one simulated path
length times the data's as near zero as possible, weighted by the inverse long-run covariance of the data's
scores.
indirect_inference
¶
indirect_inference(data: Any, simulate: Callable[[ndarray, ndarray], Any], auxiliary: Callable[[Any], Any], theta0: Sequence[float], paths: int = 10, shocks: Callable[[Generator, int], ndarray] | None = None, names: Sequence[str] | None = None, weight: str = 'efficient', seed: int = 0, maxiter: int = 4000) -> SimulationEstimate
Indirect inference: theta such that the auxiliary estimates on paths simulated paths average to those on the
data. simulate(theta, shocks) gives a path of the data's length from the random numbers shocks (by default
standard normals, one more than the data's length; give shocks(rng, n) to draw others). weight: "efficient"
(the inverse covariance of the auxiliary estimates, by simulation at a first-step estimate) or "identity".
minimum_distance
¶
minimum_distance(estimates: Sequence[float], cov: Any, restriction: Any, theta0: Sequence[float], names: Sequence[str] | None = None) -> MinimumDistance
Classical minimum distance (Chamberlain 1982): theta minimising (pi - h(theta))' V^-1 (pi - h(theta)), with pi
reduced-form estimates, V their covariance and h the restriction; standard errors (H' V^-1 H)^-1, H the
Jacobian of h; the minimised distance is chi-squared with len(pi) - len(theta) degrees of freedom.
simulated_moments
¶
simulated_moments(data: Any, simulate: Callable[[ndarray, ndarray], Any], moments: Callable[[Any], Any], theta0: Sequence[float], paths: int = 10, shocks: Callable[[Generator, int], ndarray] | None = None, names: Sequence[str] | None = None, lags: int | None = None, seed: int = 0, maxiter: int = 4000) -> SimulationEstimate
The simulated method of moments: theta such that the means of the per-period moments(y) (an array, periods
by moments) on simulated paths match the data's, weighted by the inverse of their Newey-West long-run covariance.
stock_wright
¶
stock_wright(equation: Equation, data: Dataset, method: GMM, values: Mapping[str, float], span: Any = None) -> Any
Stock and Wright's (2000) S test that every parameter has the given values: the continuously updated GMM
objective there, chi-squared with as many degrees of freedom as moments, whatever the instruments' strength.
Results¶
FittedGMM
dataclass
¶
FittedGMM(params: Any, stats: Mapping[str, float], contributions: DataFrame, method: MomentGMM, notes: tuple[str, ...] = (), provenance: Any = None)
GMM estimates from moment functions: params (values and covariance), stats (J, its p-value and degrees
of freedom, observations, moments, steps), contributions (the moments at the estimates, by row) and notes.
FittedSystem
dataclass
¶
FittedSystem(system: System, method: Any, params: PointEstimate, equations: tuple[FittedEquation, ...], sigma: DataFrame, resid: DataFrame, stats: Mapping[str, float], provenance: Provenance, instrument_names: tuple[str, ...] = ())
Estimates of a system: all parameters with their joint covariance, and each equation as a FittedEquation.
SimulationEstimate
dataclass
¶
SimulationEstimate(method: str, names: tuple[str, ...], values: ndarray, cov: ndarray, distance: float = 0.0, J: float | None = None, J_df: int = 0, paths: int = 1, nobs: int = 0, converged: bool = True, summaries: int = 0, provenance: Any = None)
Parameters estimated by simulation, with sandwich standard errors and the over-identification test.