Skip to main content

cleverly

Read the cleverly documentation →

Python 3.11+ License: MIT Status: alpha

cleverly is the Python toolbox for causal studies built on targeted maximum likelihood estimation (TMLE), organized around the causal question before the estimation method.

It is named for TMLE's clever covariate. Even the jokes in this toolbox are targeted.

study design -> typed estimand -> identified effect -> estimation method -> causal result

cleverly supports point and longitudinal treatment settings, influence-curve inference, cross-fitting, diagnostics, sensitivity analysis, and structured persistence. It accepts pandas, polars, Arrow-backed pandas, and pyarrow.Table inputs through narwhals.

Install

Install the core package from PyPI:

python -m pip install cleverly

Add pandas, polars, and plotting support with the all extra. Third-party nuisance estimators such as XGBoost or LightGBM can be installed separately and passed as sklearn-compatible objects:

python -m pip install "cleverly[all]"

Python 3.11 or newer is required. See Installation for a development environment and reproducible version-pinned installs.

Quickstart

Declare the design and the estimand separately, inspect identification, estimate, then assess:

from sklearn.linear_model import LinearRegression, LogisticRegression
from cleverly import ATE, CausalStudy, PointTreatment
from cleverly.datasets import make_linear_ate

frame, truth = make_linear_ate(n=2_000, seed=7)
study = CausalStudy(
    frame,
    design=PointTreatment(
        outcome="Y",
        treatment="A",
        adjustment=("W1", "W2", "W3", "W4"),
    ),
)
effect = study.identify(ATE(reference=0))
print(effect.summary())
result = effect.estimate(
    outcome_learner=LinearRegression(),
    treatment_learner=LogisticRegression(max_iter=1000),
    cross_fit=False,
    random_state=7,
)
print(result.summary())
print(result["ate"].ci, "population ATE:", truth["ate"])
print(result.assess().summary())

Both nuisance functions of make_linear_ate are linear, so these learners are correctly specified. A correctly specified parametric learner needs no cross-fitting, so this fit uses none. Cross-fitting a continuous outcome needs its support declared, because q_bounds=None reads the held-out rows to set the scale. The identified effect states its functional and assumptions before any learner is fit.

Continue with the full quickstart or the analysis workflow.

Documentation

The Sphinx/MyST documentation is published on GitHub Pages and builds from docs/.

section use it for
Getting started installation, first fit, and result basics
Workflow moving from a causal question through identification, estimation, assessment, and reporting
User guide data roles, estimands, learners, methods, longitudinal designs, results, and refusals
Technical reference every implementation family, with theory, citations, local source, external provenance, and evidence
Examples complete point, intervention, longitudinal, and post-fit workflows
Python API generated signatures, attributes, methods, and return types

The development reference contains the roadmap, the architecture invariants, the fast-test and validation-study rules, and the method-benchmarking strategy. The test-enforced evidence manifest lives in the Technical reference.

Implemented analysis families

This table summarizes the package. The technical implementation matrix is the authoritative inventory, and it names the evidence for each row.

family what cleverly ships
point-treatment effects counterfactual means, ATE, ATT, ATC, risk and odds ratios, natural-course means, population-attributable effects, multi-valued treatments, declared missing outcomes and treatments, and controlled direct effects
interventions static, dynamic, and stochastic regimes; continuous modified treatment policies; incremental propensity-score interventions; and point and longitudinal MSM projections
longitudinal outcomes regimen means and contrasts for end-of-study, survival, and competing-risk outcomes
design and inference observation weights, strata, cluster-robust inference, cross-fitting, repeated cross-fitting, CV-TMLE, simultaneous intervals, and bootstrap inference
estimator variants ordinary TMLE, collaborative TMLE, and DR-TMLE, each over its documented compatible estimands
post-fit work positivity, nuisance, and score diagnostics; omitted-variable, E-value, and missingness sensitivity analyses; refutation; variable importance; and trusted whole-result persistence

Roadmap

  • Validate sequential-decision analyses over three to five decisions, and add pre-fit support checks for price policies.
  • Add a long-panel adapter, sequential g-computation and IPW baselines, and two applied tutorials.
  • Add an experimental status and a reason code on each refusal.
  • After the beta, add EP learning and the nested Riesz engine where an analysis needs them.

These are accepted directions, not implemented release claims. The roadmap orders them by milestone. It keeps work that needs new fundamental theory in a separate future grid.

Method configuration

Named shortcuts normalize into immutable configuration groups:

from cleverly import CrossFitting, Inference, ModelSpec, Runtime, TMLEMethod

method = TMLEMethod(
    models=ModelSpec(
        outcome_learner=LinearRegression(), treatment_learner=LogisticRegression(max_iter=1000)
    ),
    cross_fitting=CrossFitting(enabled=False, learner_folds=3),
    inference=Inference(alpha=0.05, simultaneous=False),
    runtime=Runtime(random_state=7, n_jobs=1),
)
result = effect.estimate(method=method)

CrossFitting(enabled=False) here for the reason the quickstart gives. To cross-fit this fit instead, declare the outcome support with Targeting(q_bounds=(lower, upper)), or use a law whose outcome is bounded.

CollaborativeTMLEMethod and DRTMLEMethod select estimator variants without changing the identified causal question. effect.available_methods() reports support and refusal reasons.

Development

uv venv
uv pip install -e ".[dev,docs]"
ruff check .
ruff format --check .
python -m tests.prose
mypy
pytest -q -n auto --dist loadgroup
sphinx-build -W --keep-going -b html docs docs/_build/html

mypy reads its own configuration, which covers src/cleverly and scripts. nox -s docs runs the warning-as-error build in an isolated environment. CI uses this command. The direct call is faster, so the installation command above includes the docs extra.

python -m tests.prose reports on the reader-facing prose. It does not rewrite anything and it does not fail on what it finds. Read each finding, then either change the sentence or record accepted: <reason> against it in tests/prose-report.md. The fast tier fails only on a finding with no recorded judgment, which keeps the decision with the writer. Sentence length is advisory output and carries no row at all. tests/prose.py says which rules were rejected and why.

The fast tier compiles every Python fence and executes the registered reader-facing guides. It also resolves relative links and checks that generated API source represents the root API. Scientific behavior belongs in ordinary fast tests or registered validation studies. Regenerate only the affected studies. Run the relevant checks locally before handoff. A green GitHub Actions CI run is the final merge signal.

CONTRIBUTING.md gives the branch names, the checks each kind of change needs, and the commit style.

Citing

There is no DOI yet. Cite the repository commit used in the analysis and the primary method papers listed in the technical reference and references.

License

MIT License.

The R comparison runners under tests/canonical/ are under the GNU General Public License v3.0. They call reference R packages in the same process, and one package is AGPL-3. No published distribution carries them, so an installed copy of cleverly is MIT alone.

Metadata

Release files for cleverly 0.1.3

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

Source distribution (sdist)

Source distribution for cleverly 0.1.3
File Size Uploaded
cleverly-0.1.3.tar.gz 7.0 MB Details

Built distribution (wheel)

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

Total release size: 8.1 MB

Release files / cleverly-0.1.3.tar.gz

Download URL cleverly-0.1.3.tar.gz
Size 7.0 MB
Tags Source
SHA-256 checksum
How to use checksums
07e68e59868913a73e59cb16b4e00d61e805230d98f25107bb44f796a1a12332
BLAKE2b-256 checksum
How to use checksums
aad3bd63c262450ea97244d05f8941b39ebe04aef4e8f2b4c68d4e339e16ff72
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 14, 2026.

Transparency log

Release files / cleverly-0.1.3-py3-none-any.whl

Download URL cleverly-0.1.3-py3-none-any.whl
Size 1.2 MB
Tags Python 3
SHA-256 checksum
How to use checksums
9cab98eadd92955065153bdf3b2532933a0573a23aa1280978115cee9e2e3f65
BLAKE2b-256 checksum
How to use checksums
82ab4dceed2564097496e6399cc874d90dedd1c7e3f8d49f0ecaaa0a2f18e876
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 14, 2026.

Transparency log

Release history Release notifications | RSS feed

0.1.4

2 release files

This release

0.1.3 This release

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

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