Metadata-Version: 2.5
Name: lattab
Version: 0.2.0
Summary: Convert DataFrames and regression results to LaTeX tables in multiple formats
Project-URL: Repository, https://github.com/jianqih/lattab
Project-URL: Issues, https://github.com/jianqih/lattab/issues
Author-email: Jianqi Huang <jianqi_huang@outlook.com>
License-Expression: MIT
License-File: LICENSE
Keywords: econometrics,latex,linearmodels,regression,statsmodels,tables
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: pandas
Provides-Extra: econometrics
Requires-Dist: linearmodels>=6.1; extra == 'econometrics'
Requires-Dist: pyhdfe>=0.1; extra == 'econometrics'
Requires-Dist: scipy>=1.7; extra == 'econometrics'
Provides-Extra: statsmodels
Requires-Dist: statsmodels; extra == 'statsmodels'
Provides-Extra: test
Requires-Dist: linearmodels>=6.1; extra == 'test'
Requires-Dist: pyhdfe>=0.1; extra == 'test'
Requires-Dist: pytest; extra == 'test'
Requires-Dist: scipy>=1.7; extra == 'test'
Requires-Dist: statsmodels; extra == 'test'
Description-Content-Type: text/markdown

# lattab

Fit OLS and instrumental-variable regressions with fixed effects, and export
DataFrames or fitted models to LaTeX.

[User guide (PDF)](README.pdf) · [LaTeX source](README.tex)

The base package requires pandas. Model fitting uses the optional
`econometrics` extra. The table exporter also accepts fitted statsmodels and
linearmodels results directly.

Tested result types include OLS, WLS, GLS, binary Logit, Probit, MNLogit,
GLM, IV2SLS and PanelOLS. GLM columns name the family in the estimator row,
e.g. `GLM (Poisson)`; a requested statistic that the backend does not carry
(such as Pseudo $R^2$ for GLM) prints blank. Pass a fitted statsmodels MNLogit
result to `regression_table([result])`.
Each non-reference category gets a column. The Outcome row names the comparison
and its reference category. When combining models, supply one `model_names`
entry and one cell in each `extra_rows` row per input model. Model-level entries
and summary statistics repeat across that model's outcome columns. Custom rows accept
plain text such as `R&D` and inline LaTeX math between dollar signs.

## Installation

```bash
python -m pip install -e .                 # table exporters
python -m pip install -e ".[econometrics]" # include regression fitting
```

## Styles

For general-purpose regression tables, use `style="double-outer"`.
Both exporters accept the same styles. The default is `"hline-hline"`.

| name | rules |
|---|---|
| `"double-outer"` | `\hline\hline` at the top and bottom; single `\hline` inside |
| `"hline-hline"` (default) | `\hline\hline` at every separator |
| `"booktabs"` | `\toprule` / `\midrule` / `\bottomrule` |
| `"hline"` | single `\hline` |
| custom | pass your own `RuleStyle(name, top, mid, bottom)` |

## Usage

```python
from lattab import to_latex, regression_table

# DataFrame -> table
to_latex(df, caption="Summary statistics", label="tab:sum",
         style="booktabs", digits=3, rename={"old": "New"})
# missing cells (NaN/None/pd.NA) print blank by default
to_latex(df_with_gaps, na_rep="--")

# Regression results -> table
tex = regression_table(
    [m1, m2],                      # statsmodels results objects
    model_names=[r"$\Delta$ UR", "Model 2"],
    caption="Main results",
    label="tab:reg",
    style="double-outer",
    rename={"d_fedfunds": r"$\Delta$ FFR"},
    notes=r"Standard errors in parentheses. *** $p<0.01$.",
)
```

Inline math in labels, headers, and notes is preserved automatically: text
inside `$...$` spans is passed through verbatim, everything else is escaped.

## Compare OLS, IV and fixed effects

This example estimates three specifications on the same Card wage observations.
The two IV columns instrument years of schooling with proximity to a four-year
college. The last column adds separate effects for metropolitan and Southern
residence in 1966.

```python
from linearmodels.datasets import card
from lattab import fit_regression, regression_table

wages = card.load()
controls = ["exper", "expersq"]
iv = dict(endogenous="educ", instruments="nearc4")
ols = fit_regression(wages, "lwage", ["educ", *controls])
tsls = fit_regression(wages, "lwage", controls, **iv)
tsls_fe = fit_regression(wages, "lwage", controls, fixed_effects=["smsa66", "south66"], **iv)

tex = regression_table(
    [ols, tsls, tsls_fe], model_names=["OLS", "IV", "IV with FE"],
    keep=["educ"], rename={"educ": "Schooling"}, show_first_stage=True,
)
```

Each fit uses observations complete for its own specification, including its
cluster variables. The default is HC0. Pass `clusters="firm"` or
`clusters=["firm", "year"]` for one- or two-way clustering. OLS absorbs the
fixed effects. IV uses explicit indicators by default. For many effect levels,
set `absorb_iv=True` to residualize the outcome, controls, endogenous variables
and instruments together before 2SLS. The absorbed fit reports slopes and keeps
singletons. Its native result uses within-transformed data. The table reports
full and within R-squared separately. Use `fit.first_stage_diagnostics` for
FE-adjusted diagnostics. With unadjusted covariance and three or more varying
effects, the first-stage test reports an asymptotic Wald chi-square. The native result, including IV first-stage
regressions, is available as `tsls.result`.

To compare specifications on the same observations, pass their column names
to `fit_regressions` on a single DataFrame:

```python
from lattab import fit_regressions

specs = [
    dict(dependent="lwage", exog=["educ", "exper", "expersq"]),
    dict(dependent="lwage", exog=["exper", "expersq"],
         endogenous="educ", instruments="nearc4"),
]
ols, iv = fit_regressions(wages, specs, common_sample=True)
```

The common sample keeps rows complete for every specification, including its
instruments, fixed effects and cluster identifiers. The default uses each
model's own complete observations.

Detailed tables label the outcome and estimator rows `Dep. var.` and `Est.`.
Override them with `rename={"Dependent variable": "Outcome", "Estimator": "Method"}`.
Use `rename={"Observations": "Obs.", "$R^2$": "R-sq."}` for regression
summary rows. For a DataFrame summary, use
`to_latex(df.describe(), index=True, rename={"count": "Obs."})`.

Choose the summary rows in display order, rename them, and set their precision independently of the coefficients. For example:

```python
tex = regression_table(
    [ols, tsls, tsls_fe], inference="ci",
    summary_stats=["Observations", "Clusters", "Within $R^2$", "$R^2$"],
    rename={"Observations": "Obs."}, stat_digits={"$R^2$": 2},
)
```

The default `inference="se"` prints standard errors in parentheses. `"ci"` prints the fitted backend's 95% intervals in brackets. Use `summary_stats=[]` to omit the summary block. A requested statistic is blank where unavailable. `"Clusters"` reports counts recorded by `fit_regression`, in the order of its cluster dimensions. `"Within $R^2$"` uses PanelOLS's entity-within measure or AbsorbingLS's measure after removing all absorbed effects. `"$R^2$"` includes effects when the backend supplies an inclusive measure. `"Pseudo $R^2$"` uses the fitted result's pseudo R-squared.

Pass one label per fitted model with `column_groups=["Card", "Card", "Mroz"]` to group adjacent columns. MNLogit model headings span their outcome comparisons automatically. Use `control_groups={"Experience controls": ["exper", "expersq"]}` to summarize fitted terms, including terms hidden by `keep`. A partially included group prints `Partial`; full and absent groups follow `fe_style`.

Tables align coefficients by name and leave absent estimates blank. The fixed
effect rows name each dimension. Use `fe_style="checkmark"` for a tick on
included effects and a blank elsewhere, or `fe_style="yes_no"` for the default
text labels. The checkmark requires `\usepackage{amssymb}` in the paper preamble. `show_first_stage=True` adds the partial
R-squared and joint test of the excluded instruments for each endogenous
variable. The table prints the fitted test's reference distribution, including
the robust Wald chi-square. [First-stage diagnostics](https://bashtage.github.io/linearmodels/iv/iv/linearmodels.iv.results.FirstStageResults.diagnostics.html)

The model R-squared includes fixed effects. In the Card IV column it is
negative because the structural residual sum of squares exceeds the centered
total sum of squares.

### Report average marginal effects

```python
tex = regression_table([binary_logit, multinomial_logit],
                       marginal_effects=True, inference="ci")
```

Pass fitted statsmodels Logit, Probit or MNLogit results. Coefficients become
sample-average derivatives of predicted probabilities, with standard errors or
95% intervals from `get_margeff(at="overall", method="dydx")`. A binary outcome
has one event column. A multinomial outcome has a column per category, including
the reference. Binary regressors use continuous derivatives under this convention.

## Publication layout

### Align numbers on the decimal point

```python
tex = regression_table([m1, m2, m3], siunitx=True)
```

`siunitx=True` typesets model columns as `S` columns so every coefficient,
standard error and statistic aligns on the decimal marker. The column format
is sized to the widest number actually displayed. Stars ride behind the
coefficient; standard errors keep their parentheses and stay aligned with the
coefficient above. The output requires `\usepackage{siunitx}` and begins with a
comment reminding you of it.

### Fit wide and long tables

```python
tex = regression_table([m1, m2, m3, m4, m5, m6], resize=True)   # shrink to \linewidth
tex = regression_table(long_output, longtable=True)             # break across pages
```

`resize=True` wraps the tabular in `\resizebox{\linewidth}{!}{...}`
(requires `\usepackage{graphicx}`). `longtable=True` emits a `longtable` that
repeats the header on every page and carries the caption inside the
environment (requires `\usepackage{longtable}`); the `table` float wrapper and
`position` are ignored. The two options are mutually exclusive.

## Reproduce the five-column table

The example creates three separate temporary SQLite databases from datasets
included with the Python packages, reads each sample with SQL, and fits the
five columns below. It runs offline after installation. The wage models include
experience and its square. The Grunfeld columns of the source data measure
investment, firm value and capital at 1947 prices.

| Database | Specifications | Estimation sample |
| --- | --- | ---: |
| Card | OLS, IV, IV with two location effects | 3,010 per column |
| Mroz | IV with mother's and father's schooling as excluded instruments | 428 observed log wages among 753 records |
| Grunfeld | Firm and year effects, standard errors clustered by firm | 220 firm-years, 11 firms |

```bash
python -m examples.multiple_databases > comparison.tex
```

The column and fixed-effect layout follows Julia's RegressionTables.jl.
[Example script](examples/multiple_databases.py) · [Generated LaTeX table](examples/multiple_databases.tex) · [Dataset examples](https://bashtage.github.io/linearmodels/iv/examples/basic-examples.html) · [Grunfeld data](https://www.statsmodels.org/stable/datasets/generated/grunfeld.html) · [RegressionTables.jl](https://github.com/jmboehm/RegressionTables.jl)

## Tests

```bash
python -m pip install -e ".[test]"
python -m pytest tests/
```

GitHub Actions runs the suite on Python 3.9 through 3.13.

## License

MIT. See [LICENSE](LICENSE).
