Skip to main content

lattab

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

User guide (PDF) · LaTeX source

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

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

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.

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:

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:

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

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

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

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

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
python -m examples.multiple_databases > comparison.tex

The column and fixed-effect layout follows Julia's RegressionTables.jl. Example script · Generated LaTeX table · Dataset examples · Grunfeld data · RegressionTables.jl

Tests

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.

Metadata

Release files for lattab 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lattab 0.2.0
File Size Uploaded Provenance Actions
lattab-0.2.0.tar.gz 204.3 kB Without provenance Details for lattab-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lattab 0.2.0
File Interpreter ABI Platform Actions
lattab-0.2.0-py3-none-any.whl Python 3 none any Details for lattab-0.2.0-py3-none-any.whl

Total release size: 228.3 kB

Release files / lattab-0.2.0.tar.gz

Download URL lattab-0.2.0.tar.gz
Size 204.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9ce4fdc115aae0b3296149e51edeae50a3b8ff11331f3f4ce3312e6f56446090
BLAKE2b-256 checksum
How to use checksums
3edf687d1f90543ee85d7682162ddaa57af51937b8009d788fd4c011ea4aa614
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Release files / lattab-0.2.0-py3-none-any.whl

Download URL lattab-0.2.0-py3-none-any.whl
Size 24.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8f76d1206d268b30b0dd7ca33e4583a6963064c4c6f83db4f172d90e6f7821b5
BLAKE2b-256 checksum
How to use checksums
eb2b200321f5ccad9acfb26fa2830b924cb7332b5a6e3c9c46b4e75d68380337
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Security for lattab 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page