From be957b54ec5ef76a5ca0f4c226b2a045d90c29a4 Mon Sep 17 00:00:00 2001 From: Cyber-Marty <15370813896@163.com> Date: Wed, 25 Nov 2026 10:59:32 +0800 Subject: [PATCH] BUG: Require residual degrees of freedom in FamaMacBethCovariance --- linearmodels/panel/covariance.py | 22 +++++-- .../tests/panel/test_no_residual_df.py | 58 +++++++++++++++++++ 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/linearmodels/panel/covariance.py b/linearmodels/panel/covariance.py index dd43e4d567..90dd88ea5a 100644 --- a/linearmodels/panel/covariance.py +++ b/linearmodels/panel/covariance.py @@ -888,10 +888,13 @@ class FamaMacBethCovariance(HomoskedasticCovariance): Raises ------ ValueError - If the bandwidth is not below the number of time periods that are used. - It is also raised if the bandwidth is not provided and there are fewer - time periods than the kernel needs to compute it, or if the bandwidth - that is computed is not finite. + If there are no residual degrees of freedom, which occurs when at most + one cross-sectional estimate is available and ``debiased`` is True, or + if no finite cross-sectional estimates are available. It is also raised + if the bandwidth is not below the number of time periods that are used, + if the bandwidth is not provided and there are fewer time periods than + the kernel needs to compute it, or if the bandwidth that is computed is + not finite. UnknownOptionError If ``kernel`` is not one of the supported names, whether or not the covariance is a kernel covariance. It is both a ``ValueError`` and a @@ -961,10 +964,17 @@ def __init__( # Checked here, also if the bandwidth is selected from the data, so that fit # raises and not the first use of the covariance self._kernel_weights = lookup_option(KERNEL_LOOKUP, self._kernel, "kernel") + deviations = np.asarray(all_params) - params.T + nperiods = int(np.all(np.isfinite(deviations), 1).sum()) + if nperiods - int(bool(debiased)) <= 0: + period_word = "period" if nperiods == 1 else "periods" + raise ValueError( + "The covariance of the model cannot be estimated since the model has " + f"no residual degrees of freedom. It uses {nperiods} cross-sectional " + f"time {period_word}." + ) if bandwidth is not None: # Checked here so that fit raises, and not the first use of the covariance - deviations = np.asarray(all_params) - params.T - nperiods = int(np.all(np.isfinite(deviations), 1).sum()) if bandwidth >= nperiods: raise ValueError( "The bandwidth of the Fama-MacBeth kernel covariance, " diff --git a/linearmodels/tests/panel/test_no_residual_df.py b/linearmodels/tests/panel/test_no_residual_df.py index abe21026ba..8919ac6476 100644 --- a/linearmodels/tests/panel/test_no_residual_df.py +++ b/linearmodels/tests/panel/test_no_residual_df.py @@ -21,6 +21,7 @@ PanelOLS, PooledOLS, ) +from linearmodels.panel.covariance import FamaMacBethCovariance from linearmodels.shared.exceptions import InferenceUnavailableWarning from linearmodels.shared.hypotheses import ( InapplicableTestStatistic, @@ -149,3 +150,60 @@ def test_single_period_with_time_effects(const): res = PanelOLS(y, x, time_effects=True).fit() assert isinstance(res.f_pooled, InapplicableTestStatistic) assert np.all(np.isfinite(res.params)) + + +@pytest.mark.parametrize("cov_type", ["unadjusted", "robust", "kernel"]) +def test_famamacbeth_single_period_raises_value_error(cov_type): + y, x = single_period(const=True) + with pytest.warns(InferenceUnavailableWarning): + mod = FamaMacBeth(y, x) + with pytest.raises(ValueError, match=NO_DF) as exc_info: + mod.fit(cov_type=cov_type) + assert exc_info.type is ValueError + + +def test_famamacbeth_single_period_zero_bandwidth_raises_value_error(): + y, x = make_panel(8, 1, 1) + mod = FamaMacBeth(y, x) + with pytest.raises(ValueError, match=NO_DF): + mod.fit() + with pytest.raises(ValueError, match=NO_DF): + mod.fit(cov_type="kernel", bandwidth=0) + + +def test_famamacbeth_dropped_to_single_period_raises_value_error(): + y, x = make_panel(8, 2, 1) + x.insert(0, "const", 1.0) + period = x.index.get_level_values(1) + x.loc[period == 1, "x0"] = 1.5 + with pytest.warns(InferenceUnavailableWarning): + mod = FamaMacBeth(y, x) + with pytest.raises(ValueError, match=NO_DF): + mod.fit() + + +def test_famamacbeth_single_period_not_debiased(): + y, x = single_period(const=True) + with pytest.warns(InferenceUnavailableWarning): + mod = FamaMacBeth(y, x) + res = mod.fit(debiased=False) + assert np.all(np.isfinite(res.params)) + np.testing.assert_allclose(res.cov, 0.0) + assert res.df_resid == 0 + assert isinstance(res.f_statistic_robust, InvalidTestStatistic) + assert str(res.summary) + + res_bw0 = mod.fit(cov_type="kernel", bandwidth=0, debiased=False) + np.testing.assert_allclose(res_bw0.cov, 0.0) + + +def test_famamacbeth_covariance_requires_residual_df(): + all_params = pd.DataFrame([[1.0, 2.0]], columns=["const", "x0"]) + params = all_params.mean(axis=0).to_numpy()[:, None] + y, x = np.zeros((8, 1)), np.ones((8, 2)) + with pytest.raises(ValueError, match=NO_DF): + FamaMacBethCovariance(y, x, params, all_params, debiased=True) + with pytest.raises(ValueError, match=NO_DF): + FamaMacBethCovariance(y, x, params, all_params, debiased=True, bandwidth=0) + cov = FamaMacBethCovariance(y, x, params, all_params, debiased=False, bandwidth=0) + np.testing.assert_allclose(cov.cov, 0.0)