Repository navigation
Conversation
The two-way clustered covariance of the panel models is not guaranteed to be positive semi-definite, and in small panels a variance can be negative. The standard error was then NaN with a RuntimeWarning from np.sqrt. - Add the cov_config option fix_psd. With two-way clustering it sets the negative eigenvalues of the parameter covariance to zero, as in Cameron, Gelbach and Miller (2011). The default, False, does not change results. - Issue a NegativeVarianceWarning, a RuntimeWarning, that names the parameters with a negative variance, instead of NumPy's warning. With two-way clustering it points to fix_psd. Closes bashtage#831 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W74MiDikqd2RitwCNYw17E
|
First pass LGTM. Thanks. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #863 +/- ##
========================================
Coverage 99.69% 99.69%
========================================
Files 207 209 +2
Lines 39478 39762 +284
Branches 2541 2547 +6
========================================
+ Hits 39357 39641 +284
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:
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W74MiDikqd2RitwCNYw17E
|
Could you verify that this fixes all of the models identified in #831? Not sure this is a closes or just an ref. |
bashtage
left a comment
There was a problem hiding this comment.
I checked my question from earlier: this fixes the panel models only. On this branch, the IV models still give a negative variance and a NaN standard error with two-way clusters, and they don't accept fix_psd:
import numpy as np
import pandas as pd
from linearmodels.iv import IV2SLS
rng = np.random.default_rng(0)
n = 60
x = pd.DataFrame({"const": 1.0, "x": rng.standard_normal(n)})
y = pd.Series(rng.standard_normal(n), name="y")
clusters = pd.DataFrame({"a": rng.integers(0, 4, n), "b": rng.integers(0, 4, n)})
res = IV2SLS(y, x, None, None).fit(cov_type="clustered", clusters=clusters)
print(np.diag(res.cov)) # [ 0.01076232 -0.00969557]
print(res.std_errors) # x is NaNIVLIML gives the same, and AbsorbingLS also has a negative variance. Merging with "Closes #831" would close the issue, so please either extend fix_psd to the clustered covariances of the IV and absorbing models (clip_negative_eigenvalues is already generic, so this should be small) or change it to "xref #831".
Also before merging:
.. versionadded:: 7.2forfix_psd(the model docstrings andClusteredCovariance),clip_negative_eigenvaluesandNegativeVarianceWarning;- document
NegativeVarianceWarningindoc/source/utility.rst, next toMissingValueWarning; - a tolerance instead of
rtol=0, atol=0intest_fix_psd_definite_unchanged,test_fix_psd_one_way_unchangedand the symmetry check intest_clip_negative_eigenvalues; - a 7.2 note under "New features".
IV2SLS, IVLIML, OLS and AbsorbingLS use the two-way clustered covariance of linearmodels.iv.covariance, which has the same problem as the panel covariance (bashtage#831): it is not guaranteed to be positive semi-definite, and a variance can be negative in small samples. ClusteredCovariance accepts fix_psd=True, which sets the negative eigenvalues of the two-way clustered covariance to zero, and reports it in its config, so that the cov_config of the results can be passed to fit again. IVGMM, IVGMMCUE and IVJIVE only support one-way clustering. The results of these models issue the NegativeVarianceWarning of the panel models, instead of NumPy's RuntimeWarning from sqrt. The warning is built by negative_variance_warning in shared/exceptions.py, which the panel and IV results share. Only the two-way clustered covariance can have a negative variance, since the other estimators are positive semi-definite, so the message always points to fix_psd for a two-way clustered covariance. This removes the check of the type of the estimator, whose other branch could only be reached by replacing a private attribute in a test.
…lerance The checks that fix_psd leaves a positive definite or one-way clustered covariance unchanged, and that the fixed covariance is symmetric, used rtol=0 and atol=0.
fix_psd in the panel models and in ClusteredCovariance, clip_negative_eigenvalues and NegativeVarianceWarning are new in 7.2. The warning is documented in the utility page next to MissingValueWarning, and the 7.2 notes list the feature under "New features" and thank echuq. Closes bashtage#831
|
I've finished this so that it can go into 7.2, on top of your commits:
Thanks for the contribution. |
Closes #831. This takes both options from the issue: a clear warning by default, and an opt-in fix.
Problem
The two-way clustered covariance (V_entity + V_time − V_entity∩time) is not guaranteed to be PSD. In small panels, a parameter variance can come out negative, so
std_errorsis NaN and the only signal is NumPy'sinvalid value encountered in sqrt.Changes
cov_configoptionfix_psdforcov_type="clustered"in all the panel models. With two-way clustering, it decomposes V = UΛU' and replaces V with UΛ₊U', where the negative eigenvalues are set to zero (Cameron, Gelbach and Miller, 2011). One-way clustering and PSD covariances are left unchanged.False, so existing results don't change. For reference, R'ssandwich::vcovCL(fix = FALSE)defaults to off, whilefixest(vcov_fix = TRUE) andreghdfeapply the fix by default. I'm happy to flip the default, or to rename the option, if you'd prefer.PanelResults.covnow issues aNegativeVarianceWarningthat names the affected parameters. With two-way clustering it also points tofix_psd. It replaces NumPy's sqrt warning, and it subclassesRuntimeWarning, so existing warning filters still work.linearmodels.shared.covariance.clip_negative_eigenvalues. The IV and system models also support two-way clustering and could reuse it in a follow-up. I left them out to keep this PR focused on the panel models.Tests
linearmodels/tests/panel/test_two_way_cluster_psd.py:fix_psd=Trueequals the eigenvalue-clipped covariance and gives finite standard errors and p-values.clusters=,PanelOLSandRandomEffects.cov_types, and a non-bool value raises.test_clustered_df.pyandtest_grid_inputs.pycompare two-way covariances that are not PSD in some samples. They now ignore the new warning, in line with the comment already incompare_results.-W error::NegativeVarianceWarningfor the panel tests. The only failures are 3test_time_zones_are_not_compared_by_instant[...US/Eastern]cases, which also fail onmainin my environment because of the tz database.ruff checkand the numpydoc lint are clean.AI disclosure
I used Claude (Anthropic) to help draft the implementation, the tests and this description. I reviewed the changes and checked the formula against Cameron, Gelbach and Miller (2011).