Repository Public Research preview
1"""Small, dependency-light panel estimator used throughout the paper.23Two-way fixed effects by alternating projections; cluster-robust covariance by unit, by time,4two-way (Cameron, Gelbach and Miller 2011) and Driscoll-Kraay; randomisation inference that5permutes a unit-level characteristic across units.6"""7import numpy as np8import pandas as pd91011def _codes(x):12 return pd.factorize(x)[0]131415def demean2(M: np.ndarray, gi: np.ndarray, gt: np.ndarray, tol=1e-10, maxit=500) -> np.ndarray:16 """Remove unit and time fixed effects from each column of M (unbalanced panels)."""17 M = M.astype(float).copy()18 ni, nt = np.bincount(gi), np.bincount(gt)19 for _ in range(maxit):20 delta = 0.021 for g, n in ((gi, ni), (gt, nt)):22 for j in range(M.shape[1]):23 mu = np.bincount(g, weights=M[:, j], minlength=len(n)) / n24 delta = max(delta, np.abs(mu).max())25 M[:, j] -= mu[g]26 if delta < tol:27 break28 return M293031def _meat(Xe: np.ndarray, g: np.ndarray) -> np.ndarray:32 S = np.zeros((g.max() + 1, Xe.shape[1]))33 np.add.at(S, g, Xe)34 return S.T @ S353637def _dk_meat(Xe, gt, L):38 T = gt.max() + 139 h = np.zeros((T, Xe.shape[1]))40 np.add.at(h, gt, Xe)41 S = h.T @ h42 for l in range(1, L + 1):43 G = h[l:].T @ h[:-l]44 S += (1 - l / (L + 1)) * (G + G.T)45 return S464748class Fit:49 def __init__(self, names, b, V, n, ni, nt, r2w, resid, extra):50 self.names, self.b, self.V, self.n, self.ni, self.nt, self.r2w = names, b, V, n, ni, nt, r2w51 self.resid, self.extra = resid, extra5253 def se(self, kind="twoway"):54 return np.sqrt(np.diag(self.V[kind]))5556 def t(self, kind="twoway"):57 return self.b / self.se(kind)5859 def table(self, kind="twoway"):60 return pd.DataFrame({"b": self.b, "se": self.se(kind), "t": self.t(kind)}, index=self.names)616263def fe_ols(df: pd.DataFrame, y: str, X: list, unit="ccy", time="date", fe=("unit", "time"), dk_lags=None) -> Fit:64 d = df[[y, unit, time] + X].dropna()65 gi, gt = _codes(d[unit]), (d[time].rank(method="dense").astype(int) - 1).values # chronological codes66 M = d[[y] + X].values.astype(float)67 if fe == ("unit", "time"):68 M = demean2(M, gi, gt)69 elif fe == ("unit",):70 for j in range(M.shape[1]):71 M[:, j] -= (np.bincount(gi, weights=M[:, j]) / np.bincount(gi))[gi]72 elif fe == ("time",):73 for j in range(M.shape[1]):74 M[:, j] -= (np.bincount(gt, weights=M[:, j]) / np.bincount(gt))[gt]75 yy, XX = M[:, 0], M[:, 1:]76 XtXi = np.linalg.pinv(XX.T @ XX)77 b = XtXi @ XX.T @ yy78 e = yy - XX @ b79 Xe = XX * e[:, None]80 n, k = XX.shape81 Ni, Nt = gi.max() + 1, gt.max() + 182 ci, ct = Ni / (Ni - 1), Nt / (Nt - 1)83 Vi = XtXi @ (ci * _meat(Xe, gi)) @ XtXi84 Vt = XtXi @ (ct * _meat(Xe, gt)) @ XtXi85 Vw = XtXi @ (Xe.T @ Xe) @ XtXi86 V2 = Vi + Vt - Vw87 # The two-way estimator Vi + Vt - Vw is not guaranteed PSD and can be far too small when one88 # dimension has few clusters. We use the conservative variant: element-wise maximum of the89 # two-way and both one-way variances on the diagonal (off-diagonals from the two-way matrix).90 dmax = np.maximum.reduce([np.diag(V2), np.diag(Vi), np.diag(Vt)])91 V2 = V2.copy()92 V2[np.diag_indices_from(V2)] = dmax93 L = dk_lags if dk_lags is not None else int(np.floor(4 * (Nt / 100) ** (2 / 9)))94 Vdk = XtXi @ _dk_meat(Xe, gt, L) @ XtXi95 r2 = 1 - (e @ e) / (yy @ yy)96 return Fit(X, b, {"twoway": V2, "unit": Vi, "time": Vt, "dk": Vdk, "white": Vw}, n, Ni, Nt, r2, e,97 {"index": d.index})9899100def randomisation_p(df, y, X, char_cols, unit="ccy", time="date", target=0, reps=999, seed=0, **kw):101 """Permute the unit-level characteristic(s) across units, rebuilding every interaction.102103 char_cols: dict {interaction column -> (time-series column, unit characteristic column)}.104 Returns the two-sided permutation p-value for coefficient `target` (based on the t-statistic105 with two-way clustering, which is the better-behaved pivot).106 """107 rng = np.random.default_rng(seed)108 base = fe_ols(df, y, X, unit, time, **kw)109 t0 = base.t()[target]110 units = df[unit].unique()111 chars = {c for _, c in char_cols.values()}112 umap = df.groupby(unit)[list(chars)].first()113 ts = np.empty(reps)114 d = df.copy()115 for r in range(reps):116 perm = pd.DataFrame(umap.values[rng.permutation(len(units))], index=umap.index, columns=umap.columns)117 for inter, (tcol, ccol) in char_cols.items():118 d[inter] = d[tcol].values * d[unit].map(perm[ccol]).values119 ts[r] = fe_ols(d, y, X, unit, time, **kw).t()[target]120 return (1 + np.sum(np.abs(ts) >= abs(t0))) / (reps + 1), ts121122123def stars(t):124 a = abs(t)125 return "***" if a > 2.576 else "**" if a > 1.96 else "*" if a > 1.645 else ""126