Skip to content

ENH: Add the Anderson-Rubin Wald test of the endogenous coefficients - #900

Open
leninworld wants to merge 4 commits into
bashtage:mainfrom
leninworld:anderson-rubin-wald-372
Open

leninworld wants to merge 4 commits into
bashtage:mainfrom
leninworld:anderson-rubin-wald-372

Conversation

@leninworld

Copy link
Copy Markdown
Contributor

This PR fixes issue #372.

IVResults gets anderson_rubin_wald(value=None), the weak-instrument-robust Anderson-Rubin test that the coefficients on the endogenous regressors equal value (zeros by default). The existing anderson_rubin property 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 @ value on the exogenous regressors and the instruments with the model's weights, fits that regression with the same cov_type and cov_config as the model (the pattern of wooldridge_regression), and tests that the instrument coefficients are zero. Without debiased the statistic is chi2(q), q = number of instruments; with debiased=True it is W / q with an F(q, n - k_exog - q) distribution, as f_statistic does. Inverting it over a grid of values gives a confidence set that is valid however weak the instruments are.

res = IV2SLS(y, exog, endog, instr).fit(cov_type="robust")
res.anderson_rubin_wald()      # H0: coefficient on the endogenous regressor is 0
res.anderson_rubin_wald(1.0)   # H0: it is 1.0
res.anderson_rubin_wald(pd.Series({"e2": 0.5, "e1": 1.0}))  # several endogs, by name

Details:

  • value can be a scalar (one endogenous regressor), a list or array in the order of model.endog.cols, or a Series aligned by name. A wrong length or non-finite value raises ValueError; a Series whose names do not match raises KeyError.
  • If the covariance of the instrument coefficients is not positive definite (an exact fit, a clustered covariance with fewer clusters than instruments, or a two-way clustered covariance with a negative variance or a negative eigenvalue), an InvalidTestStatistic is 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.
  • Available for IV2SLS, IVLIML and IVJIVE results (all IVResults), not for IVGMMResults.
  • Limit: extra_df passed to fit is not carried to the auxiliary regression, as in wooldridge_regression (it is not part of cov_config).
  • Docs: the method is listed in doc/source/iv/introduction.rst next 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):

  • homoskedastic statistic equals a numpy hand computation; the debiased form uses F with the stated degrees of freedom;
  • robust and clustered statistics equal wald_test on an IV2SLS of y - Y @ value on [exog, instruments]; weighted, LIML and JIVE results too;
  • scalar, list, array and Series values agree; wrong length, 2-D, NaN/inf, duplicate or unknown Series names raise; the default equals zeros;
  • the test does not reject at the true value and rejects far from it;
  • formula-built models; exact fit, too few clusters, and two-way clustered covariances with a negative variance or eigenvalue (no warnings); no method on GMM results.

Checks run: pytest linearmodels/tests/iv (9955 passed, 2400 skipped), ruff check linearmodels, flake8, black and isort on the changed files.

Fixes #372

if not bool(asarray(isfinite(value_arr)).all()):
raise ValueError("value must contain only finite coefficient values")

from linearmodels.iv.model import _OLS
@codecov

codecov Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.69%. Comparing base (65f4054) to head (d64300f).

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            
Flag Coverage Δ
adder 99.68% <100.00%> (+<0.01%) ⬆️
subtractor 99.68% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bashtage bashtage left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. 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 * eps cut, and the test then reports a huge statistic with a p-value of 0. With generate_data from 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)
  2. 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() and can go (positive_definite = bool((variances > 0).all())): a NaN covariance already fails variances > 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 checking np.isfinite.
  • With clusters and debiased=True the denominator df is n - k, as in f_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 from anderson_rubin back 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.
@leninworld

Copy link
Copy Markdown
Contributor Author

Thanks for checking it against R and by hand. All of it is in d896dcc:

1. Positive-definiteness guard (review)

  • The guard now uses your relative tolerance, eigenvalues[0] > 1e-10 * eigenvalues[-1], with your comment; finfo is gone.
  • Your test is in as written (test_fewer_clusters_than_instruments_is_invalid_in_other_samples). On this Mac, with the old tolerance, (30, 3) and (100, 23) fail and (40, 23) and (50, 95) already pass, so I also added test_fewer_clusters_than_instruments_is_invalid_seed_sweep: seeds 0 to 199 for 30, 50 and 100 observations with 2 clusters. With the old tolerance 7 of those 600 give a statistic here; with the new one all are invalid. The same loop checks the other side: with 3 clusters every sample still gives a finite Wald statistic. It takes about 4 s here (600 fits each way).

2. chi2 or F in the Notes

  • Your paragraph is in, after the one on inverting the test. I checked it against the code: with debiased=True the denominator df is n - (nexog + ninstr).

Optional points

  • Kept isfinite(cov).all(). You're right that no test changes without it, but with an infinite variance the scaling cov / outer(std, std) would warn before the eigenvalue check, and keeping it costs nothing. Happy to drop it if you prefer.
  • value : float or array_like, optional; anderson_rubin now has a See Also entry for anderson_rubin_wald.
  • Notes: with clusters and debiased=True the denominator df is n - k as in f_statistic, while ivreg2's AR F uses G - 1.
  • New tests: a kernel covariance (Bartlett, bandwidth 4) against the Wald test of the auxiliary regression; rows with missing values dropped by the model give the same result as dropping them first; multiplying an instrument by 1e6 leaves the statistic and p-value unchanged; a Series with a name that is not an endogenous regressor raises KeyError; the formula test now compares the statistic and p-value with the array model.

Checks: linearmodels/tests/iv 9,964 passed, 2,400 skipped; test_anderson_rubin_wald.py 25 passed with -W error::RuntimeWarning; ruff, flake8, black and isort clean on the changed files.

The failure-only append lines were never run, which lowered the patch
coverage of the pull request.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ENH: Anderson-Rubin F-test of endogenous regressors for IV regression

3 participants