|
| 1 | +""" |
| 2 | +The degrees of freedom of the clustered covariance of PanelOLS with one effect |
| 3 | +
|
| 4 | +The covariance does not count the degrees of freedom of an effect that is nested in |
| 5 | +the clusters, since an effect with the same groups as a cluster (e.g., entity effects |
| 6 | +and clustering by entity) is purged from the scores of the cluster. With several |
| 7 | +cluster variables, e.g., two-way clustering, the effect has to be nested in all of them, |
| 8 | +as in AbsorbingLS. It was nested if it was in the last cluster variable only, so that |
| 9 | +the standard errors changed with the order of the cluster variables. |
| 10 | +
|
| 11 | +The reference is the covariance of the regression on the data from which the effect is |
| 12 | +removed, written out in NumPy. |
| 13 | +""" |
| 14 | + |
| 15 | +import numpy as np |
| 16 | +from numpy.testing import assert_allclose |
| 17 | +import pandas as pd |
| 18 | +import pytest |
| 19 | + |
| 20 | +from linearmodels.panel import PanelOLS |
| 21 | + |
| 22 | + |
| 23 | +def make_data(unbalanced, seed=3, nentity=30, nperiod=8): |
| 24 | + """A panel with entities that are nested in industries""" |
| 25 | + rg = np.random.default_rng(seed) |
| 26 | + index = pd.MultiIndex.from_product( |
| 27 | + [np.arange(nentity), np.arange(nperiod)], names=["id", "year"] |
| 28 | + ) |
| 29 | + entity, period = index.codes |
| 30 | + x = rg.standard_normal((index.shape[0], 2)) |
| 31 | + effect = rg.standard_normal(nentity)[entity] |
| 32 | + shock = (1 + np.abs(x[:, 0])) * rg.standard_normal(index.shape[0]) |
| 33 | + data = pd.DataFrame( |
| 34 | + { |
| 35 | + "y": x @ [0.5, -0.3] + effect + shock, |
| 36 | + "x1": x[:, 0], |
| 37 | + "x2": x[:, 1], |
| 38 | + "entity": entity, |
| 39 | + "time": period, |
| 40 | + "industry": entity // 5, |
| 41 | + "group": (entity + period) % 4, |
| 42 | + }, |
| 43 | + index=index, |
| 44 | + ) |
| 45 | + if unbalanced: |
| 46 | + keep = rg.random((nentity, nperiod)) > 0.3 |
| 47 | + for i in range(nentity): |
| 48 | + keep[i, rg.choice(nperiod, 3, replace=False)] = True |
| 49 | + data = data.loc[keep.ravel()] |
| 50 | + return data |
| 51 | + |
| 52 | + |
| 53 | +@pytest.fixture(params=[False, True], ids=["balanced", "unbalanced"], scope="module") |
| 54 | +def data(request): |
| 55 | + return make_data(request.param) |
| 56 | + |
| 57 | + |
| 58 | +EFFECTS = { |
| 59 | + "entity": {"entity_effects": True}, |
| 60 | + "time": {"time_effects": True}, |
| 61 | + "group": {"other_effects": ("group",)}, |
| 62 | +} |
| 63 | +PAIRS = [ |
| 64 | + ("entity", "time"), |
| 65 | + ("industry", "time"), |
| 66 | + ("industry", "entity"), |
| 67 | + ("group", "time"), |
| 68 | + ("entity", "group"), |
| 69 | +] |
| 70 | + |
| 71 | + |
| 72 | +def build(data, effect): |
| 73 | + options = dict(EFFECTS[effect]) |
| 74 | + if "other_effects" in options: |
| 75 | + options["other_effects"] = data[list(options["other_effects"])] |
| 76 | + return PanelOLS(data["y"], data[["x1", "x2"]], **options) |
| 77 | + |
| 78 | + |
| 79 | +def sum_of_scores(scores, groups): |
| 80 | + total = 0.0 |
| 81 | + for key in np.unique(groups): |
| 82 | + score = scores[groups == key].sum(0) |
| 83 | + total = total + np.outer(score, score) |
| 84 | + return total |
| 85 | + |
| 86 | + |
| 87 | +def clustered_covariance(data, effect, clusters, count_effects): |
| 88 | + """Debiased covariance of the regression on the data without the effect""" |
| 89 | + groups = data[effect].to_numpy() |
| 90 | + x = data[["x1", "x2"]] - data[["x1", "x2"]].groupby(groups).transform("mean") |
| 91 | + y = data["y"] - data["y"].groupby(groups).transform("mean") |
| 92 | + x, y = x.to_numpy(), y.to_numpy() |
| 93 | + resid = y - x @ np.linalg.lstsq(x, y, rcond=None)[0] |
| 94 | + scores = x * resid[:, None] |
| 95 | + labels = [data[c].to_numpy() for c in clusters] |
| 96 | + meat = sum_of_scores(scores, labels[0]) |
| 97 | + if len(labels) == 2: |
| 98 | + pairs = pd.factorize(pd.Series(list(zip(*labels, strict=True))))[0] |
| 99 | + meat = meat + sum_of_scores(scores, labels[1]) - sum_of_scores(scores, pairs) |
| 100 | + nobs, nvar = x.shape |
| 101 | + neffects = np.unique(groups).shape[0] if count_effects else 0 |
| 102 | + bread = np.linalg.inv(x.T @ x) |
| 103 | + return bread @ meat @ bread * nobs / (nobs - neffects - nvar) |
| 104 | + |
| 105 | + |
| 106 | +def is_nested(data, effect, clusters): |
| 107 | + """The groups of the effect are in a single group of every cluster variable""" |
| 108 | + by_effect = data.groupby(effect) |
| 109 | + return all(by_effect[c].nunique().max() == 1 for c in clusters) |
| 110 | + |
| 111 | + |
| 112 | +@pytest.mark.parametrize("pair", PAIRS) |
| 113 | +@pytest.mark.parametrize("effect", list(EFFECTS)) |
| 114 | +def test_clustered_covariance_against_hand_computation(data, effect, pair): |
| 115 | + mod = build(data, effect) |
| 116 | + expected = {} |
| 117 | + for clusters in (list(pair), list(reversed(pair))): |
| 118 | + res = mod.fit(cov_type="clustered", clusters=data[clusters]) |
| 119 | + expected = clustered_covariance( |
| 120 | + data, effect, clusters, count_effects=not is_nested(data, effect, clusters) |
| 121 | + ) |
| 122 | + assert_allclose(res.cov.to_numpy(), expected, rtol=1e-8) |
| 123 | + |
| 124 | + |
| 125 | +@pytest.mark.parametrize("pair", PAIRS) |
| 126 | +@pytest.mark.parametrize("effect", list(EFFECTS)) |
| 127 | +def test_order_of_the_clusters_does_not_matter(data, effect, pair): |
| 128 | + mod = build(data, effect) |
| 129 | + forward = mod.fit(cov_type="clustered", clusters=data[list(pair)]) |
| 130 | + backward = mod.fit(cov_type="clustered", clusters=data[list(reversed(pair))]) |
| 131 | + assert_allclose(forward.cov, backward.cov) |
| 132 | + |
| 133 | + |
| 134 | +@pytest.mark.parametrize("effect", ["entity", "time"]) |
| 135 | +def test_cluster_entity_and_cluster_time(data, effect): |
| 136 | + # An effect that is nested in the clusters by entity or by time only is counted |
| 137 | + mod = build(data, effect) |
| 138 | + res = mod.fit(cov_type="clustered", cluster_entity=True, cluster_time=True) |
| 139 | + expected = clustered_covariance( |
| 140 | + data, effect, ["entity", "time"], count_effects=True |
| 141 | + ) |
| 142 | + assert_allclose(res.cov.to_numpy(), expected, rtol=1e-8) |
| 143 | + one_way = mod.fit( |
| 144 | + cov_type="clustered", |
| 145 | + cluster_entity=effect == "entity", |
| 146 | + cluster_time=effect == "time", |
| 147 | + ) |
| 148 | + expected = clustered_covariance(data, effect, [effect], count_effects=False) |
| 149 | + assert_allclose(one_way.cov.to_numpy(), expected, rtol=1e-8) |
| 150 | + |
| 151 | + |
| 152 | +def test_nested_in_all_clusters_does_not_count_the_effects(data): |
| 153 | + # Entities are nested in industries: both cluster variables nest the entity effects |
| 154 | + mod = build(data, "entity") |
| 155 | + res = mod.fit(cov_type="clustered", clusters=data[["industry", "entity"]]) |
| 156 | + counted = mod.fit( |
| 157 | + cov_type="clustered", |
| 158 | + clusters=data[["industry", "entity"]], |
| 159 | + auto_df=False, |
| 160 | + count_effects=True, |
| 161 | + ) |
| 162 | + not_counted = mod.fit( |
| 163 | + cov_type="clustered", |
| 164 | + clusters=data[["industry", "entity"]], |
| 165 | + auto_df=False, |
| 166 | + count_effects=False, |
| 167 | + ) |
| 168 | + assert_allclose(res.cov, not_counted.cov) |
| 169 | + assert not np.allclose(res.cov, counted.cov) |
0 commit comments