Skip to main content

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

cleverly

PyPI Python 3.11+ CI License: MIT

cleverly estimates what a treatment, an offer, or a policy did, from data where nobody assigned it at random, with a confidence interval for each answer. It adjusts for the confounders you recorded, mostly with targeted maximum likelihood estimation (TMLE). Afterward it checks how strong a missing confounder would have to be to change the result. Read the documentation, or start with a complete analysis.

Releases use 0.2.N versions, and the public API can still change between them. Pin a version for reproducible work.

Key features

  • One-time treatments: average effects for everyone, the treated, or the untreated, as a difference, risk ratio, or odds ratio, with missing outcomes and treatments handled.
  • Effects that vary with baseline columns such as age: declared curves with intervals, or a flexible curve (the EP learner) without them.
  • Policies: treating by a rule, following a learned rule, raising the chance of treatment, or shifting a dose.
  • Treatments over time, including time until an event with competing events such as death.
  • Out-of-fold model fitting for flexible machine-learning models, with sampling weights and clustered data.
  • Checks after the fit: overlap, attempts to break the result, and sensitivity to a missing confounder.
  • Refusals instead of approximations: a request the library cannot answer correctly fails before any model is fit, and the error says why.
  • Other estimators for comparison or special cases, such as collaborative TMLE and the parametric g-formula.
  • pandas, polars, and pyarrow.Table inputs, through narwhals.

The technical reference lists every method with its source papers and evidence.

Install

python -m pip install cleverly          # Python 3.11 or newer
python -m pip install "cleverly[all]"   # adds pandas, polars, and plotting

The installation guide covers other learners, development installs, and version pinning.

Quick start

Simulated data with a true average effect of 1.5:

import numpy as np
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)

# 1. Describe the data: the outcome, the treatment, and the confounders to adjust for.
study = CausalStudy(
    frame,
    design=PointTreatment(
        outcome="Y",
        treatment="A",
        adjustment=("W1", "W2", "W3", "W4"),
    ),
)

# 2. Name the question: the average effect of A = 1 compared with A = 0 (ATE).
#    The summary lists the conditions the answer rests on and the methods that can fit it.
effect = study.identify(ATE(reference=0))
print(effect.summary())

# 3. Fit the outcome model and the treatment model, then apply the correction step.
result = effect.estimate(
    outcome_learner=LinearRegression(),
    # An unpenalized logistic regression, which matches how the data were simulated.
    treatment_learner=LogisticRegression(C=np.inf, max_iter=1000),
    cross_fit=False,
    random_state=7,
)
print(result.summary())
# The truth is known only because the data are simulated.
print(result["ate"].ci, "population ATE:", truth["ate"])

# 4. Check the fit and how sensitive the answer is to a missing confounder.
print(result.assess().summary())

The estimate is 1.513 with a 95% interval from 1.422 to 1.603, which contains the truth:

                            Effect estimate (TMLE)
==============================================================================
Question:      average effect of A on   Rows:                            2,000
               Y (1 compared with 0)    Treated share:                   0.506
Outcome:       Y (continuous)           Out-of-fold predictions:            no
Adjusted for:  W1, W2, W3, W4           Outcome model:       linear regression
Method:        targeted maximum         Treatment model:   logistic regression
               likelihood (TMLE)        Probability limits:  [0.01471, 0.9853]
==============================================================================
      estimate   std. error           95% CI    p-value
------------------------------------------------------------------------------
ate      1.513        0.046   [1.422, 1.603]    <0.0001
==============================================================================

The question summary lists the conditions the answer rests on: a well-defined treatment, no interference between people, no missing confounder, and overlap (every kind of person had some chance of each treatment). The data cannot confirm the first three.

The two models here match how the data were simulated, so cross_fit=False is safe. On your own data, use flexible models and keep the default out-of-fold fitting; a continuous outcome then needs Targeting(q_bounds=(lower, upper)). The full quickstart explains the settings. The assessment's E-value of 3.52 means a missing confounder would need a risk ratio of 3.52 with both treatment and outcome to explain the effect away.

effect.available_methods() lists the estimators that can answer the question and why the others cannot; the methods and learners guide shows how to configure them.

Examples

Each example uses simulated data with a known answer, except the last (real birth records).

The examples index lists them all.

How cleverly is tested

More than 100 registered simulation studies check the shipped methods on data with a known answer: whether estimates center on the truth and 95% intervals cover it as often as they should. Where an established package computes the same quantity (R tmle, tmle3, ltmle, lmtp, drtmle, ctmle, survtmle; Python zEpid and EconML), the study compares answers too. Some comparisons have not run yet, and those pages say so. A result is marked experimental when no study covers its setup. The validation grid lists every study.

Documentation

  • Getting started: install, a first fit, and how to read a result.
  • Workflow: one analysis from the question to the report.
  • User guide: data, questions, models, methods, treatments over time, results, and refusals.
  • Examples: complete analyses to adapt.
  • Technical reference: for statisticians, the exact quantities, conditions, papers, and evidence behind each method.
  • Python API: every public object and its signature.

Contributing

Report bugs and questions on the issue tracker. See CONTRIBUTING.md for setup, checks, and commit style.

Citing

There is no DOI yet. Cite the version or commit you used and the method papers listed in the technical reference.

License

MIT. The R comparison runners under tests/canonical/ are GPL-3.0 because they call AGPL-3 R packages in-process; they are not distributed, so an installed cleverly is MIT alone.

Metadata

Release files for cleverly 0.2.5

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.2.5
File Size Uploaded Provenance Actions
cleverly-0.2.5.tar.gz 11.5 MB With provenance Details for cleverly-0.2.5.tar.gz

Built distribution (wheel)

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

Total release size: 14.3 MB

Release files / cleverly-0.2.5.tar.gz

Download URL cleverly-0.2.5.tar.gz
Size 11.5 MB
Tags Source
SHA-256 checksum
How to use checksums
2725302d853529f0255f073e70f6a55694149e116f17345a28ef2e556ec99a14
BLAKE2b-256 checksum
How to use checksums
ae8630bc8aba53a1d9bbc266f4e3b0bb7d9b38ac76c92c5d705f7570ebe9856c
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 Nov 14, 2026.

Transparency log

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

Download URL cleverly-0.2.5-py3-none-any.whl
Size 2.8 MB
Tags Python 3
SHA-256 checksum
How to use checksums
c50af3561ee5919eae2c9bdbd0a6d97c92e715ec9eac997723a7c86d1b767045
BLAKE2b-256 checksum
How to use checksums
059d373257ac7e0086381a4f343c7d85e35fcb76845bbced3acd6b4f5c2fcfe1
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 Nov 14, 2026.

Transparency log

Security for cleverly 0.2.5

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 cleverly-0.2.5.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 14, 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