factor-factory 1.0.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.
Files changed (134) hide show
  1. factor_factory/__init__.py +32 -0
  2. factor_factory/__main__.py +46 -0
  3. factor_factory/_version.py +1 -0
  4. factor_factory/diagnostics/__init__.py +13 -0
  5. factor_factory/diagnostics/assertions.py +49 -0
  6. factor_factory/diagnostics/balance.py +99 -0
  7. factor_factory/diagnostics/residuals.py +96 -0
  8. factor_factory/diagnostics/trends.py +80 -0
  9. factor_factory/engines/__init__.py +29 -0
  10. factor_factory/engines/_base.py +12 -0
  11. factor_factory/engines/_registry.py +37 -0
  12. factor_factory/engines/changepoint/__init__.py +64 -0
  13. factor_factory/engines/changepoint/_base.py +59 -0
  14. factor_factory/engines/changepoint/ruptures_adapter.py +78 -0
  15. factor_factory/engines/climate/__init__.py +179 -0
  16. factor_factory/engines/did/__init__.py +126 -0
  17. factor_factory/engines/did/_base.py +82 -0
  18. factor_factory/engines/did/borusyak_jaravel_spiess.py +166 -0
  19. factor_factory/engines/did/callaway_santanna.py +199 -0
  20. factor_factory/engines/did/sun_abraham.py +152 -0
  21. factor_factory/engines/did/twfe.py +87 -0
  22. factor_factory/engines/diffusion/__init__.py +180 -0
  23. factor_factory/engines/dml/__init__.py +69 -0
  24. factor_factory/engines/dml/_base.py +69 -0
  25. factor_factory/engines/dml/plr.py +85 -0
  26. factor_factory/engines/event_study/__init__.py +80 -0
  27. factor_factory/engines/event_study/_base.py +102 -0
  28. factor_factory/engines/event_study/fama_french.py +281 -0
  29. factor_factory/engines/event_study/market_adjusted.py +136 -0
  30. factor_factory/engines/hawkes/__init__.py +191 -0
  31. factor_factory/engines/het_te/__init__.py +74 -0
  32. factor_factory/engines/het_te/_base.py +77 -0
  33. factor_factory/engines/het_te/bcf.py +130 -0
  34. factor_factory/engines/het_te/causal_forest.py +106 -0
  35. factor_factory/engines/inequality/__init__.py +167 -0
  36. factor_factory/engines/mediation/__init__.py +85 -0
  37. factor_factory/engines/mediation/_base.py +234 -0
  38. factor_factory/engines/mediation/four_way.py +269 -0
  39. factor_factory/engines/panel_reg/__init__.py +73 -0
  40. factor_factory/engines/panel_reg/_base.py +71 -0
  41. factor_factory/engines/panel_reg/pyfixest_adapter.py +79 -0
  42. factor_factory/engines/rdd/__init__.py +85 -0
  43. factor_factory/engines/rdd/_base.py +93 -0
  44. factor_factory/engines/rdd/rd_robust.py +130 -0
  45. factor_factory/engines/reporting_bias/__init__.py +214 -0
  46. factor_factory/engines/scm/__init__.py +71 -0
  47. factor_factory/engines/scm/_base.py +70 -0
  48. factor_factory/engines/scm/augmented.py +129 -0
  49. factor_factory/engines/scm/matrix_completion.py +123 -0
  50. factor_factory/engines/scm/pysyncon_adapter.py +116 -0
  51. factor_factory/engines/sdid/__init__.py +82 -0
  52. factor_factory/engines/sdid/_base.py +141 -0
  53. factor_factory/engines/sdid/arkhangelsky.py +449 -0
  54. factor_factory/engines/spatial/__init__.py +64 -0
  55. factor_factory/engines/spatial/_base.py +59 -0
  56. factor_factory/engines/spatial/morans_i.py +67 -0
  57. factor_factory/engines/stl/__init__.py +69 -0
  58. factor_factory/engines/stl/_base.py +66 -0
  59. factor_factory/engines/stl/sktime_stl.py +71 -0
  60. factor_factory/engines/survival/__init__.py +105 -0
  61. factor_factory/engines/survival/_base.py +114 -0
  62. factor_factory/engines/survival/cox_ph.py +144 -0
  63. factor_factory/engines/survival/kaplan_meier.py +101 -0
  64. factor_factory/factors/__init__.py +8 -0
  65. factor_factory/jellycell/__init__.py +12 -0
  66. factor_factory/jellycell/_templates/audit.md.j2 +37 -0
  67. factor_factory/jellycell/_templates/diagnostics_checklist.md.j2 +52 -0
  68. factor_factory/jellycell/_templates/findings.md.j2 +61 -0
  69. factor_factory/jellycell/_templates/manuscript.md.j2 +57 -0
  70. factor_factory/jellycell/_templates/methodology.md.j2 +97 -0
  71. factor_factory/jellycell/cells.py +94 -0
  72. factor_factory/jellycell/figure.py +70 -0
  73. factor_factory/jellycell/notebooks/__init__.py +5 -0
  74. factor_factory/jellycell/notebooks/_scaffold.py +114 -0
  75. factor_factory/jellycell/notebooks/_templates/01_load.py +109 -0
  76. factor_factory/jellycell/notebooks/_templates/_helpers.py +19 -0
  77. factor_factory/jellycell/notebooks/_templates/data_README.md +37 -0
  78. factor_factory/jellycell/notebooks/_templates/jellycell.toml +33 -0
  79. factor_factory/jellycell/tearsheets/__init__.py +17 -0
  80. factor_factory/jellycell/tearsheets/_render.py +233 -0
  81. factor_factory/jellycell/tearsheets/audit.py +25 -0
  82. factor_factory/jellycell/tearsheets/diagnostics.py +25 -0
  83. factor_factory/jellycell/tearsheets/findings.py +25 -0
  84. factor_factory/jellycell/tearsheets/manuscript.py +29 -0
  85. factor_factory/jellycell/tearsheets/methodology.py +25 -0
  86. factor_factory/reporting/__init__.py +23 -0
  87. factor_factory/reporting/quarto.py +140 -0
  88. factor_factory/tests/__init__.py +0 -0
  89. factor_factory/tests/_fixtures/__init__.py +0 -0
  90. factor_factory/tests/_fixtures/cross_domain.py +1001 -0
  91. factor_factory/tests/_fixtures/synthetic_panels.py +113 -0
  92. factor_factory/tests/benchmarks/__init__.py +1 -0
  93. factor_factory/tests/benchmarks/test_panel_benchmarks.py +40 -0
  94. factor_factory/tests/properties/__init__.py +1 -0
  95. factor_factory/tests/properties/test_panel_properties.py +111 -0
  96. factor_factory/tests/test_batch15.py +121 -0
  97. factor_factory/tests/test_cross_domain.py +149 -0
  98. factor_factory/tests/test_diagnostics.py +136 -0
  99. factor_factory/tests/test_engines/__init__.py +0 -0
  100. factor_factory/tests/test_engines/test_batch10_imports.py +21 -0
  101. factor_factory/tests/test_engines/test_batch11_imports.py +82 -0
  102. factor_factory/tests/test_engines/test_batch12_imports.py +38 -0
  103. factor_factory/tests/test_engines/test_callaway_santanna.py +95 -0
  104. factor_factory/tests/test_engines/test_did_conformance.py +66 -0
  105. factor_factory/tests/test_engines/test_did_extensions.py +58 -0
  106. factor_factory/tests/test_engines/test_event_study.py +46 -0
  107. factor_factory/tests/test_engines/test_event_study_fama_french.py +84 -0
  108. factor_factory/tests/test_engines/test_het_te_dml.py +69 -0
  109. factor_factory/tests/test_engines/test_mediation.py +132 -0
  110. factor_factory/tests/test_engines/test_mediation_sensitivity.py +74 -0
  111. factor_factory/tests/test_engines/test_rdd.py +55 -0
  112. factor_factory/tests/test_engines/test_scm.py +33 -0
  113. factor_factory/tests/test_engines/test_sdid.py +94 -0
  114. factor_factory/tests/test_engines/test_sdid_placebo.py +39 -0
  115. factor_factory/tests/test_engines/test_survival.py +78 -0
  116. factor_factory/tests/test_engines/test_survival_strata.py +37 -0
  117. factor_factory/tests/test_geography.py +61 -0
  118. factor_factory/tests/test_jellycell_integration.py +153 -0
  119. factor_factory/tests/test_panel_contract.py +168 -0
  120. factor_factory/tests/test_polish.py +287 -0
  121. factor_factory/tests/test_streaming.py +77 -0
  122. factor_factory/tests/test_treatment_events.py +210 -0
  123. factor_factory/tidy/__init__.py +19 -0
  124. factor_factory/tidy/contracts.py +260 -0
  125. factor_factory/tidy/geography.py +118 -0
  126. factor_factory/tidy/panel.py +757 -0
  127. factor_factory/tidy/record_view.py +117 -0
  128. factor_factory/tidy/socrata.py +106 -0
  129. factor_factory/tidy/streaming.py +136 -0
  130. factor_factory-1.0.0.dist-info/METADATA +372 -0
  131. factor_factory-1.0.0.dist-info/RECORD +134 -0
  132. factor_factory-1.0.0.dist-info/WHEEL +4 -0
  133. factor_factory-1.0.0.dist-info/entry_points.txt +2 -0
  134. factor_factory-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,32 @@
1
+ """factor-factory — shared factor-model + analysis-pipeline framework.
2
+
3
+ Default install ships the tidy + diagnostics + jellycell layers. Engine
4
+ families are optional extras; install via e.g. ``pip install
5
+ factor-factory[did]``.
6
+
7
+ Top-level surface:
8
+
9
+ import factor_factory as ff
10
+
11
+ panel = ff.Panel.from_records(...)
12
+ results = ff.engines.did.estimate(panel, methods=("twfe",), ...)
13
+ ff.diagnostics.standardized_mean_differences(panel, ...)
14
+ ff.jellycell.tearsheets.methodology(project="my-showcase")
15
+ """
16
+
17
+ from . import diagnostics, engines, factors, jellycell
18
+ from ._version import __version__
19
+ from .tidy import Panel, PanelMetadata, Provenance, RecordView, TreatmentEvent
20
+
21
+ __all__ = [
22
+ "Panel",
23
+ "PanelMetadata",
24
+ "Provenance",
25
+ "RecordView",
26
+ "TreatmentEvent",
27
+ "__version__",
28
+ "diagnostics",
29
+ "engines",
30
+ "factors",
31
+ "jellycell",
32
+ ]
@@ -0,0 +1,46 @@
1
+ """``python -m factor_factory <subcommand>`` entry point.
2
+
3
+ Currently the only subcommand is ``scaffold``. More may be added later
4
+ (e.g., ``render-tearsheets``, ``validate-panel``).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import sys
11
+
12
+ from .jellycell.notebooks._scaffold import main as scaffold_main
13
+
14
+
15
+ def build_argument_parser() -> argparse.ArgumentParser:
16
+ parser = argparse.ArgumentParser(
17
+ prog="python -m factor_factory",
18
+ description="factor-factory CLI",
19
+ )
20
+ sub = parser.add_subparsers(dest="command")
21
+ sub.add_parser(
22
+ "scaffold",
23
+ help="Generate a jellycell + factor-factory showcase skeleton",
24
+ add_help=False,
25
+ )
26
+ return parser
27
+
28
+
29
+ def main(argv: list[str] | None = None) -> int:
30
+ argv = sys.argv[1:] if argv is None else argv
31
+ if not argv:
32
+ build_argument_parser().print_help()
33
+ return 0
34
+ cmd, *rest = argv
35
+ if cmd == "scaffold":
36
+ return scaffold_main(rest)
37
+ if cmd in ("-h", "--help", "help"):
38
+ build_argument_parser().print_help()
39
+ return 0
40
+ print(f"Unknown command: {cmd}", file=sys.stderr)
41
+ build_argument_parser().print_help()
42
+ return 2
43
+
44
+
45
+ if __name__ == "__main__": # pragma: no cover
46
+ raise SystemExit(main())
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,13 @@
1
+ """Diagnostic primitives shipped in v0.1 (the four required-everywhere ones)."""
2
+
3
+ from .assertions import multi_index_assertions
4
+ from .balance import standardized_mean_differences
5
+ from .residuals import residual_diagnostics
6
+ from .trends import parallel_trends_plot
7
+
8
+ __all__ = [
9
+ "multi_index_assertions",
10
+ "parallel_trends_plot",
11
+ "residual_diagnostics",
12
+ "standardized_mean_differences",
13
+ ]
@@ -0,0 +1,49 @@
1
+ """Structural integrity checks usable as defensive guardrails in notebooks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pandas as pd
6
+
7
+ from ..tidy.panel import Panel
8
+
9
+
10
+ def multi_index_assertions(panel: Panel) -> None:
11
+ """Raise ``AssertionError`` if the panel violates structural invariants.
12
+
13
+ Idempotent — safe to call at the top of any analysis cell.
14
+
15
+ Checks:
16
+ - Index is MultiIndex with names ('unit_id', 'period')
17
+ - unit_id is string-typed
18
+ - period is pd.Timestamp-typed
19
+ - Index is sorted
20
+ - Panel is balanced (every unit has every period)
21
+ - Outcome column exists
22
+ """
23
+ df = panel.df
24
+ idx = df.index
25
+
26
+ assert isinstance(idx, pd.MultiIndex), "Panel index must be MultiIndex."
27
+ assert list(idx.names) == ["unit_id", "period"], (
28
+ f"Panel index names must be ['unit_id', 'period'], got {list(idx.names)}."
29
+ )
30
+
31
+ units = idx.get_level_values("unit_id")
32
+ periods = idx.get_level_values("period")
33
+ assert units.dtype == object or pd.api.types.is_string_dtype(units), (
34
+ f"unit_id index must be string-typed, got {units.dtype}."
35
+ )
36
+ assert isinstance(periods, pd.DatetimeIndex), "period index must be DatetimeIndex."
37
+
38
+ assert idx.is_monotonic_increasing, "Panel index must be sorted."
39
+
40
+ n_units = len(units.unique())
41
+ n_periods = len(periods.unique())
42
+ assert len(df) == n_units * n_periods, (
43
+ f"Panel is unbalanced: {len(df)} rows vs expected {n_units * n_periods} "
44
+ f"({n_units} units × {n_periods} periods)."
45
+ )
46
+
47
+ assert panel.outcome_col in df.columns, (
48
+ f"Outcome column {panel.outcome_col!r} missing from panel."
49
+ )
@@ -0,0 +1,99 @@
1
+ """Standardized mean differences (SMD) for treated/control balance checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ from ..tidy.panel import Panel
9
+
10
+
11
+ def standardized_mean_differences(
12
+ panel: Panel,
13
+ *,
14
+ treated_col: str = "treated_unit",
15
+ covariates: tuple[str, ...],
16
+ pre_treatment_only: bool = True,
17
+ ) -> pd.DataFrame:
18
+ """Compute SMDs between treated and control units on each covariate.
19
+
20
+ Returns a DataFrame with one row per covariate. The ``imbalance_flag``
21
+ column flags ``"*"`` for ``|SMD| > 0.1`` and ``"***"`` for
22
+ ``|SMD| > 0.5`` — the conventional Stuart 2010 cutoffs.
23
+ """
24
+ if not covariates:
25
+ raise ValueError("At least one covariate must be supplied.")
26
+ df = panel.df
27
+ if treated_col not in df.columns:
28
+ raise ValueError(
29
+ f"Panel missing treated_col '{treated_col}'. Got columns: {list(df.columns)}."
30
+ )
31
+ missing = [c for c in covariates if c not in df.columns]
32
+ if missing:
33
+ raise ValueError(f"Panel missing covariate(s) {missing}. Got columns: {list(df.columns)}.")
34
+
35
+ if pre_treatment_only and "post" in df.columns:
36
+ df = df[df["post"] == 0]
37
+ if df.empty:
38
+ raise ValueError(
39
+ "pre_treatment_only=True but no pre-treatment rows on the panel "
40
+ "(all rows have post=1)."
41
+ )
42
+
43
+ treated_mask = df[treated_col].astype(bool)
44
+ control_mask = ~treated_mask
45
+ if not treated_mask.any():
46
+ raise ValueError(f"No treated rows: '{treated_col}' is all 0.")
47
+ if not control_mask.any():
48
+ raise ValueError(f"No control rows: '{treated_col}' is all 1.")
49
+
50
+ rows: list[dict[str, object]] = []
51
+ for cov in covariates:
52
+ treated_vals = df.loc[treated_mask, cov].astype(float)
53
+ control_vals = df.loc[control_mask, cov].astype(float)
54
+
55
+ treated_mean = float(treated_vals.mean())
56
+ control_mean = float(control_vals.mean())
57
+ diff = treated_mean - control_mean
58
+
59
+ # Pooled SD per Rubin 2001 / Stuart 2010
60
+ treated_var = float(treated_vals.var(ddof=1)) if len(treated_vals) > 1 else 0.0
61
+ control_var = float(control_vals.var(ddof=1)) if len(control_vals) > 1 else 0.0
62
+ pooled_sd = float(np.sqrt((treated_var + control_var) / 2.0))
63
+
64
+ if pooled_sd == 0: # noqa: SIM108 — explicit branches are clearer here
65
+ smd = 0.0 if diff == 0 else float("inf")
66
+ else:
67
+ smd = diff / pooled_sd
68
+
69
+ if not np.isfinite(smd) or abs(smd) > 0.5:
70
+ flag = "***"
71
+ elif abs(smd) > 0.1:
72
+ flag = "*"
73
+ else:
74
+ flag = ""
75
+
76
+ rows.append(
77
+ {
78
+ "covariate": cov,
79
+ "treated_mean": treated_mean,
80
+ "control_mean": control_mean,
81
+ "diff": diff,
82
+ "pooled_sd": pooled_sd,
83
+ "smd": smd,
84
+ "imbalance_flag": flag,
85
+ }
86
+ )
87
+
88
+ return pd.DataFrame(
89
+ rows,
90
+ columns=[
91
+ "covariate",
92
+ "treated_mean",
93
+ "control_mean",
94
+ "diff",
95
+ "pooled_sd",
96
+ "smd",
97
+ "imbalance_flag",
98
+ ],
99
+ )
@@ -0,0 +1,96 @@
1
+ """Residual normality + heteroskedasticity diagnostics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from scipy import stats
10
+
11
+ _RNG_SEED = 20260419 # fixed seed so Shapiro sub-sampling is reproducible
12
+
13
+
14
+ def residual_diagnostics(
15
+ residuals: pd.Series,
16
+ *,
17
+ fitted_values: pd.Series | None = None,
18
+ sample_size_for_shapiro: int = 5000,
19
+ ) -> dict[str, Any]:
20
+ """Run the canonical normality + heteroskedasticity test set.
21
+
22
+ Returns a JSON-serializable dict with normality (Jarque-Bera,
23
+ Shapiro-Wilk) and, if ``fitted_values`` is supplied, a manual
24
+ Breusch-Pagan test for heteroskedasticity (regression of squared
25
+ residuals on fitted values).
26
+ """
27
+ residuals = pd.Series(residuals).dropna().astype(float)
28
+ if residuals.empty:
29
+ raise ValueError("residual_diagnostics received an empty residuals series.")
30
+
31
+ n = int(residuals.size)
32
+ mean = float(residuals.mean())
33
+ std = float(residuals.std(ddof=1)) if n > 1 else 0.0
34
+
35
+ jb_stat, jb_p = stats.jarque_bera(residuals.to_numpy())
36
+
37
+ sample = residuals
38
+ if n > sample_size_for_shapiro:
39
+ rng = np.random.default_rng(_RNG_SEED)
40
+ idx = rng.choice(n, size=sample_size_for_shapiro, replace=False)
41
+ sample = residuals.iloc[idx]
42
+ sw_stat, sw_p = stats.shapiro(sample.to_numpy())
43
+
44
+ bp_stat: float | None = None
45
+ bp_p: float | None = None
46
+ homo_passes: bool | None = None
47
+ if fitted_values is not None:
48
+ fitted = pd.Series(fitted_values).astype(float).reindex(residuals.index).dropna()
49
+ # align — Shapiro can't help here; we just need both series same length
50
+ common = residuals.index.intersection(fitted.index)
51
+ if len(common) < 5:
52
+ raise ValueError(
53
+ "residual_diagnostics: fitted_values has fewer than 5 overlapping "
54
+ "rows with residuals; can't run Breusch-Pagan."
55
+ )
56
+ e = residuals.loc[common].to_numpy()
57
+ f = fitted.loc[common].to_numpy()
58
+ bp_stat, bp_p = _breusch_pagan_simple(e, f)
59
+ homo_passes = bp_p > 0.05
60
+
61
+ return {
62
+ "n": n,
63
+ "mean": mean,
64
+ "std": std,
65
+ "jarque_bera_stat": float(jb_stat),
66
+ "jarque_bera_p": float(jb_p),
67
+ "shapiro_wilk_stat": float(sw_stat),
68
+ "shapiro_wilk_p": float(sw_p),
69
+ "breusch_pagan_stat": bp_stat,
70
+ "breusch_pagan_p": bp_p,
71
+ "normality_passes": bool(jb_p > 0.05),
72
+ "homoskedasticity_passes": homo_passes,
73
+ }
74
+
75
+
76
+ def _breusch_pagan_simple(residuals: np.ndarray, fitted: np.ndarray) -> tuple[float, float]:
77
+ """Simple Breusch-Pagan against fitted values.
78
+
79
+ LM = n * R^2 from regressing squared residuals on fitted values
80
+ (constant + fitted), distributed asymptotically as chi-square(1).
81
+ """
82
+ e2 = residuals**2
83
+ if np.allclose(e2.var(ddof=0), 0.0):
84
+ return 0.0, 1.0
85
+ x = np.column_stack([np.ones_like(fitted), fitted])
86
+ coef, *_ = np.linalg.lstsq(x, e2, rcond=None)
87
+ pred = x @ coef
88
+ ss_res = float(((e2 - pred) ** 2).sum())
89
+ ss_tot = float(((e2 - e2.mean()) ** 2).sum())
90
+ if ss_tot == 0:
91
+ return 0.0, 1.0
92
+ r_squared = 1.0 - ss_res / ss_tot
93
+ n = int(residuals.size)
94
+ lm = n * r_squared
95
+ p_value = float(stats.chi2.sf(lm, df=1))
96
+ return float(lm), p_value
@@ -0,0 +1,80 @@
1
+ """Parallel-trends visualization for DiD pre-flight checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date
6
+ from typing import TYPE_CHECKING
7
+
8
+ import pandas as pd
9
+
10
+ from ..tidy.panel import Panel
11
+
12
+ if TYPE_CHECKING: # pragma: no cover
13
+ import matplotlib.axes
14
+ import matplotlib.figure
15
+
16
+
17
+ def parallel_trends_plot(
18
+ panel: Panel,
19
+ *,
20
+ treated_col: str = "treated_unit",
21
+ outcome_col: str | None = None,
22
+ treatment_date: date | pd.Timestamp | None = None,
23
+ ax: matplotlib.axes.Axes | None = None,
24
+ ) -> matplotlib.figure.Figure:
25
+ """Plot mean outcome over time for treated vs. control units.
26
+
27
+ Useful as a pre-DiD parallel-trends visual. If the panel carries
28
+ treatment events and ``treatment_date`` is omitted, the first
29
+ event's date is used.
30
+ """
31
+ import matplotlib.figure as _mfig
32
+ import matplotlib.pyplot as plt
33
+
34
+ df = panel.df
35
+ if treated_col not in df.columns:
36
+ raise ValueError(f"Panel missing treated_col '{treated_col}'. Columns: {list(df.columns)}.")
37
+
38
+ outcome = outcome_col or panel.outcome_col
39
+ if outcome not in df.columns:
40
+ raise ValueError(f"Panel missing outcome column '{outcome}'.")
41
+
42
+ if treatment_date is None and panel.treatment_events:
43
+ treatment_date = panel.treatment_events[0].treatment_date
44
+
45
+ grouped = (
46
+ df.groupby([treated_col, df.index.get_level_values("period")])[outcome].mean().unstack(0)
47
+ )
48
+ # rename 0/1 columns to control/treated for the legend
49
+ rename = {0: "Control", 1: "Treated"}
50
+ grouped = grouped.rename(columns=rename)
51
+
52
+ if ax is None:
53
+ fig, ax = plt.subplots(figsize=(8, 5))
54
+ else:
55
+ host_fig = ax.figure
56
+ if not isinstance(host_fig, _mfig.Figure):
57
+ raise TypeError("ax.figure must be a top-level Figure, not a SubFigure.")
58
+ fig = host_fig
59
+
60
+ for col in ("Control", "Treated"):
61
+ if col in grouped.columns:
62
+ ax.plot(grouped.index, grouped[col], marker="o", label=col, linewidth=1.5)
63
+
64
+ if treatment_date is not None:
65
+ # axvline is type-stubbed as float-only but matplotlib accepts datetimes.
66
+ ax.axvline(
67
+ pd.Timestamp(treatment_date), # type: ignore[arg-type]
68
+ color="black",
69
+ linestyle="--",
70
+ alpha=0.6,
71
+ label="Treatment date",
72
+ )
73
+
74
+ ax.set_xlabel("Period")
75
+ ax.set_ylabel(f"Mean {outcome}")
76
+ ax.set_title(f"Parallel trends — {outcome}")
77
+ ax.legend()
78
+ ax.grid(True, alpha=0.3)
79
+ fig.tight_layout()
80
+ return fig
@@ -0,0 +1,29 @@
1
+ """Pluggable engines.
2
+
3
+ Each method family lives under its own subpackage with a Protocol +
4
+ frozen Result dataclass + registry. See
5
+ ``docs/og_context/03_specs/engine_protocol.md`` for the contract.
6
+
7
+ Currently shipped families:
8
+
9
+ - :mod:`factor_factory.engines.did` — TwfeEngine + CallawaySantannaEngine
10
+ - :mod:`factor_factory.engines.survival` — KaplanMeierEngine + CoxPHEngine
11
+ - :mod:`factor_factory.engines.event_study` — MarketAdjustedEngine
12
+ - :mod:`factor_factory.engines.sdid` — SyntheticDidEngine (closes a
13
+ Python-ecosystem gap; no mature pkg before this)
14
+ - :mod:`factor_factory.engines.mediation` — FourWayMediationEngine
15
+ (VanderWeele 2014 — closes a Python-ecosystem gap)
16
+
17
+ Planned families (Phase 2): rdd, scm, changepoint, stl, panel_reg,
18
+ inequality, oaxaca_blinder, spatial, reporting_bias, hawkes, het_te
19
+ (causal forests), dml (double ML), climate, diffusion.
20
+
21
+ Deliberately out of scope: GWAS / biobank-scale genetics — different
22
+ ops world (HPC, BGEN/VCF formats, JVM-backed ``hail``). See
23
+ ``docs/supported-domains.md`` for rationale.
24
+ """
25
+
26
+ from . import did, event_study, mediation, sdid, survival
27
+ from ._registry import EngineRegistry
28
+
29
+ __all__ = ["EngineRegistry", "did", "event_study", "mediation", "sdid", "survival"]
@@ -0,0 +1,12 @@
1
+ """Common base types shared across engine families.
2
+
3
+ Each engine family (`did/`, `rdd/`, `scm/`, ...) defines its own
4
+ ``Result`` dataclass and ``Engine`` Protocol in its own ``_base.py``.
5
+ This module just re-exports the registry helper for convenience.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ._registry import EngineRegistry
11
+
12
+ __all__ = ["EngineRegistry"]
@@ -0,0 +1,37 @@
1
+ """Generic engine registry — runtime discovery + extension hook."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class EngineRegistry[E]:
7
+ """Lazy-loading engine registry.
8
+
9
+ Engines that depend on missing optional packages should be skipped
10
+ at registration time (the package's ``__init__.py`` does the
11
+ try/except dance), so the registry only ever holds engines that are
12
+ actually callable.
13
+
14
+ Downstream packages can register their own engines at runtime via
15
+ ``registry.register("name", MyEngine())``.
16
+ """
17
+
18
+ def __init__(self, engines: dict[str, E] | None = None) -> None:
19
+ self._engines: dict[str, E] = dict(engines or {})
20
+
21
+ def __getitem__(self, name: str) -> E:
22
+ if name not in self._engines:
23
+ raise KeyError(f"Unknown engine '{name}'. Available: {sorted(self._engines)}")
24
+ return self._engines[name]
25
+
26
+ def __contains__(self, name: object) -> bool:
27
+ return isinstance(name, str) and name in self._engines
28
+
29
+ def register(self, name: str, engine: E) -> None:
30
+ """Register a new engine at runtime (e.g., from a downstream package)."""
31
+ self._engines[name] = engine
32
+
33
+ def available(self) -> list[str]:
34
+ return sorted(self._engines)
35
+
36
+ def __repr__(self) -> str:
37
+ return f"EngineRegistry(available={self.available()!r})"
@@ -0,0 +1,64 @@
1
+ """Changepoint-detection engines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from typing import Any
7
+
8
+ from ...tidy.panel import Panel
9
+ from .._registry import EngineRegistry
10
+ from ._base import ChangepointEngine, ChangepointResult
11
+
12
+ _engines: dict[str, ChangepointEngine] = {}
13
+
14
+ try:
15
+ from .ruptures_adapter import RupturesEngine
16
+
17
+ _engines["ruptures"] = RupturesEngine()
18
+ except ImportError: # pragma: no cover
19
+ pass
20
+
21
+ registry: EngineRegistry[ChangepointEngine] = EngineRegistry(_engines)
22
+
23
+
24
+ class ChangepointResults:
25
+ def __init__(self, results: list[ChangepointResult]) -> None:
26
+ self.results = results
27
+
28
+ def __iter__(self) -> Iterable[ChangepointResult]:
29
+ return iter(self.results)
30
+
31
+ def __getitem__(self, key: int | str) -> ChangepointResult:
32
+ if isinstance(key, int):
33
+ return self.results[key]
34
+ for r in self.results:
35
+ if r.method == key:
36
+ return r
37
+ raise KeyError(key)
38
+
39
+ def to_records(self) -> list[dict[str, Any]]:
40
+ return [r.to_dict() for r in self.results]
41
+
42
+
43
+ def estimate(
44
+ panel: Panel,
45
+ *,
46
+ methods: tuple[str, ...] = ("ruptures",),
47
+ outcome: str | None = None,
48
+ **engine_specific_kwargs: Any,
49
+ ) -> ChangepointResults:
50
+ outcome = outcome or panel.outcome_col
51
+ if not methods:
52
+ raise ValueError("methods must be non-empty.")
53
+ return ChangepointResults(
54
+ [registry[m].fit(panel, outcome=outcome, **engine_specific_kwargs) for m in methods]
55
+ )
56
+
57
+
58
+ __all__ = [
59
+ "ChangepointEngine",
60
+ "ChangepointResult",
61
+ "ChangepointResults",
62
+ "estimate",
63
+ "registry",
64
+ ]
@@ -0,0 +1,59 @@
1
+ """Changepoint-detection engine Protocol + Result."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Protocol
7
+
8
+ import pandas as pd
9
+
10
+ from ...tidy.panel import Panel
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ChangepointResult:
15
+ """Changepoint-detection fit result."""
16
+
17
+ method: str
18
+ changepoints: list[int] # period indices at detected breaks
19
+ regime_means: list[float] # mean outcome within each regime
20
+ n_regimes: int
21
+ model: str # "l1" | "l2" | "rbf" | "bayesian_online"
22
+ penalty: float | None = None
23
+ confidence: list[float] | None = None # per-changepoint confidence score
24
+ diagnostics: dict[str, Any] | None = None
25
+ meta: dict[str, Any] | None = field(default=None, repr=False)
26
+
27
+ def to_dict(self) -> dict[str, Any]:
28
+ return {
29
+ "method": self.method,
30
+ "changepoints": self.changepoints,
31
+ "regime_means": self.regime_means,
32
+ "n_regimes": self.n_regimes,
33
+ "model": self.model,
34
+ "penalty": self.penalty,
35
+ "confidence": self.confidence,
36
+ "diagnostics": self.diagnostics,
37
+ }
38
+
39
+ def summary_table(self) -> pd.DataFrame:
40
+ row = {
41
+ "method": self.method,
42
+ "n_changepoints": len(self.changepoints),
43
+ "n_regimes": self.n_regimes,
44
+ "model": self.model,
45
+ "penalty": self.penalty,
46
+ }
47
+ return pd.DataFrame([row]).set_index("method")
48
+
49
+
50
+ class ChangepointEngine(Protocol):
51
+ name: str
52
+
53
+ def fit(
54
+ self,
55
+ panel: Panel,
56
+ *,
57
+ outcome: str,
58
+ **engine_specific_kwargs: Any,
59
+ ) -> ChangepointResult: ...