trustframe 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trustframe/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """trustframe: trustworthy data analysis.
2
+
3
+ Modules map to the gaps that dataframe libraries leave open:
4
+
5
+ * :mod:`trustframe.trace` - catch silent pandas bugs (fan-out joins, lossy dropna, empty filters)
6
+ * :mod:`trustframe.quality` - find leakage, placeholders, unit changes and hidden duplicates
7
+ * :mod:`trustframe.explain` - explain why a metric changed (root-cause / contribution analysis)
8
+ * :mod:`trustframe.causal` - causal effects with assumptions and robustness checks attached
9
+ * :mod:`trustframe.parity` - check results agree across pandas, Polars, DuckDB, ...
10
+ * :mod:`trustframe.uncertainty` - intervals, LLM-label inference (PPI), conformal sets, sample sizes
11
+ * :mod:`trustframe.report` - reports whose numbers are computed and verified
12
+ """
13
+ from .causal import CausalEstimate, DiDResult, PlaceboResult, diff_in_diff, e_value, estimate_effect, placebo_test
14
+ from .explain import ChangeExplanation, explain_change
15
+ from .parity import ParityReport, ParityResults, check_parity, compare, sql, to_pandas
16
+ from .quality import Issue, QualityReport, scan
17
+ from .report import Fact, Report, UnknownFactError, VerificationResult, lint_chart, verify_text
18
+ from .trace import AuditLog, JoinCheck, Thresholds, TrustError, TrustWarning, audit, audited, check_join
19
+ from .uncertainty import (
20
+ Interval,
21
+ bootstrap_ci,
22
+ cohen_kappa,
23
+ conformal_classification,
24
+ conformal_regression,
25
+ fleiss_kappa,
26
+ labeler_report,
27
+ mean_ci,
28
+ metric_ci,
29
+ minimum_detectable_effect,
30
+ ppi_mean,
31
+ proportion_ci,
32
+ sample_size_ab,
33
+ sample_size_mean,
34
+ sample_size_proportion,
35
+ )
36
+
37
+ __version__ = "0.1.0"
38
+
39
+ __all__ = [
40
+ "audit", "audited", "check_join", "AuditLog", "JoinCheck", "Thresholds", "TrustWarning", "TrustError",
41
+ "scan", "QualityReport", "Issue",
42
+ "explain_change", "ChangeExplanation",
43
+ "estimate_effect", "diff_in_diff", "placebo_test", "e_value", "CausalEstimate", "DiDResult", "PlaceboResult",
44
+ "compare", "check_parity", "sql", "to_pandas", "ParityReport", "ParityResults",
45
+ "Interval", "bootstrap_ci", "mean_ci", "proportion_ci", "metric_ci", "ppi_mean", "cohen_kappa", "fleiss_kappa",
46
+ "labeler_report", "conformal_regression", "conformal_classification", "sample_size_proportion",
47
+ "sample_size_mean", "sample_size_ab", "minimum_detectable_effect",
48
+ "Report", "Fact", "verify_text", "VerificationResult", "lint_chart", "UnknownFactError",
49
+ "__version__",
50
+ ]
trustframe/_util.py ADDED
@@ -0,0 +1,90 @@
1
+ """Small numeric and formatting helpers shared across trustframe (no SciPy needed)."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from statistics import NormalDist
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ _NORMAL = NormalDist()
11
+
12
+
13
+ def z_value(confidence: float) -> float:
14
+ """Two-sided critical value of the standard normal for a confidence level."""
15
+ if not 0 < confidence < 1:
16
+ raise ValueError("confidence must be between 0 and 1")
17
+ return _NORMAL.inv_cdf(0.5 + confidence / 2)
18
+
19
+
20
+ def t_value(confidence: float, df: float) -> float:
21
+ """Two-sided critical value of Student's t; falls back to the normal without SciPy."""
22
+ try:
23
+ from scipy import stats # type: ignore
24
+
25
+ return float(stats.t.ppf(0.5 + confidence / 2, df))
26
+ except Exception: # pragma: no cover - SciPy is optional
27
+ return z_value(confidence)
28
+
29
+
30
+ def p_two_sided(z: float) -> float:
31
+ if not math.isfinite(z):
32
+ return 0.0 if abs(z) == math.inf else float("nan")
33
+ return 2 * (1 - _NORMAL.cdf(abs(z)))
34
+
35
+
36
+ def auc_score(scores, y01) -> float:
37
+ """Rank-based ROC AUC (Mann-Whitney), ties averaged. Returns nan if one class is absent."""
38
+ s = pd.Series(np.asarray(scores, dtype=float))
39
+ y = np.asarray(y01).astype(bool)
40
+ n1 = int(y.sum())
41
+ n0 = len(y) - n1
42
+ if n1 == 0 or n0 == 0:
43
+ return float("nan")
44
+ ranks = s.rank(method="average").to_numpy()
45
+ return float((ranks[y].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))
46
+
47
+
48
+ def spearman(x, y) -> float:
49
+ rx = pd.Series(np.asarray(x, dtype=float)).rank().to_numpy()
50
+ ry = pd.Series(np.asarray(y, dtype=float)).rank().to_numpy()
51
+ if rx.std() == 0 or ry.std() == 0:
52
+ return float("nan")
53
+ return float(np.corrcoef(rx, ry)[0, 1])
54
+
55
+
56
+ def fmt_num(x, digits: int = 3, signed: bool = False) -> str:
57
+ """Human-friendly number: 1234567 -> '1.23M', 0.012345 -> '0.0123'."""
58
+ try:
59
+ x = float(x)
60
+ except (TypeError, ValueError):
61
+ return str(x)
62
+ if math.isnan(x):
63
+ return "nan"
64
+ if math.isinf(x):
65
+ return ("+" if signed and x > 0 else "") + ("inf" if x > 0 else "-inf")
66
+ sign = "+" if signed and x > 0 else ""
67
+ ax = abs(x)
68
+ for limit, suffix in ((1e12, "T"), (1e9, "B"), (1e6, "M"), (1e3, "k")):
69
+ if ax >= limit:
70
+ return f"{sign}{x / limit:.{digits}g}{suffix}"
71
+ if x == int(x):
72
+ return f"{sign}{int(x):,}"
73
+ return f"{sign}{x:.{max(digits, len(str(int(ax))))}g}"
74
+
75
+
76
+ def fmt_pct(x, digits: int = 1, signed: bool = False) -> str:
77
+ try:
78
+ x = float(x)
79
+ except (TypeError, ValueError):
80
+ return str(x)
81
+ if math.isnan(x):
82
+ return "nan"
83
+ return f"{x * 100:{'+' if signed else ''}.{digits}f}%"
84
+
85
+
86
+ def fmt_p(p: float) -> str:
87
+ """p-value for display: 'p<0.001' instead of 'p=0'."""
88
+ if p != p:
89
+ return "p=nan"
90
+ return "p<0.001" if p < 0.001 else f"p={p:.3g}"
trustframe/causal.py ADDED
@@ -0,0 +1,517 @@
1
+ """Causal effect estimates with their assumptions and robustness checks attached.
2
+
3
+ Most business questions are causal ("did the campaign *cause* more purchases?").
4
+ This module gives you a guarded path from data to an answer:
5
+
6
+ * :func:`estimate_effect` - effect of a binary treatment adjusting for confounders,
7
+ with four estimators side by side (naive, regression, IPW, doubly robust),
8
+ covariate balance, overlap diagnostics and an E-value for sensitivity.
9
+ * :func:`diff_in_diff` - difference-in-differences for a before/after change
10
+ that hit one group, with an optional parallel-trends pre-test.
11
+ * :func:`placebo_test` - shuffle the treatment and check the effect disappears.
12
+
13
+ Every result's ``summary()`` states the assumptions in plain language.
14
+ Only NumPy and pandas are needed.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from dataclasses import dataclass, field
20
+ from typing import Optional, Sequence
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ from ._util import fmt_num, fmt_p, p_two_sided, z_value
26
+
27
+ __all__ = [
28
+ "estimate_effect",
29
+ "diff_in_diff",
30
+ "placebo_test",
31
+ "CausalEstimate",
32
+ "DiDResult",
33
+ "PlaceboResult",
34
+ "e_value",
35
+ ]
36
+
37
+
38
+ # --------------------------------------------------------------------------- linear algebra
39
+
40
+
41
+ def _ols(y: np.ndarray, X: np.ndarray, cluster: Optional[np.ndarray] = None):
42
+ """OLS with heteroskedasticity-robust (HC1) or cluster-robust standard errors."""
43
+ XtX_inv = np.linalg.pinv(X.T @ X)
44
+ beta = XtX_inv @ X.T @ y
45
+ e = y - X @ beta
46
+ n, k = X.shape
47
+ Xe = X * e[:, None]
48
+ if cluster is None:
49
+ meat = Xe.T @ Xe
50
+ adj = n / max(n - k, 1)
51
+ else:
52
+ codes = pd.factorize(cluster)[0]
53
+ G = int(codes.max()) + 1
54
+ S = np.zeros((G, k))
55
+ np.add.at(S, codes, Xe)
56
+ meat = S.T @ S
57
+ adj = (G / max(G - 1, 1)) * ((n - 1) / max(n - k, 1))
58
+ cov = adj * XtX_inv @ meat @ XtX_inv
59
+ return beta, np.sqrt(np.clip(np.diag(cov), 0, None))
60
+
61
+
62
+ def _logit_fit(Z: np.ndarray, t: np.ndarray, ridge: float = 1e-4, iters: int = 100) -> np.ndarray:
63
+ beta = np.zeros(Z.shape[1])
64
+ I = np.eye(Z.shape[1])
65
+ I[0, 0] = 0.0 # do not penalize the intercept
66
+ for _ in range(iters):
67
+ p = 1 / (1 + np.exp(-np.clip(Z @ beta, -30, 30)))
68
+ W = p * (1 - p)
69
+ H = Z.T @ (Z * W[:, None]) + ridge * len(t) * I
70
+ g = Z.T @ (t - p) - ridge * len(t) * (I @ beta)
71
+ try:
72
+ step = np.linalg.solve(H, g)
73
+ except np.linalg.LinAlgError:
74
+ step = np.linalg.pinv(H) @ g
75
+ beta += step
76
+ if np.max(np.abs(step)) < 1e-8:
77
+ break
78
+ return 1 / (1 + np.exp(-np.clip(Z @ beta, -30, 30)))
79
+
80
+
81
+ def _binary(s: pd.Series, name: str) -> np.ndarray:
82
+ vals = pd.unique(s.dropna())
83
+ if pd.api.types.is_bool_dtype(s):
84
+ return s.to_numpy(dtype=float)
85
+ if len(vals) != 2:
86
+ raise ValueError(f"{name!r} must have exactly two values, found {len(vals)}")
87
+ if set(vals) <= {0, 1}:
88
+ return s.to_numpy(dtype=float)
89
+ hi = sorted(vals, key=str)[1]
90
+ return (s == hi).to_numpy(dtype=float)
91
+
92
+
93
+ def _design(df: pd.DataFrame, cols: Sequence[str]) -> pd.DataFrame:
94
+ if not cols:
95
+ return pd.DataFrame(index=df.index)
96
+ X = pd.get_dummies(df[list(cols)], drop_first=True, dtype=float).astype(float)
97
+ return X.loc[:, X.std(ddof=0) > 0]
98
+
99
+
100
+ def _standardize(X: np.ndarray) -> np.ndarray:
101
+ if X.shape[1] == 0:
102
+ return X
103
+ sd = X.std(axis=0)
104
+ sd[sd == 0] = 1
105
+ return (X - X.mean(axis=0)) / sd
106
+
107
+
108
+ def e_value(estimate: float, outcome_sd: float, ci: Optional[tuple] = None) -> tuple[float, float]:
109
+ """VanderWeele-Ding E-value for a difference in means, via the standardized-effect approximation.
110
+
111
+ Returns ``(e_point, e_ci)``: how strongly (as a risk ratio) an unmeasured confounder
112
+ would need to be tied to both treatment and outcome to explain away the estimate
113
+ (or move the confidence interval to include zero).
114
+ """
115
+
116
+ def ev(d):
117
+ rr = math.exp(0.91 * abs(d))
118
+ return rr + math.sqrt(rr * (rr - 1))
119
+
120
+ if not outcome_sd or not math.isfinite(outcome_sd):
121
+ return float("nan"), float("nan")
122
+ point = ev(estimate / outcome_sd)
123
+ if ci is None:
124
+ return point, float("nan")
125
+ lo, hi = ci
126
+ if lo <= 0 <= hi:
127
+ return point, 1.0
128
+ return point, ev(min(abs(lo), abs(hi)) / outcome_sd)
129
+
130
+
131
+ # --------------------------------------------------------------------------- estimate_effect
132
+
133
+
134
+ @dataclass
135
+ class CausalEstimate:
136
+ treatment: str
137
+ outcome: str
138
+ confounders: list
139
+ estimate: float
140
+ se: float
141
+ ci: tuple
142
+ p_value: float
143
+ method: str
144
+ n: int
145
+ n_treated: int
146
+ estimates: pd.DataFrame
147
+ balance: pd.DataFrame
148
+ e_value: float
149
+ e_value_ci: float
150
+ confidence: float = 0.95
151
+ warnings: list = field(default_factory=list)
152
+ assumptions: list = field(default_factory=list)
153
+
154
+ def summary(self) -> str:
155
+ lo, hi = self.ci
156
+ lines = [
157
+ f"Effect of {self.treatment!r} on {self.outcome!r}: {fmt_num(self.estimate, signed=True)} "
158
+ f"({self.confidence:.0%} CI {fmt_num(lo)} to {fmt_num(hi)}, {fmt_p(self.p_value)}; {self.method}, "
159
+ f"n={self.n:,}, treated={self.n_treated:,})",
160
+ ]
161
+ naive = self.estimates.set_index("method").loc["naive difference", "estimate"]
162
+ if self.confounders:
163
+ lines.append(
164
+ f"Without adjustment the difference is {fmt_num(naive, signed=True)}; adjusting for "
165
+ f"{len(self.confounders)} confounder(s) moves it to {fmt_num(self.estimate, signed=True)}."
166
+ )
167
+ lines.append("Estimators:")
168
+ for _, r in self.estimates.iterrows():
169
+ lines.append(f" {r['method']:<22} {fmt_num(r['estimate'], signed=True):>10} [{fmt_num(r['ci_low'])}, {fmt_num(r['ci_high'])}]")
170
+ if math.isfinite(self.e_value):
171
+ lines.append(
172
+ f"Sensitivity: an unmeasured confounder would need a risk-ratio association of {self.e_value:.2f} with both "
173
+ f"treatment and outcome to explain the estimate away ({self.e_value_ci:.2f} to make the CI include 0)."
174
+ )
175
+ if self.warnings:
176
+ lines.append("Warnings:")
177
+ lines += [f" ! {w}" for w in self.warnings]
178
+ lines.append("This is causal only if:")
179
+ lines += [f" - {a}" for a in self.assumptions]
180
+ return "\n".join(lines)
181
+
182
+ __str__ = summary
183
+
184
+
185
+ def _row(method, est, se, z):
186
+ return {
187
+ "method": method,
188
+ "estimate": est,
189
+ "se": se,
190
+ "ci_low": est - z * se,
191
+ "ci_high": est + z * se,
192
+ "p_value": p_two_sided(est / se) if se > 0 else float("nan"),
193
+ }
194
+
195
+
196
+ def _smd(x: np.ndarray, t: np.ndarray, w: Optional[np.ndarray] = None) -> float:
197
+ w = np.ones_like(x) if w is None else w
198
+ m1 = np.average(x[t == 1], weights=w[t == 1])
199
+ m0 = np.average(x[t == 0], weights=w[t == 0])
200
+ v1 = np.average((x[t == 1] - m1) ** 2, weights=w[t == 1])
201
+ v0 = np.average((x[t == 0] - m0) ** 2, weights=w[t == 0])
202
+ sd = math.sqrt((v1 + v0) / 2)
203
+ return (m1 - m0) / sd if sd > 0 else 0.0
204
+
205
+
206
+ def estimate_effect(
207
+ df: pd.DataFrame,
208
+ treatment: str,
209
+ outcome: str,
210
+ confounders: Sequence[str] = (),
211
+ *,
212
+ confidence: float = 0.95,
213
+ trim: float = 0.01,
214
+ ) -> CausalEstimate:
215
+ """Average effect of a binary ``treatment`` on ``outcome``, adjusting for ``confounders``.
216
+
217
+ Reports a doubly robust (AIPW) estimate as the headline, alongside the naive
218
+ difference, regression adjustment and inverse-propensity weighting so you can
219
+ see whether they agree. Categorical confounders are one-hot encoded; rows with
220
+ missing values in any used column are dropped (and counted in the warnings).
221
+ """
222
+ confounders = list(confounders)
223
+ cols = [treatment, outcome, *confounders]
224
+ missing = [c for c in cols if c not in df.columns]
225
+ if missing:
226
+ raise KeyError(f"columns not found: {missing}")
227
+ data = df[cols].dropna()
228
+ dropped = len(df) - len(data)
229
+ t = _binary(data[treatment], treatment)
230
+ y = data[outcome].to_numpy(dtype=float)
231
+ n, n1 = len(y), int(t.sum())
232
+ if n1 < 2 or n - n1 < 2:
233
+ raise ValueError("need at least two treated and two untreated rows")
234
+ Xc_df = _design(data, confounders)
235
+ Xc = Xc_df.to_numpy(dtype=float)
236
+ z = z_value(confidence)
237
+ ones = np.ones((n, 1))
238
+ warns = []
239
+ if dropped:
240
+ warns.append(f"{dropped:,} rows dropped for missing values in {cols}")
241
+
242
+ # naive
243
+ y1, y0 = y[t == 1], y[t == 0]
244
+ naive = y1.mean() - y0.mean()
245
+ naive_se = math.sqrt(y1.var(ddof=1) / len(y1) + y0.var(ddof=1) / len(y0))
246
+ rows = [_row("naive difference", naive, naive_se, z)]
247
+
248
+ # regression adjustment
249
+ beta, se = _ols(y, np.column_stack([ones, t, Xc]))
250
+ rows.append(_row("regression adjustment", beta[1], se[1], z))
251
+
252
+ # propensity scores
253
+ Z = np.column_stack([ones, _standardize(Xc)])
254
+ e_raw = _logit_fit(Z, t) if Xc.shape[1] else np.full(n, t.mean())
255
+ e = np.clip(e_raw, trim, 1 - trim)
256
+
257
+ # IPW (Hajek) with influence-function SE (treats propensities as known: slightly conservative)
258
+ w1, w0 = t / e, (1 - t) / (1 - e)
259
+ m1, m0 = (w1 * y).sum() / w1.sum(), (w0 * y).sum() / w0.sum()
260
+ ipw = m1 - m0
261
+ psi_ipw = w1 * (y - m1) / w1.mean() - w0 * (y - m0) / w0.mean()
262
+ rows.append(_row("inverse propensity", ipw, psi_ipw.std(ddof=1) / math.sqrt(n), z))
263
+
264
+ # AIPW (doubly robust)
265
+ Xo = np.column_stack([ones, Xc])
266
+ b1, _ = _ols(y[t == 1], Xo[t == 1])
267
+ b0, _ = _ols(y[t == 0], Xo[t == 0])
268
+ mu1, mu0 = Xo @ b1, Xo @ b0
269
+ psi = mu1 - mu0 + t * (y - mu1) / e - (1 - t) * (y - mu0) / (1 - e)
270
+ aipw, aipw_se = psi.mean(), psi.std(ddof=1) / math.sqrt(n)
271
+ rows.append(_row("doubly robust (AIPW)", aipw, aipw_se, z))
272
+ est_df = pd.DataFrame(rows)
273
+
274
+ # balance
275
+ weights = t / e + (1 - t) / (1 - e)
276
+ bal = [
277
+ {"covariate": c, "smd_raw": _smd(Xc[:, j], t), "smd_weighted": _smd(Xc[:, j], t, weights)}
278
+ for j, c in enumerate(Xc_df.columns)
279
+ ]
280
+ bal_df = pd.DataFrame(bal, columns=["covariate", "smd_raw", "smd_weighted"])
281
+ bad = bal_df[bal_df["smd_weighted"].abs() > 0.1]
282
+ if len(bad):
283
+ warns.append(f"covariates still imbalanced after weighting (|SMD|>0.1): {list(bad['covariate'])[:6]}")
284
+
285
+ # overlap (common support): units whose propensity lies outside the other group's range have no comparable counterpart
286
+ if Xc.shape[1]:
287
+ lo = max(e_raw[t == 1].min(), e_raw[t == 0].min())
288
+ hi = min(e_raw[t == 1].max(), e_raw[t == 0].max())
289
+ if hi < lo:
290
+ warns.append("treated and untreated propensity ranges do not overlap at all; there is no comparable control for anyone")
291
+ else:
292
+ outside = float(((e_raw < lo) | (e_raw > hi)).mean())
293
+ if outside > 0.1:
294
+ warns.append(
295
+ f"{outside:.0%} of rows have a propensity outside the range shared by both groups (weak overlap); "
296
+ "estimates for them lean on extrapolation"
297
+ )
298
+ extreme_w = float(np.max(weights) / np.sum(weights))
299
+ if extreme_w > 0.05:
300
+ warns.append(f"one unit carries {extreme_w:.0%} of the total IPW weight; weighted estimates are fragile")
301
+
302
+ adj = est_df[est_df["method"] != "naive difference"]["estimate"].to_numpy()
303
+ if confounders and (np.ptp(adj) > 2 * aipw_se or len(set(np.sign(adj))) > 1):
304
+ warns.append("adjusted estimators disagree by more than 2 standard errors; model specification matters here")
305
+
306
+ ci = (aipw - z * aipw_se, aipw + z * aipw_se)
307
+ ev, ev_ci = e_value(aipw, float(y0.std(ddof=1)), ci)
308
+ assumptions = [
309
+ f"no unmeasured confounding: {confounders or 'nothing'} capture every common cause of {treatment!r} and {outcome!r}",
310
+ "confounders were measured before treatment and are not affected by it",
311
+ "overlap: every kind of unit could have received either treatment",
312
+ "one unit's treatment does not affect another unit's outcome (no interference)",
313
+ ]
314
+ return CausalEstimate(
315
+ treatment=treatment,
316
+ outcome=outcome,
317
+ confounders=confounders,
318
+ estimate=float(aipw),
319
+ se=float(aipw_se),
320
+ ci=(float(ci[0]), float(ci[1])),
321
+ p_value=p_two_sided(aipw / aipw_se) if aipw_se > 0 else float("nan"),
322
+ method="doubly robust (AIPW)",
323
+ n=n,
324
+ n_treated=n1,
325
+ estimates=est_df,
326
+ balance=bal_df,
327
+ e_value=ev,
328
+ e_value_ci=ev_ci,
329
+ confidence=confidence,
330
+ warnings=warns,
331
+ assumptions=assumptions,
332
+ )
333
+
334
+
335
+ # --------------------------------------------------------------------------- difference in differences
336
+
337
+
338
+ @dataclass
339
+ class DiDResult:
340
+ outcome: str
341
+ estimate: float
342
+ se: float
343
+ ci: tuple
344
+ p_value: float
345
+ means: pd.DataFrame
346
+ pretrend: Optional[dict]
347
+ n: int
348
+ confidence: float = 0.95
349
+ warnings: list = field(default_factory=list)
350
+ assumptions: list = field(default_factory=list)
351
+
352
+ def summary(self) -> str:
353
+ lo, hi = self.ci
354
+ lines = [
355
+ f"Difference-in-differences effect on {self.outcome!r}: {fmt_num(self.estimate, signed=True)} "
356
+ f"({self.confidence:.0%} CI {fmt_num(lo)} to {fmt_num(hi)}, {fmt_p(self.p_value)}, n={self.n:,})",
357
+ "Group means:",
358
+ ]
359
+ for idx, r in self.means.iterrows():
360
+ lines.append(f" {idx:<10} before {fmt_num(r['before']):>10} after {fmt_num(r['after']):>10} change {fmt_num(r['change'], signed=True):>10}")
361
+ if self.pretrend:
362
+ pt = self.pretrend
363
+ lines.append(
364
+ f"Pre-period trend difference (treated - control per time unit): {fmt_num(pt['slope_difference'], signed=True)} "
365
+ f"({fmt_p(pt['p_value'])})"
366
+ )
367
+ if self.warnings:
368
+ lines += [f" ! {w}" for w in self.warnings]
369
+ lines.append("This is causal only if:")
370
+ lines += [f" - {a}" for a in self.assumptions]
371
+ return "\n".join(lines)
372
+
373
+ __str__ = summary
374
+
375
+
376
+ def _numeric_time(s: pd.Series) -> np.ndarray:
377
+ if pd.api.types.is_datetime64_any_dtype(s):
378
+ return ((s - s.min()).dt.total_seconds() / 86400.0).to_numpy(dtype=float)
379
+ if pd.api.types.is_numeric_dtype(s):
380
+ return s.to_numpy(dtype=float)
381
+ order = {v: i for i, v in enumerate(sorted(pd.unique(s), key=str))}
382
+ return s.map(order).to_numpy(dtype=float)
383
+
384
+
385
+ def diff_in_diff(
386
+ df: pd.DataFrame,
387
+ outcome: str,
388
+ treated: str,
389
+ post: str,
390
+ *,
391
+ unit: Optional[str] = None,
392
+ time: Optional[str] = None,
393
+ covariates: Sequence[str] = (),
394
+ confidence: float = 0.95,
395
+ ) -> DiDResult:
396
+ """Difference-in-differences: ``(treated after - treated before) - (control after - control before)``.
397
+
398
+ ``treated`` and ``post`` are two-valued columns. Pass ``unit`` to cluster
399
+ standard errors by unit (recommended for panel data) and ``time`` to test
400
+ whether the groups were already trending apart before the change.
401
+ """
402
+ covariates = list(covariates)
403
+ cols = [outcome, treated, post, *covariates] + [c for c in (unit, time) if c]
404
+ missing = [c for c in cols if c not in df.columns]
405
+ if missing:
406
+ raise KeyError(f"columns not found: {missing}")
407
+ data = df[list(dict.fromkeys(cols))].dropna()
408
+ y = data[outcome].to_numpy(dtype=float)
409
+ g = _binary(data[treated], treated)
410
+ p = _binary(data[post], post)
411
+ Xc = _design(data, covariates).to_numpy(dtype=float)
412
+ X = np.column_stack([np.ones(len(y)), g, p, g * p, Xc])
413
+ cl = data[unit].to_numpy() if unit else None
414
+ beta, se = _ols(y, X, cl)
415
+ z = z_value(confidence)
416
+ est, s = float(beta[3]), float(se[3])
417
+ warns = []
418
+ cells = pd.DataFrame({"g": g, "p": p, "y": y}).groupby(["g", "p"])["y"].mean()
419
+ if len(cells) < 4:
420
+ raise ValueError("need rows in all four treated/post cells")
421
+ means = pd.DataFrame(
422
+ {"before": [cells[(1.0, 0.0)], cells[(0.0, 0.0)]], "after": [cells[(1.0, 1.0)], cells[(0.0, 1.0)]]},
423
+ index=["treated", "control"],
424
+ )
425
+ means["change"] = means["after"] - means["before"]
426
+
427
+ pretrend = None
428
+ if time:
429
+ pre = data[p == 0]
430
+ if pre[time].nunique() >= 3:
431
+ tn = _numeric_time(pre[time])
432
+ gp = _binary(pre[treated], treated)
433
+ Xp = np.column_stack([np.ones(len(tn)), gp, tn, gp * tn])
434
+ bp, sp = _ols(pre[outcome].to_numpy(dtype=float), Xp, pre[unit].to_numpy() if unit else None)
435
+ pv = p_two_sided(bp[3] / sp[3]) if sp[3] > 0 else float("nan")
436
+ pretrend = {"slope_difference": float(bp[3]), "se": float(sp[3]), "p_value": pv}
437
+ if pv < 0.05:
438
+ warns.append(
439
+ "groups were already trending apart before the change (p<0.05); the parallel-trends assumption looks doubtful"
440
+ )
441
+ else:
442
+ warns.append("need at least 3 pre-period time points to test parallel trends")
443
+ if unit is None:
444
+ warns.append("standard errors are not clustered; pass unit= for repeated observations of the same units")
445
+ return DiDResult(
446
+ outcome=outcome,
447
+ estimate=est,
448
+ se=s,
449
+ ci=(est - z * s, est + z * s),
450
+ p_value=p_two_sided(est / s) if s > 0 else float("nan"),
451
+ means=means,
452
+ pretrend=pretrend,
453
+ n=len(y),
454
+ confidence=confidence,
455
+ warnings=warns,
456
+ assumptions=[
457
+ "parallel trends: without the change, treated and control would have moved by the same amount",
458
+ "the change did not alter who is in each group (no composition shift)",
459
+ "nothing else that affects the outcome changed for only one group at the same time",
460
+ "the control group was not affected by the change (no spillover)",
461
+ ],
462
+ )
463
+
464
+
465
+ # --------------------------------------------------------------------------- placebo
466
+
467
+
468
+ @dataclass
469
+ class PlaceboResult:
470
+ actual: float
471
+ placebo_effects: np.ndarray
472
+ p_value: float
473
+
474
+ def summary(self) -> str:
475
+ q = np.quantile(np.abs(self.placebo_effects), 0.95)
476
+ verdict = (
477
+ "the real effect stands out from shuffled-treatment noise"
478
+ if self.p_value < 0.05
479
+ else "the real effect is NOT distinguishable from shuffled-treatment noise"
480
+ )
481
+ return (
482
+ f"Placebo test: actual effect {fmt_num(self.actual, signed=True)}; 95% of {len(self.placebo_effects)} placebo "
483
+ f"effects are within +/-{fmt_num(q)} (permutation {fmt_p(self.p_value)}); {verdict}."
484
+ )
485
+
486
+ __str__ = summary
487
+
488
+
489
+ def placebo_test(
490
+ df: pd.DataFrame,
491
+ treatment: str,
492
+ outcome: str,
493
+ confounders: Sequence[str] = (),
494
+ *,
495
+ n_permutations: int = 500,
496
+ seed: Optional[int] = 0,
497
+ ) -> PlaceboResult:
498
+ """Shuffle the treatment labels and re-estimate (regression adjustment) many times.
499
+
500
+ If the real effect is not larger than most placebo effects, the estimate may be noise.
501
+ """
502
+ confounders = list(confounders)
503
+ data = df[[treatment, outcome, *confounders]].dropna()
504
+ t = _binary(data[treatment], treatment)
505
+ y = data[outcome].to_numpy(dtype=float)
506
+ Xc = _design(data, confounders).to_numpy(dtype=float)
507
+ ones = np.ones((len(y), 1))
508
+
509
+ def coef(tt):
510
+ X = np.column_stack([ones, tt, Xc])
511
+ return float((np.linalg.pinv(X) @ y)[1])
512
+
513
+ actual = coef(t)
514
+ rng = np.random.default_rng(seed)
515
+ placebo = np.array([coef(rng.permutation(t)) for _ in range(n_permutations)])
516
+ p = (1 + np.sum(np.abs(placebo) >= abs(actual))) / (n_permutations + 1)
517
+ return PlaceboResult(actual, placebo, float(p))