lattab 0.2.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.
lattab/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # lattab
2
+
3
+ Convert DataFrames and regression results to LaTeX tables in multiple formats.
4
+ The base package requires `pandas`. Install `.[econometrics]` to fit OLS,
5
+ IV and multi-way fixed effects. The package is importable via
6
+ `sys.path.insert(0, <repo root>)` or `pip install -e .`.
7
+
8
+ The project guide includes a five-model comparison estimated from three
9
+ SQLite databases. [Examples and installation](../README.md)
10
+
11
+ ## Styles
12
+
13
+ | name | rules |
14
+ |---|---|
15
+ | `"double-outer"` (recommended for regression tables) | `\hline\hline` at the top and bottom; single `\hline` inside |
16
+ | `"hline-hline"` (default) | `\hline\hline` at every separator |
17
+ | `"booktabs"` | `\toprule` / `\midrule` / `\bottomrule` |
18
+ | `"hline"` | single `\hline` |
19
+ | `"grid"` | single `\hline` (extend by passing a custom `RuleStyle`) |
20
+
21
+ ## Usage
22
+
23
+ ```python
24
+ from lattab import to_latex, regression_table
25
+
26
+ # DataFrame -> table
27
+ to_latex(df, caption="Summary statistics", label="tab:sum",
28
+ style="booktabs", digits=3, rename={"old": "New"})
29
+
30
+ # Regression results -> table
31
+ from lattab import regression_table
32
+ tex = regression_table(
33
+ [m1, m2], # statsmodels results objects
34
+ model_names=[r"$\Delta$ UR", "Model 2"],
35
+ caption="Main results",
36
+ label="tab:reg",
37
+ style="double-outer",
38
+ rename={"d_fedfunds": r"$\Delta$ FFR"},
39
+ notes=r"Standard errors in parentheses. *** $p<0.01$.",
40
+ )
41
+ ```
42
+
43
+ Inline math in labels, headers, and notes is preserved automatically: text
44
+ inside `$...$` spans is passed through verbatim, everything else is escaped.
45
+
46
+ ## Tests
47
+
48
+ ```bash
49
+ python -m pytest tests/
50
+ ```
lattab/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """lattab: convert DataFrames and regression results to LaTeX tables.
2
+
3
+ Quick start::
4
+
5
+ from lattab import to_latex, regression_table
6
+
7
+ to_latex(df, caption="Summary statistics", label="tab:summary",
8
+ style="hline-hline")
9
+
10
+ regression_table([m1, m2], caption="Main results", label="tab:reg",
11
+ style="double-outer")
12
+ """
13
+
14
+ from .core import escape, to_latex
15
+ from .estimation import FittedRegression, fit_regression
16
+ from .regression import regression_table
17
+ from .samples import fit_regressions
18
+ from .styles import (
19
+ BOOKTABS,
20
+ DOUBLE_OUTER,
21
+ GRID,
22
+ HHLINE,
23
+ SINGLE,
24
+ RuleStyle,
25
+ get_style,
26
+ )
27
+
28
+ __all__ = [
29
+ "to_latex",
30
+ "fit_regression",
31
+ "fit_regressions",
32
+ "FittedRegression",
33
+ "regression_table",
34
+ "escape",
35
+ "RuleStyle",
36
+ "get_style",
37
+ "BOOKTABS",
38
+ "DOUBLE_OUTER",
39
+ "HHLINE",
40
+ "SINGLE",
41
+ "GRID",
42
+ ]
43
+
44
+ __version__ = "0.2.0"
lattab/core.py ADDED
@@ -0,0 +1,181 @@
1
+ """DataFrame -> LaTeX table conversion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Mapping
7
+
8
+ import pandas as pd
9
+
10
+ from .styles import RuleStyle, get_style
11
+
12
+
13
+ def escape(text: str) -> str:
14
+ """Escape LaTeX special characters in plain-text cells."""
15
+ replacements = {
16
+ "\\": r"\textbackslash{}",
17
+ "&": r"\&",
18
+ "%": r"\%",
19
+ "$": r"\$",
20
+ "#": r"\#",
21
+ "_": r"\_",
22
+ "{": r"\{",
23
+ "}": r"\}",
24
+ "~": r"\textasciitilde{}",
25
+ "^": r"\textasciicircum{}",
26
+ }
27
+ return "".join(replacements.get(ch, ch) for ch in text)
28
+
29
+
30
+ _MATH_SPAN = re.compile(r"(\$[^$]*\$)")
31
+
32
+
33
+ def escape_mixed(text: str) -> str:
34
+ """Escape text while keeping inline ``$...$`` math spans verbatim.
35
+
36
+ Handles labels such as ``"$\\Delta$ FFR"``: the math span is passed
37
+ through untouched, surrounding text is escaped.
38
+ """
39
+ parts = _MATH_SPAN.split(text)
40
+ return "".join(p if i % 2 else escape(p) for i, p in enumerate(parts))
41
+
42
+
43
+ def _is_math(cell: str) -> bool:
44
+ s = cell.strip()
45
+ return s.startswith("$") and s.endswith("$") and len(s) > 1
46
+
47
+
48
+ def _fmt_value(value, digits: int, na_rep: str) -> str:
49
+ try:
50
+ if pd.isna(value):
51
+ return na_rep
52
+ except (TypeError, ValueError): # array-like cells render as text
53
+ pass
54
+ if isinstance(value, int) and not isinstance(value, bool):
55
+ return str(value)
56
+ if isinstance(value, float):
57
+ return f"{value:.{digits}f}"
58
+ return str(value)
59
+
60
+
61
+ def _column_alignment(df, align: str | None, index: bool) -> str:
62
+ if align is not None:
63
+ return align
64
+ n = len(df.columns) + (1 if index else 0)
65
+ return "l" + "r" * (n - 1)
66
+
67
+
68
+ def to_latex(
69
+ df,
70
+ caption: str | None = None,
71
+ label: str | None = None,
72
+ notes: str | None = None,
73
+ style: str | RuleStyle | None = None,
74
+ digits: int = 3,
75
+ index: bool = False,
76
+ rename: Mapping[str, str] | None = None,
77
+ align: str | None = None,
78
+ full: bool = True,
79
+ position: str = "h!",
80
+ na_rep: str = "",
81
+ ) -> str:
82
+ """Convert a DataFrame to a LaTeX table string.
83
+
84
+ Parameters
85
+ ----------
86
+ df : pandas.DataFrame
87
+ Data to render. String cells are escaped automatically; cells wrapped
88
+ in ``$...$`` are passed through verbatim so you can use math mode.
89
+ na_rep : str
90
+ Replacement for missing cells (NaN, None, pd.NA), empty by default.
91
+ The replacement is escaped like other plain-text cells.
92
+ caption, label : str, optional
93
+ Table caption and \\label (only used when ``full=True``).
94
+ notes : str, optional
95
+ Footnotes rendered under the table in \\footnotesize.
96
+ style : str or RuleStyle, optional
97
+ One of ``"booktabs"``, ``"hline-hline"``, ``"double-outer"``,
98
+ ``"hline"``, ``"grid"`` (or a custom :class:`~lattab.styles.RuleStyle`).
99
+ ``"double-outer"`` uses double top and bottom rules and single interior rules.
100
+ Default is ``"hline-hline"`` (double horizontal rules).
101
+ digits : int
102
+ Number of decimals for float cells.
103
+ index : bool
104
+ Include the DataFrame index as the first column.
105
+ rename : mapping, optional
106
+ Rename column headers, the index name, and displayed index labels.
107
+ align : str, optional
108
+ Column specification, e.g. ``"lcc"``. Default is first column ``l``,
109
+ the rest ``r``.
110
+ full : bool
111
+ If True (default), wrap in a ``table`` environment with caption,
112
+ label, and notes. If False, return only the ``tabular``.
113
+ position : str
114
+ Float placement specifier when ``full=True``.
115
+
116
+ Returns
117
+ -------
118
+ str
119
+ The LaTeX source.
120
+ """
121
+ rules = get_style(style)
122
+ rename = rename or {}
123
+ headers = [rename.get(str(c), str(c)) for c in df.columns]
124
+ headers = [escape_mixed(h) for h in headers]
125
+
126
+ colspec = _column_alignment(df, align, index)
127
+ lines: list[str] = []
128
+ if index:
129
+ try:
130
+ name_missing = bool(pd.isna(df.index.name))
131
+ except (TypeError, ValueError):
132
+ name_missing = False
133
+ ind_name = None if name_missing else rename.get(str(df.index.name), str(df.index.name))
134
+ else:
135
+ ind_name = None
136
+
137
+ lines.append(r"\begin{tabular}{" + colspec + "}")
138
+ lines.append(rules.top)
139
+ if any(headers) or (index and ind_name not in ("None", "")):
140
+ head = ([escape(ind_name) if ind_name and not _is_math(ind_name) else (ind_name or "")] if index else []) + headers
141
+ lines.append(" & ".join(head) + r" \\")
142
+ lines.append(rules.mid)
143
+ # itertuples is the fast path; duplicated column names fall back to iterrows.
144
+ if df.columns.duplicated().any():
145
+ rows = (tuple(row) for row in df.iterrows())
146
+ else:
147
+ rows = df.itertuples(index=False, name=None)
148
+ for idx, values in zip(df.index, rows):
149
+ cells = []
150
+ if index:
151
+ try:
152
+ missing = bool(pd.isna(idx))
153
+ except (TypeError, ValueError):
154
+ missing = False
155
+ idx_cell = na_rep if missing else rename.get(str(idx), str(idx))
156
+ cells.append(idx_cell if _is_math(idx_cell) else escape(idx_cell))
157
+ for v in values:
158
+ cell = _fmt_value(v, digits, na_rep)
159
+ cells.append(cell if _is_math(cell) or re.fullmatch(r"-?[\d.,]+", cell) else escape(cell))
160
+ lines.append(" & ".join(cells) + r" \\")
161
+ lines.append(rules.bottom)
162
+ lines.append(r"\end{tabular}")
163
+
164
+ body = "\n".join(lines)
165
+ if not full:
166
+ return body
167
+
168
+ out = [f"\\begin{{table}}[{position}]", r" \centering"]
169
+ if caption:
170
+ out.append(f" \\caption{{{escape(caption)}}}")
171
+ if label:
172
+ out.append(f" \\label{{{label}}}")
173
+ out.append(" " + body)
174
+ if notes:
175
+ out.append(
176
+ " \\begin{flushleft}\n"
177
+ " \\footnotesize{\\emph{Notes}: " + escape_mixed(notes) + "}\n"
178
+ " \\end{flushleft}"
179
+ )
180
+ out.append("\\end{table}")
181
+ return "\n".join(out)
lattab/estimation.py ADDED
@@ -0,0 +1,246 @@
1
+ """OLS and instrumental variables with named regressors and fixed effects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from functools import cached_property
7
+ from typing import Any, Sequence
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class FittedRegression:
15
+ """A native linearmodels result and the specification used in a table."""
16
+
17
+ result: Any
18
+ dependent: str
19
+ terms: tuple[str, ...]
20
+ fixed_effects: tuple[str, ...]
21
+ endogenous: tuple[str, ...]
22
+ instruments: tuple[str, ...]
23
+ clusters: tuple[str, ...]
24
+ cluster_counts: tuple[int, ...]
25
+
26
+ absorbed_totals: pd.Series | None = None
27
+ absorbed_rank: int | None = None
28
+
29
+ @property
30
+ def rsquared_inclusive(self):
31
+ if self.absorbed_totals is None:
32
+ return self.result.rsquared
33
+ total = self.absorbed_totals[self.dependent]
34
+ return 1 - self.result.resid_ss / total if total else np.nan
35
+
36
+ @property
37
+ def rsquared_within(self):
38
+ if self.absorbed_totals is not None:
39
+ return self.result.rsquared
40
+ return getattr(self.result, "absorbed_rsquared", None)
41
+
42
+ @cached_property
43
+ def first_stage_diagnostics(self):
44
+ """First-stage results on the original outcome scale and FE degrees of freedom."""
45
+ first = self.result.first_stage
46
+ diagnostics = first.diagnostics
47
+ if self.absorbed_totals is None:
48
+ return diagnostics
49
+ from scipy.stats import chi2, f
50
+
51
+ diagnostics = diagnostics.copy()
52
+ q = len(self.instruments)
53
+ for name, stage in first.individual.items():
54
+ total = self.absorbed_totals[name]
55
+ diagnostics.loc[name, "rsquared"] = 1 - stage.resid_ss / total if total else np.nan
56
+ if self.result.cov_type in ("unadjusted", "homoskedastic"):
57
+ stat = diagnostics.loc[name, "f.stat"]
58
+ if self.absorbed_rank is None:
59
+ # Three or more dimensions have no exact pairwise FE rank.
60
+ diagnostics.loc[name, ["f.stat", "f.pval", "f.dist"]] = (
61
+ q * stat, chi2.sf(q * stat, q), f"chi2({q})",
62
+ )
63
+ else:
64
+ df = stage.df_resid - self.absorbed_rank
65
+ if df <= 0:
66
+ raise ValueError("no residual degrees of freedom for the first-stage F test")
67
+ diagnostics.loc[name, ["f.pval", "f.dist"]] = f.sf(stat, q, df), f"F({q},{df})"
68
+ return diagnostics
69
+
70
+
71
+ def _names(value: str | Sequence[str], role: str) -> tuple[str, ...]:
72
+ names = (value,) if isinstance(value, str) else tuple(value)
73
+ if any(not isinstance(name, str) or not name for name in names):
74
+ raise ValueError(f"{role} must contain nonempty column names")
75
+ if len(set(names)) != len(names):
76
+ raise ValueError(f"{role} contains a duplicate column")
77
+ return names
78
+
79
+
80
+ def _effect_indicators(effects: pd.DataFrame, reserved: Sequence[str]) -> pd.DataFrame:
81
+ """Choose a basis for the categorical effects conditional on the intercept."""
82
+ from scipy.linalg import qr
83
+
84
+ dummies = pd.get_dummies(effects, drop_first=True, dtype=float)
85
+ if effects.shape[1] > 1:
86
+ # Nested effects and disconnected panels can have redundant indicators
87
+ # even after removing one reference category per effect.
88
+ values = dummies.to_numpy()
89
+ _, triangular, order = qr(values - values.mean(axis=0), mode="economic", pivoting=True)
90
+ diagonal = np.abs(triangular.diagonal())
91
+ tolerance = diagonal.max() * max(values.shape) * np.finfo(float).eps
92
+ rank = np.count_nonzero(diagonal > tolerance)
93
+ dummies = dummies.iloc[:, sorted(order[:rank])]
94
+ prefix = "_fe_"
95
+ while any(name.startswith(prefix) for name in reserved):
96
+ prefix = "_" + prefix
97
+ dummies.columns = [f"{prefix}{i}" for i in range(dummies.shape[1])]
98
+ return dummies
99
+
100
+
101
+ def _absorb_iv(numeric, effects, dependent, exog, endogenous, instruments, cov_type):
102
+ """Remove the joint FE space from outcome, regressors and instruments."""
103
+ import pyhdfe
104
+
105
+ ids = np.column_stack([effects[name].cat.codes for name in effects])
106
+ need_rank = cov_type == "unadjusted" and effects.shape[1] <= 2
107
+ algorithm = pyhdfe.create(
108
+ ids, drop_singletons=False, compute_degrees=need_rank,
109
+ options={"tol": 1e-12} if effects.shape[1] > 1 else None,
110
+ )
111
+ # Standardize before the projection so its stopping tolerance is unit-free.
112
+ centered = numeric - numeric.mean()
113
+ scales = centered.std(ddof=0).replace(0, 1)
114
+ within = algorithm.residualize((centered / scales).to_numpy())
115
+ # Numerical dust after projecting out a term cannot identify its slope.
116
+ absorbed = np.linalg.norm(within, axis=0) <= 1e-10 * np.sqrt(len(numeric))
117
+ if absorbed.any():
118
+ names = ", ".join(numeric.columns[absorbed])
119
+ raise ValueError(f"no within-effect variation in: {names}")
120
+ frame = pd.DataFrame(within, index=numeric.index, columns=numeric.columns)
121
+ for columns in ((*exog, *endogenous), (*exog, *instruments)):
122
+ design = frame.loc[:, list(columns)].to_numpy()
123
+ # Projection error can leave tiny singular values in exactly collinear
124
+ # combinations, e.g. when an instrument equals a control plus firm FE.
125
+ if np.linalg.matrix_rank(design, tol=1e-10 * np.sqrt(len(design))) < len(columns):
126
+ raise ValueError(f"no full column rank after absorbing fixed effects: {columns}")
127
+ frame = frame.mul(scales)
128
+ totals = centered[[dependent, *endogenous]].pow(2).sum()
129
+ # pyhdfe counts FE rank after peeling singletons, even when retained.
130
+ rank = algorithm.degrees + algorithm.singletons if need_rank else None
131
+ return frame, totals, rank
132
+
133
+
134
+ def fit_regression(
135
+ data: pd.DataFrame,
136
+ dependent: str,
137
+ exog: str | Sequence[str] = (),
138
+ *,
139
+ endogenous: str | Sequence[str] = (),
140
+ instruments: str | Sequence[str] = (),
141
+ fixed_effects: str | Sequence[str] = (),
142
+ clusters: str | Sequence[str] = (),
143
+ cov_type: str | None = None,
144
+ absorb_iv: bool = False,
145
+ ) -> FittedRegression:
146
+ """Fit OLS or two-stage least squares, with an intercept.
147
+
148
+ Supply column names. The outcome, controls, endogenous regressors and
149
+ excluded instruments must be numeric. Each fixed effect is categorical,
150
+ including integer years. Rows missing any field used in this specification
151
+ are dropped together. The input DataFrame and its index are preserved.
152
+
153
+ OLS absorbs additive fixed effects. For IV, treatment-coded fixed effects
154
+ enter both stages as included instruments. This IV design is dense, so
155
+ its memory usage grows with the number of observed levels. For IV with
156
+ additive fixed effects, pass absorb_iv=True to remove those effects
157
+ before both stages. This mode reports slopes only and retains singleton
158
+ observations. Its native result uses within-transformed data. Use
159
+ rsquared_inclusive and first_stage_diagnostics on the returned fit for
160
+ original-scale statistics. For unadjusted covariance with three or more
161
+ varying effects the excluded-instrument test uses an asymptotic chi-square.
162
+
163
+ The default covariance is heteroskedasticity-robust (HC0). Specify
164
+ one or two cluster columns for clustered covariance, or request
165
+ `cov_type="unadjusted"` for homoskedastic inference. Covariances use
166
+ linearmodels' default without the finite-sample correction. Access the
167
+ native result (and, for IV, its first stage) through `.result`.
168
+ """
169
+ try:
170
+ from linearmodels.iv import AbsorbingLS, IV2SLS
171
+ except ModuleNotFoundError as exc:
172
+ if exc.name != "linearmodels":
173
+ raise
174
+ raise ImportError("fit_regression requires the lattab[econometrics] extra") from exc
175
+
176
+ if not isinstance(dependent, str) or not dependent:
177
+ raise ValueError("dependent must be one column name")
178
+ exog = _names(exog, "exog")
179
+ endogenous = _names(endogenous, "endogenous")
180
+ instruments = _names(instruments, "instruments")
181
+ effects = _names(fixed_effects, "fixed_effects")
182
+ clusters = _names(clusters, "clusters")
183
+ if bool(endogenous) != bool(instruments) or len(instruments) < len(endogenous):
184
+ raise ValueError("IV requires at least one excluded instrument per endogenous regressor")
185
+ if len(clusters) > 2:
186
+ raise ValueError("clusters supports one or two columns")
187
+ if cov_type is None:
188
+ cov_type = "clustered" if clusters else "robust"
189
+ if cov_type not in {"unadjusted", "robust", "clustered"}:
190
+ raise ValueError("cov_type must be unadjusted, robust or clustered")
191
+ if (cov_type == "clustered") != bool(clusters):
192
+ raise ValueError("clustered covariance requires cluster columns and vice versa")
193
+
194
+ roles = (dependent, *exog, *endogenous, *instruments, *effects)
195
+ if len(set(roles)) != len(roles):
196
+ raise ValueError("outcome, regressors, instruments and fixed effects must have distinct names")
197
+ if "const" in (*exog, *endogenous, *instruments):
198
+ raise ValueError("'const' is reserved for the fitted intercept")
199
+ if not data.columns.is_unique:
200
+ raise ValueError("data must have unique column names")
201
+ required = list(dict.fromkeys((*roles, *clusters)))
202
+ missing = [name for name in required if name not in data]
203
+ if missing:
204
+ raise ValueError(f"columns missing from data: {', '.join(missing)}")
205
+ sample = data.loc[:, required].dropna()
206
+ if sample.empty:
207
+ raise ValueError("no complete observations for this specification")
208
+
209
+ numeric = sample[[dependent, *exog, *endogenous, *instruments]].astype(float)
210
+ if not np.isfinite(numeric.to_numpy()).all():
211
+ raise ValueError("outcome, regressors and instruments must have finite numeric values")
212
+ # A one-level effect is already spanned by the intercept.
213
+ varying = pd.DataFrame({
214
+ e: pd.Categorical(sample[e]).remove_unused_categories()
215
+ for e in effects if sample[e].nunique() > 1
216
+ }, index=sample.index)
217
+ absorb = absorb_iv and bool(endogenous) and not varying.empty
218
+ totals = rank = None
219
+ if absorb:
220
+ numeric, totals, rank = _absorb_iv(numeric, varying, dependent, exog, endogenous, instruments, cov_type)
221
+ y = numeric[dependent]
222
+ x = numeric.loc[:, list(exog)].copy()
223
+ if not absorb:
224
+ x.insert(0, "const", 1.0)
225
+ terms = (*x.columns, *endogenous)
226
+ if not endogenous and not varying.empty:
227
+ model = AbsorbingLS(y, x, absorb=varying)
228
+ else:
229
+ if endogenous and not varying.empty and not absorb:
230
+ x = pd.concat([x, _effect_indicators(varying, roles)], axis=1)
231
+ endog = numeric[list(endogenous)] if endogenous else None
232
+ excluded = numeric[list(instruments)] if instruments else None
233
+ model = IV2SLS(y, x if x.shape[1] else None, endog, excluded)
234
+
235
+ counts = tuple(int(sample[name].nunique()) for name in clusters)
236
+ cov_options = {}
237
+ if clusters:
238
+ if min(counts) < 2:
239
+ raise ValueError("each cluster column needs at least two groups in the estimation sample")
240
+ # The covariance backend forms joint group IDs by multiplying the
241
+ # two codes. Widen pandas' compact integers before that multiplication.
242
+ cov_options["clusters"] = sample[list(clusters)].apply(
243
+ lambda s: pd.Categorical(s).codes.astype("int64")
244
+ )
245
+ result = model.fit(cov_type=cov_type, **cov_options)
246
+ return FittedRegression(result, dependent, terms, effects, endogenous, instruments, clusters, counts, totals, rank)