Repository navigation
ENH: Add the Anderson-Rubin Wald test of the endogenous coefficients - #900
leninworld wants to merge 4 commits into
Conversation
| if not bool(asarray(isfinite(value_arr)).all()): | ||
| raise ValueError("value must contain only finite coefficient values") | ||
|
|
||
| from linearmodels.iv.model import _OLS |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #900 +/- ##
========================================
Coverage 99.69% 99.69%
========================================
Files 207 208 +1
Lines 39478 39758 +280
Branches 2541 2554 +13
========================================
+ Hits 39357 39637 +280
Misses 52 52
Partials 69 69
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
bashtage
left a comment
There was a problem hiding this comment.
Thanks, this is a useful addition and the statistic is right. I checked it against a hand computation and against R for unadjusted, robust, one- and two-way clustered and kernel covariances, debiased or not, with both fit methods, weights, LIML and JIVE, formulas and dropped missing rows; everything agrees to about 1e-15. The debiased version equals the classical F from the two sums of squares, and nothing leaks a warning.
-
The positive-definiteness guard lets some singular covariances through. With 2 clusters and 2 instruments the covariance of the instrument coefficients has rank 1, but rounding leaves eigenvalue ratios of up to about 40 eps, above the
ninstr * epscut, and the test then reports a huge statistic with a p-value of 0. Withgenerate_datafrom your tests, 9 of 1,200 such samples got through here, e.g.generate_data(nobs=30, seed=3)gives 2.5e17. Valid covariances are far away (the smallest ratio I found with one more cluster than instruments was 3e-7), so a relative tolerance of 1e-10 separates them with a wide margin:@@ -17,7 +17,6 @@ from numpy import ( c_, diag, empty, - finfo, isfinite, isnan, log, @@ -1484,6 +1483,8 @@ class IVResults(_CommonIVResults): if positive_definite: std = sqrt(variances) eigenvalues = eigvalsh(cov / outer(std, std)) - tolerance = ninstr * finfo(float).eps * eigenvalues[-1] - positive_definite = bool(eigenvalues[0] > tolerance) + # The covariance is singular if there are fewer clusters than + # instruments, and rounding leaves eigenvalues of up to about 50 eps, + # so the tolerance is well above eps. Valid covariances are far above it + positive_definite = bool(eigenvalues[0] > 1e-10 * eigenvalues[-1]) if not positive_definite:
with a test next to
test_clustered_covariance_with_fewer_clusters_than_instruments_is_invalid(these seeds fail on the current head on my machine; the exact seeds may differ elsewhere):@pytest.mark.parametrize(("nobs", "seed"), [(30, 3), (40, 23), (50, 95), (100, 23)]) def test_fewer_clusters_than_instruments_is_invalid_in_other_samples(nobs, seed): # The covariance of the instrument coefficients has rank 1 with 2 clusters y, exog, endog, instr, _ = generate_data(nobs=nobs, seed=seed) clusters = np.arange(nobs) % 2 result = IV2SLS(y, exog, endog, instr).fit( cov_type="clustered", clusters=clusters, method="qr" ) assert isinstance(result.anderson_rubin_wald(1.0), InvalidTestStatistic)
-
Please say in the Notes when the statistic is chi2 and when it is F, e.g. after the paragraph on inverting the test:
The statistic has a :math:`\chi^2_q` distribution, where :math:`q` is the number of excluded instruments. If the model was fit with ``debiased=True``, the covariance of the auxiliary regression is debiased as well, and the statistic is divided by :math:`q` and has an :math:`F_{q,n-k}` distribution, where :math:`k` is the number of exogenous regressors and instruments.
Optional:
isfinite(cov).all() andcan go (positive_definite = bool((variances > 0).all())): a NaN covariance already failsvariances > 0, and I could not get an infinite one through the public API. Removing it changes no test.- The robust, clustered, weighted and JIVE tests compare with
IV2SLS(y0, regressors, None, None).fit(...).wald_test(...), which runs the same covariance code as_OLS, so only the homoskedastic test is independent. Nothing tests a kernel covariance (the bandwidth of the fit is reused), a model with dropped missing rows, a Series with an extra name, or that rescaling an instrument does not change the statistic (which is what the correlation scaling of the guard is for). The formula test could compare with the array model instead of checkingnp.isfinite. - With clusters and
debiased=Truethe denominator df is n - k, as inf_statistic. ivreg2's AR F is the same statistic but uses G - 1, so a sentence in the Notes may save someone a puzzled comparison. value : float or array_like, optional, since a scalar is accepted, and a See Also link fromanderson_rubinback to the new method.
Use a relative eigenvalue tolerance of 1e-10 so that clustered covariances with fewer clusters than instruments are reported as invalid instead of giving a huge statistic. Document when the statistic is chi2 and when it is F, and add tests for kernel covariances, dropped missing rows, instrument rescaling, unknown Series names and formula models.
|
Thanks for checking it against R and by hand. All of it is in d896dcc: 1. Positive-definiteness guard (review)
2. chi2 or F in the Notes
Optional points
Checks: |
The failure-only append lines were never run, which lowered the patch coverage of the pull request.
This PR fixes issue #372.
IVResultsgetsanderson_rubin_wald(value=None), the weak-instrument-robust Anderson-Rubin test that the coefficients on the endogenous regressors equalvalue(zeros by default). The existinganderson_rubinproperty is the LIML test of overidentification and is unchanged; the new name follows ivreg2's "Anderson-Rubin Wald test".How it works: it regresses
y - Y @ valueon the exogenous regressors and the instruments with the model's weights, fits that regression with the samecov_typeandcov_configas the model (the pattern ofwooldridge_regression), and tests that the instrument coefficients are zero. Withoutdebiasedthe statistic is chi2(q), q = number of instruments; withdebiased=Trueit is W / q with an F(q, n - k_exog - q) distribution, asf_statisticdoes. Inverting it over a grid of values gives a confidence set that is valid however weak the instruments are.Details:
valuecan be a scalar (one endogenous regressor), a list or array in the order ofmodel.endog.cols, or a Series aligned by name. A wrong length or non-finite value raisesValueError; a Series whose names do not match raisesKeyError.InvalidTestStatisticis returned instead of a meaningless or negative statistic. The check is on the correlation matrix, so it does not depend on the units of the instruments.IVResults), not forIVGMMResults.extra_dfpassed tofitis not carried to the auxiliary regression, as inwooldridge_regression(it is not part ofcov_config).doc/source/iv/introduction.rstnext to the other tests, and a release note is under "Version 7.2" / New features.Tests (
linearmodels/tests/iv/test_anderson_rubin_wald.py, 16 tests, all fail on main and pass here):wald_teston anIV2SLSofy - Y @ valueon[exog, instruments]; weighted, LIML and JIVE results too;Checks run:
pytest linearmodels/tests/iv(9955 passed, 2400 skipped),ruff check linearmodels, flake8, black and isort on the changed files.Fixes #372