diff --git a/linearmodels/panel/model.py b/linearmodels/panel/model.py index 5c9111d880..cad6c0bedd 100644 --- a/linearmodels/panel/model.py +++ b/linearmodels/panel/model.py @@ -4907,7 +4907,9 @@ def fit( with the others in the means of the entities (the year dummies and the constant in a balanced panel) is not in the between regression. A ``ValueError`` is raised if either regression has no residual degrees of - freedom, since the variances cannot be estimated. + freedom, since the variances cannot be estimated. If both estimated + variances are zero, the fit is pooled least squares, with theta and the + reported share of variance due to effects both set to zero. .. versionchanged:: 7.1 @@ -5048,9 +5050,14 @@ def fit( else: t_bar = neffects / ((1.0 / t).sum()) sigma2_u = max(0, ssr / df_between - sigma2_e / t_bar) - rho = sigma2_u / (sigma2_u + sigma2_e) - - theta = 1.0 - np.sqrt(sigma2_e / (t * sigma2_u + sigma2_e)) + if sigma2_u == 0 and sigma2_e == 0: + # With no variation in the errors, use pooled least squares. This also + # follows the PanelOLS convention for the share of a zero variance. + rho = 0.0 + theta = np.zeros_like(t, dtype=float) + else: + rho = sigma2_u / (sigma2_u + sigma2_e) + theta = 1.0 - np.sqrt(sigma2_e / (t * sigma2_u + sigma2_e)) theta_out = DataFrame(theta, columns=["theta"], index=wybar.index) wy: linearmodels.typing.data.Float64Array = np.asarray( root_w * self.dependent.values2d, dtype=float diff --git a/linearmodels/tests/test_rsquared_zero_tss.py b/linearmodels/tests/test_rsquared_zero_tss.py index b183a1d57a..0100c42361 100644 --- a/linearmodels/tests/test_rsquared_zero_tss.py +++ b/linearmodels/tests/test_rsquared_zero_tss.py @@ -126,6 +126,21 @@ def test_constant_dependent_variable_panel(name, value): assert_summary_has(res, "R-squared") +@pytest.mark.parametrize("small_sample", [False, True]) +def test_random_effects_zero_variance_components(small_sample): + _, _, xc = panel_data() + xc = xc.iloc[:-1] + y = pd.Series(0.0, index=xc.index) + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = RandomEffects(y, xc).fit(small_sample=small_sample) + assert_nan(res, PANEL_MEASURES) + assert_allclose(res.params, 0.0) + assert_allclose(res.cov, 0.0) + assert_allclose(res.theta, 0.0) + assert_allclose(res.variance_decomposition, 0.0) + + @pytest.mark.parametrize("name", PANEL_WITH_CONSTANT) def test_constant_dependent_variable_weighted_and_unbalanced_panel(name): index, _, xc = panel_data(seed=1)