Skip to main content

A Toolbox for Meta-Analysis and APA-Compliant Reporting

About

This toolbox is a curated collection of utilities I frequently use for statistical analysis and nicely reporting research findings in accordance with APA standards. While some of the included libraries may be slightly outdated, they remain functional and reliable, making them my go-to tools.

Install

pip install apatools

Requires Python 3.10 or newer. The latest development version is available with pip install git+https://github.com/ellariel/apatools.git.

The base installation is light: it contains apatools.calc and apatools.format and needs only numpy and scipy. Every other module has its own heavier dependencies and is installed through an extra of the same name:

install module brings in
pip install apatools calc, format numpy, scipy
pip install "apatools[lm]" lm pandas, statsmodels, lxml
pip install "apatools[slm]" slm pandas, statsmodels, spreg, libpysal
pip install "apatools[plm]" plm pandas, spreg, libpysal, patsy
pip install "apatools[sem]" sem pandas, semopy
pip install "apatools[psm]" psm pandas, psmpy
pip install "apatools[lib]" lib pandas, statsmodels
pip install "apatools[linearmodels]" plm with the linearmodels backend the plm extra and linearmodels
pip install "apatools[graphviz]" sem_plot path diagrams the sem extra and the Python package graphviz; the Graphviz executables must also be installed and on the PATH
pip install "apatools[krippendorff]" lib.krippendorffs_alpha the lib extra and krippendorff (GPL-3.0-or-later)
pip install "apatools[all]" everything all of the above

Extras can be combined, e.g. pip install "apatools[lm,plm]". Importing a module without its extra gives an ImportError that names the extra to install.

Content and examples

  • apatools.calc - a basic module for statistical conversions and bootstrapping
  • apatools.format - simple APA-compliant formatting functions for numerical results
  • apatools.lm (extra lm) - a module offering wrapper functions for statsmodels, streamlining the fitting of OLS, RLM, and GLM models, as well as generating detailed tables
  • apatools.slm (extra slm) - a module offering wrapper functions for spreg, streamlining the fitting of OLS, spatial lag (SLM) and spatial error (SEM) models, as well as generating detailed tables
  • apatools.plm (extra plm) - a module offering wrapper functions for panel regressions (pooled, fixed and random effects, with optional spatial lag/error terms) with spreg or, optionally, linearmodels, as well as generating detailed tables and specification tests
  • apatools.sem (extra sem) - a module for performing structural equation modeling, complete with result reporting and path diagram visualization
  • apatools.psm (extra psm) - a module for performing propensity score matching, complete with effect sizes reporting
  • apatools.lib (extra lib) - assorted helpers: inter-rater agreement (Fleiss' kappa, Krippendorff's alpha), pooling and comparing correlations, HTMT ratio, Gini coefficient

apatools.calc

This module provides essential conversion functions alongside tools for bootstrapping means, confidence intervals, and related statistics. It includes a comprehensive set of approximate conversion functions for bidirectional transformations between t-, z-, and F-statistics, as well as conversions involving Cohen's r, Cohen's d, and p-values.

Conversion examples

from apatools.calc import cohen_r_from_z, cohen_d_from_z
# calculation Cohen's r and d from z-score:
# there is also a shorten aliases r_from_z and d_from_z
z = -1.472
r = cohen_r_from_z(z) # r = -0.9
d = cohen_d_from_z(z) # d = -4.1
from apatools.calc import p_from_r
# calculation p-value for Cohen's r  or correlation coefficient:
r = -0.79
n = 100
p = p_from_r(r, n) # p = 0.0

Bootstrap examples

import numpy as np
from apatools.calc import bootstrap
# bootstraping confidence intervals for a mean value:
cil, m, cir = bootstrap([1, 2, 3, 4, 5, 6, 7, 8, 9],
        func=np.mean,
        n_rep=1000) # cil = 3.3, m = 5.0, cir = 6.7
from apatools.calc import bootstrap
from scipy.stats import spearmanr
# bootstraping value for Spearman's correlation:
def func(*args):
    return spearmanr(*args).statistic

_, m, _ = bootstrap(
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [4, 5, 8, 4, 5, 6, 7, 8, 9],
    func=func,
    n_rep=1000) # m = 0.75

apatools.lm

Fitting of OLS, RLM, GLM, QuantReg and MixedLM models using statsmodels. Arguments for the model constructor and for .fit() are passed as <model>_<stage>_<argument>: the model prefix (ols_, rlm_, glm_, qlm_, mlm_) followed by model_ (constructor) or fit_ (the .fit() call), e.g. ols_fit_cov_type, glm_model_family, rlm_model_M.

Specific parameters:

  • qlm_fit_q – adds a quantile for QuantReg, e.g. 0.5
  • mlm_model_groups – adds a grouping variable for MixedLM, e.g. country
  • vif - adds a VIF column to the metrics dictionary and reported table
  • formula - a formula string as in statsmodels
  • pred_r_sq - calculates predicted R²
from apatools.lm import lm, lm_report
results, metrics = lm(
        data,
        y, x,
        model=["ols", "rlm", "glm"],
        verbose=True,
        vif=True,
        pred_r_sq=True,
        ols_fit_cov_type="HC1",
        rlm_model_M=sm.robust.norms.RamsayE(),
        glm_model_family=sm.families.Gaussian(),
    )
results_rep = lm_report(results, metrics)
print(results_rep, metrics)

apatools.slm

Fitting of OLS, SLM, and SEM spatial models using spreg. Arguments for the spreg model constructor are passed as <model>_model_<argument> with the model prefix ols_, slm_ or sem_, e.g. ols_model_spat_diag.

Specific parameters:

  • w - a spatial matrix, created with libpysal; its rows must correspond to the rows of data (rows dropped because of NAs are removed from w automatically)
  • formula - a formula string as in statsmodels
  • pred_metrics - adds leave-one-out prediction metrics (R²pred, MAEpred, MADpred) to the metrics dictionary and the reported table. Every observation is held out in turn, the model and the weights are refitted without it, and the held-out value is predicted: x·β for OLS and SEM, and ρ·(Wy)ᵢ + x·β for SLM (observed neighbour values enter through the weights, so SLM is not strictly comparable with the other two). It needs one fit per observation and model; for large samples pass e.g. slm_model_method="LU".
  • pred_exclude_neighbors - with pred_metrics: also remove the neighbours of the held-out observation from the training sample

Caveat: plain leave-one-out is optimistic for spatial data. The neighbours of the held-out observation stay in the training sample and are correlated with it, so R²pred overestimates how well the model predicts a new, unseen region. pred_exclude_neighbors=True gives a more honest (slightly pessimistic) estimate; it may create islands in the training weights, which is reported with a warning.

from apatools.slm import slm, slm_report
results, metrics = slm(
        data,
        y, x, w,
        model=["ols", "slm", "sem"],
        verbose=True,
        ols_model_spat_diag=True,
        ols_model_nonspat_diag=True,
        pred_metrics=True,  # leave-one-out R²pred etc. (optimistic, see the caveat)
        pred_exclude_neighbors=True,  # leave the neighbourhood out as well
    )
results_rep = slm_report(results, metrics)
print(results_rep, metrics)

apatools.plm

Panel regressions (pooled, fixed effects, random effects, optionally with a spatial lag or spatial error) in the same format as lm and slm. Two backends: spreg (default; all models) and the optional linearmodels (pip install "apatools[linearmodels]"; non-spatial models, adds e.g. clustered standard errors and two-way fixed effects).

Data are an ordinary long data frame with an entity and a time column (or an (entity, time) index). The module checks that the panel is balanced, aligns the entities with the rows of the spatial weights w (the entity values must be the ids w.id_order, otherwise pass w_ids) and brings the rows into the layout spreg needs, so the row order of your data does not matter.

Models (model=): pooled, fe, re (both backends), slm_fe, slm_re, sem_pooled, sem_fe, sem_re, sem_pooled_gm, sem_re_gm (spreg: spatial lag / spatial error with ML or GMM estimation). sem_re (ML) failed with older numpy/scipy versions (numpy 2.0-2.2, scipy 1.13-1.15) in spreg 1.9.0, but worked with recent ones; sem_re_gm worked everywhere.

Specific parameters:

  • entity, time - columns (or index levels) identifying entity and period; balance="drop" drops entities that are not observed in all periods instead of raising an error
  • backend - "spreg" (default) or "linearmodels"
  • slx_lags - number of spatial lags of the predictors (spreg; slx_lags=1 gives a Durbin-type model)
  • <model>_model_<arg> / <model>_fit_<arg> - arguments for the model class / .fit(), e.g. slm_fe_model_method="LU", or for linearmodels fe_fit_cov_type="clustered", fe_fit_cluster_entity=True, fe_model_time_effects=True
  • pred_metrics - adds leave-one-group-out prediction metrics (R²pred, MAEpred, MADpred). Leaving out single observations is not meaningful in panels, so whole entities (pred_group="entity", predicts a new entity; not possible for fixed-effects models) or whole periods (pred_group="time") are held out, the model and the weights are refitted, and the held-out rows are predicted (x·β, plus ρ·Wy for spatial lag and the estimated entity effect for fixed effects). With spatial data the neighbours of a held-out entity stay in the training sample, which is optimistic; pred_exclude_neighbors=True removes them as well (see the caveat for slm).
from apatools.plm import plm, plm_report, plm_tests
results, metrics = plm(
        data,
        "y", ["x1", "x2"],
        w=w,
        entity="county", time="year",
        model=["pooled", "fe", "re", "slm_fe"],
        verbose=True,
        pred_metrics=True,
        pred_group="time",
    )
results_rep = plm_report(results, metrics)
print(results_rep, metrics)
print(plm_tests(results))  # Hausman, Mundlak, F test of entity effects, spatial LM tests

plm_tests() returns a tidy table: Hausman test (FE vs RE; undefined when V_fe - V_re is not positive definite, which is typical when the effects are correlated with the predictors), the regression-based Mundlak test (robust to that problem), the F test of entity effects, and, for pooled spreg models with weights, the Baltagi-Song-Koh and Anselin LM tests for random effects and spatial dependence.

Notes: R² is R²within for fixed effects, R²overall for random effects with linearmodels, R²pseudo (squared correlation of observed and predicted y) for spatial and spreg random-effects models and the plain R² for pooled OLS. spreg's PanelFE reports residuals and a pseudo R² that ignore the fixed effects and uses N·T - N instead of N·T - N - k degrees of freedom for the standard errors (slightly too small); the within R², the residual statistics and the F test use the correct values and agree with linearmodels. AIC/BIC from spreg do not count the fixed effects.

apatools.sem

Structural equation modeling implemented with semopy. The module provides modeling function sem(), formatting sem_report() and plotting sem_plot() functions.

from apatools.sem import sem, sem_report, sem_plot
stats, metrics, model = sem(
        data,
        formula,
        method="MLW",  # MLW ULS GLS FIML DWLS WLS
        return_model=True,
    )
results_rep = sem_report(stats, metrics)
print(results_rep)
fig = sem_plot(
        stats,
        save_to_file="fig.png",
        return_fig=True,
    )

apatools.psm

Propensity score matching implemented with psmpy. The module provides modeling function psm() and psm_effect_size() to report differences.

from apatools.psm import psm, psm_effect_size
results, model = psm(
        data,
        treatment_variable='vs',
        include_vars=['age', 'gender'],
        balance=True,
        replacement=True,
        return_model=True,
    )
print(psm_effect_size(model))

apatools.format

Simple APA-compliant functions for formatting numeric results, such as formatting R and r values, p-values, etc.

Formatting examples

from apatools.format import get_stars, format_p, format_r
# formatting numeric results
r = format_r(0.999, keep_spaces=True, use_letter="r", no_equals=False) # r = 'r = 1.'
r = format_r(0.011, keep_spaces=True, use_letter="R", no_equals=False) # r = 'R = .01'
p = format_p(0.0004, use_letter="p", keep_spaces=True, no_equals=False) # p = 'p < .001'
s = get_stars(0.04, p001="***", p01="**", p05="*", p10="⁺", p_="") # s = '*'

Sources and references

Note that APA citations of the original packages can be imported from each specific implementation as follows:

# e.g., for psmpy
from apatools.psm import CITATION
print(CITATION.APA) 

License

MIT, see LICENSE. Note that the optional dependency krippendorff is licensed under GPL-3.0-or-later.

Metadata

Release files for apatools 0.1.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 apatools 0.1.0
File Size Uploaded Provenance Actions
apatools-0.1.0.tar.gz 73.4 kB With provenance Details for apatools-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 127.3 kB

Release files / apatools-0.1.0.tar.gz

Download URL apatools-0.1.0.tar.gz
Size 73.4 kB
Tags Source
SHA-256 checksum
How to use checksums
94af55f215122f6ae9ebc1d6658711acb1e68b81ddeed1e67e505adf91f3d41b
BLAKE2b-256 checksum
How to use checksums
365ed5b9ed5147689e56f2a9dae4b9fc9aa5d3d248382f8fc3c067fde83cf23e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / apatools-0.1.0-py3-none-any.whl

Download URL apatools-0.1.0-py3-none-any.whl
Size 53.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
338f54320c5aa73339893d28b900fcfc7116c94f90d571d244523c8b6e27d5c3
BLAKE2b-256 checksum
How to use checksums
4870da6ad89c9177eb4f1913341ec7a092ccfc7a0479267ef5c8e0b3f64ebf6a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for apatools 0.1.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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for apatools-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

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.

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