Skip to content

DPredict · Guide test 185

Hansen J test

Tests overidentifying moment restrictions using a generalized method of moments criterion with suitable covariance estimation.

Runs in CodeSplashPython (calls R) example not runR example validated

Do it in CodeSplash

In the app, set it up in Analyze with this method:

In Instrumental variables (2SLS / LIML / GMM), choose Estimator = Two-step efficient GMM.

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Hansen J test

200
0.60
0.40

0 makes x exogenous: OLS and 2SLS estimate the same thing.

0.70
0.20

Not 0: z₂ violates the exclusion restriction (an invalid instrument).

0.050

Your data

Simulated with known truth
—— first stage, slope 0.47—— OLS 1.09– – IV 0.96

Left: how strongly the instruments move x (a flat line means weak instruments). Right: OLS and the instrumented slope; they part when x is endogenous.

If H₀ were true

J = 11.45
  1. The reference: how J varies across samples when H₀ is true (χ² approximation).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = < .001).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

J=n gˉ(β^)⊤S^−1gˉ(β^)∼χL−K2,gˉ(β)=1n∑izi(yi−xi⊤β)J = n\,\bar g(\hat\beta)^{\top}\hat{\mathbf S}^{-1}\bar g(\hat\beta) \sim \chi^2_{L-K},\qquad \bar g(\beta) = \tfrac1n\sum_i z_i(y_i - x_i^{\top}\beta)

With your numbers

J=11.45,df=1J = 11.45,\qquad df = 1
S^\hat{\mathbf S}
covariance of the moments (heteroskedasticity-robust)
β^\hat\beta
two-step efficient GMM estimate

The verdict

J(1) = 11.45, p < .001

p ≤ α = .050: reject H₀

The robust version of Sargan's test; the same caveat applies: consistent invalid instruments go unnoticed.

Statistic
11.451
p-value
0.0007
Hansen J test on 200 observations: outcome y, regressor x, instruments z1 and z2: J(1) = 11.45, p < .001. The p-value is below α = .050, so the data are hard to reconcile with H0.

Hansen J test on 200 observations: outcome y, regressor x, instruments z₁ and z₂: J(1) = 11.45, p < .001. The p-value is below α = .050, so the data are hard to reconcile with H₀.

Question and hypotheses

H0: all population moment restrictions E[g(Z,θ)]=0 hold for some θ.

Assumptions

Identified GMM model, valid large sample regularity, and a consistent optimal covariance weight that accounts for heteroskedasticity/dependence as needed.

Formula

J=ngˉ(θ^)TS^−1gˉ(θ^)≈χL−K2J=n\bar g(\widehat\theta)^T\widehat S^{-1}\bar g(\widehat\theta)\approx\chi^2_{L-K}

Parameters and notation

L moment conditions,K estimated parameters; S estimates the long-run covariance of √n ḡ.

Structure of the method

Estimate parameters by an efficient GMM criterion and evaluate the remaining sample moment vector using a consistent inverse covariance weight. Multiplying the minimized quadratic criterion by sample size gives J. Its chi-square reference depends on valid moments, identification, and appropriate optimal weighting, not just on the algebraic quadratic form.

Estimated and nuisance parameters

Structural parameters, moment means, and the covariance or long-run covariance of moments are estimated. A two-step procedure first obtains preliminary parameters and then estimates the weight; continuously updated or iterated versions have different computational paths.

Settings and design choices

Prespecify moment conditions, instrument reduction, covariance type, HAC kernel/bandwidth if needed, optimizer tolerances, and GMM variant. The displayed MDS setting permits martingale-difference-type moment behavior and should not be silently treated as a general HAC correction for arbitrary serial correlation.

Fitting and adaptation

Recompute both parameter estimates and the weight after changing moments or data. For bootstrap inference, reproduce the full estimator/weight-fitting sequence under a valid null design. Numerical convergence and objective scaling should be inspected; arbitrary fixed weights do not justify the standard J reference.

Sensitivity and robustness

Weak identification, many moments, ill-conditioned covariance, finite samples, and moment misspecification can undermine chi-square calibration. Rejection cannot isolate the failed moment; nonrejection can reflect weak power. Report excess-moment degrees of freedom, weighting details, and diagnostics for instruments and optimizer behavior. This is statistical estimation and recalibration, not neural fine-tuning.

How to use and calibrate

Compute at the efficient GMM estimate and use the upper chi square tail.

Example application

Test overidentifying restrictions in a heteroskedastic IV/GMM model.

Interpretation and pitfalls

Watch out

Arbitrary weights do not give this chi square law. Many or weak instruments can make the test uninformative.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.

Python and R

Hansen J for overidentified GMM with heteroskedastic martingale-difference moment covariance. Using vcov="iid" in this linear model would impose homoskedastic structure.

Python · invokes R

Not run — Executed end to end through Rscript · needs Python standard library + Rscript; R packages: gmm

# Python launcher for the complete R implementation below.
# Requires Rscript on PATH and the listed R packages.
import shutil
import subprocess
rscript = shutil.which("Rscript")
if rscript is None:
    raise RuntimeError("Install R and make Rscript available on PATH.")
r_code = r"""
set.seed(2026)
n<-200;z1<-rnorm(n);z2<-rnorm(n);u<-rnorm(n);v<-rnorm(n);x<-.8*z1+.5*z2+.6*u+v;y<-1+.7*x+u;d<-data.frame(y,x,z1,z2)
fit<-gmm::gmm(y~x,~z1+z2,data=d,vcov="MDS");print(gmm::specTest(fit))
"""
# No shell interpolation. A failed R execution raises an error in Python.
result = subprocess.run([rscript, "--vanilla", "-"], input=r_code,
                        text=True, capture_output=True)
print(result.stdout)
if result.stderr:
    print(result.stderr)
result.check_returncode()
R

Validated — Executed successfully in the validation environment · needs gmm

set.seed(2026)
n<-200;z1<-rnorm(n);z2<-rnorm(n);u<-rnorm(n);v<-rnorm(n);x<-.8*z1+.5*z2+.6*u+v;y<-1+.7*x+u;d<-data.frame(y,x,z1,z2)
fit<-gmm::gmm(y~x,~z1+z2,data=d,vcov="MDS");print(gmm::specTest(fit))
Output
 ##  J-Test: degrees of freedom is 1  ## 

                J-test    P-value 
Test E(g)=0:    0.048452  0.825779

Sources

Statistics guide v4 (historical):
Python: Executed end to end through Rscript · R: Executed successfully in the validation environment
Reference's record:
Edition 2 review: Python: skip · R: not executed (Rscript unavailable); why not run: Python: Python-to-R bridge; Rscript is unavailable. R code was not executed. Python: Not run in the reference's review: Python-to-R bridge; Rscript is unavailable. R code was not executed. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 185, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT185.