experiment-toolkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ """experiment-toolkit: small utilities for online controlled experiments."""
2
+
3
+ from experiment_toolkit.cuped import apply_cuped, compute_theta
4
+ from experiment_toolkit.ratio import ratio_metric_variance
5
+ from experiment_toolkit.sample_size import mde_for_n, sample_size_for_mde
6
+ from experiment_toolkit.sequential import msprt_pvalue
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ __all__ = [
11
+ "apply_cuped",
12
+ "compute_theta",
13
+ "mde_for_n",
14
+ "msprt_pvalue",
15
+ "ratio_metric_variance",
16
+ "sample_size_for_mde",
17
+ ]
@@ -0,0 +1,44 @@
1
+ """Minimal CLI for experiment-toolkit.
2
+
3
+ Example usage:
4
+ experiment-toolkit sample-size --mde 0.02 --sd 1.0
5
+ experiment-toolkit mde --n 10000 --sd 1.0
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import sys
12
+
13
+ from experiment_toolkit.sample_size import mde_for_n, sample_size_for_mde
14
+
15
+
16
+ def main(argv: list[str] | None = None) -> int:
17
+ parser = argparse.ArgumentParser(prog="experiment-toolkit")
18
+ sub = parser.add_subparsers(dest="cmd", required=True)
19
+
20
+ p_ss = sub.add_parser("sample-size", help="compute required per-arm sample size")
21
+ p_ss.add_argument("--mde", type=float, required=True, help="minimum detectable effect")
22
+ p_ss.add_argument("--sd", type=float, required=True, help="outcome standard deviation")
23
+ p_ss.add_argument("--alpha", type=float, default=0.05)
24
+ p_ss.add_argument("--power", type=float, default=0.80)
25
+
26
+ p_mde = sub.add_parser("mde", help="compute detectable effect given sample size")
27
+ p_mde.add_argument("--n", type=int, required=True, help="per-arm sample size")
28
+ p_mde.add_argument("--sd", type=float, required=True)
29
+ p_mde.add_argument("--alpha", type=float, default=0.05)
30
+ p_mde.add_argument("--power", type=float, default=0.80)
31
+
32
+ args = parser.parse_args(argv)
33
+
34
+ if args.cmd == "sample-size":
35
+ n = sample_size_for_mde(args.mde, args.sd, args.alpha, args.power)
36
+ print(f"Required per-arm sample size: {n:,}")
37
+ elif args.cmd == "mde":
38
+ mde = mde_for_n(args.n, args.sd, args.alpha, args.power)
39
+ print(f"Detectable effect (MDE): {mde:.4f}")
40
+ return 0
41
+
42
+
43
+ if __name__ == "__main__":
44
+ sys.exit(main())
@@ -0,0 +1,29 @@
1
+ """CUPED variance reduction — see Deng et al. (2013)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from numpy.typing import ArrayLike
7
+
8
+
9
+ def compute_theta(y: ArrayLike, x: ArrayLike) -> float:
10
+ """Optimal CUPED coefficient theta = Cov(Y, X) / Var(X)."""
11
+ y_arr = np.asarray(y, dtype=float)
12
+ x_arr = np.asarray(x, dtype=float)
13
+ var_x = np.var(x_arr, ddof=1)
14
+ if var_x < 1e-12:
15
+ return 0.0
16
+ return float(np.cov(y_arr, x_arr, ddof=1)[0, 1] / var_x)
17
+
18
+
19
+ def apply_cuped(
20
+ y: ArrayLike,
21
+ x: ArrayLike,
22
+ theta: float | None = None,
23
+ ) -> np.ndarray:
24
+ """Return CUPED-adjusted outcome: Y - theta * (X - mean(X))."""
25
+ y_arr = np.asarray(y, dtype=float)
26
+ x_arr = np.asarray(x, dtype=float)
27
+ if theta is None:
28
+ theta = compute_theta(y_arr, x_arr)
29
+ return y_arr - theta * (x_arr - x_arr.mean())
@@ -0,0 +1,57 @@
1
+ """
2
+ Variance of ratio metrics via the delta method.
3
+
4
+ Real product metrics are often ratios (revenue / session, clicks / impression,
5
+ minutes / DAU). A naive two-sample t-test on per-user ratios is usually wrong
6
+ because the numerator and denominator are correlated.
7
+
8
+ Delta-method approximation for R = E[N] / E[D] with per-user (n_i, d_i):
9
+
10
+ Var(R) ~= (1/mean(d))^2 * ( Var(N) - 2*R*Cov(N,D) + R^2 * Var(D) )
11
+
12
+ Reference: Deng, Knoblich, Lu (2018), "Applying the Delta Method in Metric
13
+ Analytics: A Practical Guide with Novel Ideas."
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import numpy as np
19
+ from numpy.typing import ArrayLike
20
+
21
+
22
+ def ratio_metric_variance(numerator: ArrayLike, denominator: ArrayLike) -> tuple[float, float]:
23
+ """
24
+ Return (ratio_estimate, standard_error) for the per-unit ratio metric.
25
+
26
+ Parameters
27
+ ----------
28
+ numerator : per-unit numerator values (e.g., minutes watched per user)
29
+ denominator : per-unit denominator values (e.g., sessions per user)
30
+
31
+ Returns
32
+ -------
33
+ (ratio, standard_error)
34
+ """
35
+ n = np.asarray(numerator, dtype=float)
36
+ d = np.asarray(denominator, dtype=float)
37
+ if n.shape != d.shape:
38
+ raise ValueError("numerator and denominator must have the same shape")
39
+ if len(n) < 2:
40
+ raise ValueError("need at least 2 observations")
41
+
42
+ mean_n = n.mean()
43
+ mean_d = d.mean()
44
+ if mean_d == 0:
45
+ raise ValueError("mean of denominator is zero; ratio undefined")
46
+
47
+ ratio = mean_n / mean_d
48
+
49
+ # Delta-method variance of the sample ratio.
50
+ var_n = np.var(n, ddof=1)
51
+ var_d = np.var(d, ddof=1)
52
+ cov_nd = np.cov(n, d, ddof=1)[0, 1]
53
+
54
+ var_ratio = (var_n - 2 * ratio * cov_nd + ratio**2 * var_d) / (len(n) * mean_d**2)
55
+ se = float(np.sqrt(max(var_ratio, 0.0)))
56
+
57
+ return float(ratio), se
@@ -0,0 +1,61 @@
1
+ """
2
+ Sample size and MDE calculators for two-sample experiments on continuous
3
+ outcomes. Uses the standard normal approximation (valid for n > ~30 per arm).
4
+
5
+ For a two-sided test at significance alpha and power 1-beta, comparing two
6
+ means with equal per-arm sample size n and pooled standard deviation sigma:
7
+
8
+ n = 2 * sigma^2 * (z_{1-alpha/2} + z_{1-beta})^2 / mde^2
9
+
10
+ where mde is the minimum detectable effect in outcome units.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+
17
+ from scipy import stats
18
+
19
+
20
+ def sample_size_for_mde(
21
+ mde: float,
22
+ std_dev: float,
23
+ alpha: float = 0.05,
24
+ power: float = 0.80,
25
+ two_sided: bool = True,
26
+ ) -> int:
27
+ """Required per-arm sample size to detect `mde` with the given power."""
28
+ if mde <= 0:
29
+ raise ValueError("mde must be positive")
30
+ if std_dev <= 0:
31
+ raise ValueError("std_dev must be positive")
32
+ if not 0 < alpha < 1:
33
+ raise ValueError("alpha must be in (0, 1)")
34
+ if not 0 < power < 1:
35
+ raise ValueError("power must be in (0, 1)")
36
+
37
+ z_alpha = stats.norm.ppf(1 - alpha / 2) if two_sided else stats.norm.ppf(1 - alpha)
38
+ z_beta = stats.norm.ppf(power)
39
+
40
+ n = 2 * std_dev**2 * (z_alpha + z_beta) ** 2 / mde**2
41
+ return math.ceil(n)
42
+
43
+
44
+ def mde_for_n(
45
+ n_per_arm: int,
46
+ std_dev: float,
47
+ alpha: float = 0.05,
48
+ power: float = 0.80,
49
+ two_sided: bool = True,
50
+ ) -> float:
51
+ """Inverse: given a fixed per-arm sample size, return the MDE you can
52
+ detect with the given power."""
53
+ if n_per_arm <= 0:
54
+ raise ValueError("n_per_arm must be positive")
55
+ if std_dev <= 0:
56
+ raise ValueError("std_dev must be positive")
57
+
58
+ z_alpha = stats.norm.ppf(1 - alpha / 2) if two_sided else stats.norm.ppf(1 - alpha)
59
+ z_beta = stats.norm.ppf(power)
60
+
61
+ return (z_alpha + z_beta) * std_dev * (2 / n_per_arm) ** 0.5
@@ -0,0 +1,69 @@
1
+ """
2
+ Always-valid p-values via the mixture Sequential Probability Ratio Test (mSPRT).
3
+
4
+ Reference: Johari, Pekelis, Walsh (2015), "Always Valid Inference: Bringing
5
+ Sequential Analysis to A/B Testing." Netflix and Optimizely both ship variants
6
+ of this in production.
7
+
8
+ The mSPRT mixes SPRTs over a prior on the effect size, yielding a test
9
+ statistic whose 1/statistic gives a p-value valid at any stopping time.
10
+
11
+ For a two-sample z-test with per-arm sample size n, difference of means
12
+ delta_hat, pooled variance sigma^2, and a normal mixing prior N(0, tau^2):
13
+
14
+ Lambda = sqrt( sigma^2 / (sigma^2 + n*tau^2/2) ) *
15
+ exp( n * delta_hat^2 / (2*sigma^2) *
16
+ (n*tau^2/2) / (sigma^2 + n*tau^2/2) )
17
+
18
+ and the always-valid p-value is min(1, 1/Lambda).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import numpy as np
24
+
25
+
26
+ def msprt_pvalue(
27
+ delta_hat: float,
28
+ sigma: float,
29
+ n_per_arm: int,
30
+ tau: float,
31
+ ) -> float:
32
+ """
33
+ Compute an always-valid mSPRT p-value for a two-sample mean comparison.
34
+
35
+ Parameters
36
+ ----------
37
+ delta_hat : observed difference in means (treatment - control)
38
+ sigma : pooled within-arm standard deviation of the outcome
39
+ n_per_arm : per-arm sample size at the moment of the peek
40
+ tau : standard deviation of the mixing prior on the true effect
41
+
42
+ Returns
43
+ -------
44
+ always-valid p-value, in [0, 1].
45
+ """
46
+ delta_hat = float(delta_hat)
47
+ sigma = float(sigma)
48
+ n_per_arm = int(n_per_arm)
49
+ tau = float(tau)
50
+
51
+ if sigma <= 0:
52
+ raise ValueError("sigma must be positive")
53
+ if n_per_arm <= 0:
54
+ raise ValueError("n_per_arm must be positive")
55
+ if tau <= 0:
56
+ raise ValueError("tau must be positive (the prior must be proper)")
57
+
58
+ sigma2 = sigma**2
59
+ # Variance of delta_hat under the null: V = 2*sigma^2 / n_per_arm
60
+ v = 2 * sigma2 / n_per_arm
61
+ shrinkage = tau**2 / (v + tau**2)
62
+
63
+ log_lambda = (
64
+ 0.5 * np.log(v / (v + tau**2))
65
+ + (delta_hat**2 / (2 * v)) * shrinkage
66
+ )
67
+ # p = min(1, 1 / Lambda) => -log(p) = min(0, log(Lambda))
68
+ p = float(min(1.0, np.exp(-log_lambda)))
69
+ return p
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: experiment-toolkit
3
+ Version: 0.1.0
4
+ Summary: Small, well-tested utilities for online controlled experiments: sample size, CUPED, sequential testing, delta-method variance.
5
+ Project-URL: Homepage, https://github.com/wavde/experiment-toolkit
6
+ Project-URL: Issues, https://github.com/wavde/experiment-toolkit/issues
7
+ Author: Tejas Wavde
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 Tejas Wavde
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: ab-testing,causal-inference,experimentation,statistics
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Science/Research
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3
35
+ Classifier: Programming Language :: Python :: 3.10
36
+ Classifier: Programming Language :: Python :: 3.11
37
+ Classifier: Programming Language :: Python :: 3.12
38
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
39
+ Requires-Python: >=3.10
40
+ Requires-Dist: numpy>=1.24
41
+ Requires-Dist: scipy>=1.10
42
+ Provides-Extra: dev
43
+ Requires-Dist: mypy>=1.8; extra == 'dev'
44
+ Requires-Dist: pytest>=7; extra == 'dev'
45
+ Requires-Dist: ruff>=0.3; extra == 'dev'
46
+ Description-Content-Type: text/markdown
47
+
48
+ # experiment-toolkit
49
+
50
+ > Small, well-tested utilities for online controlled experiments.
51
+
52
+ ![CI](https://github.com/wavde/experiment-toolkit/actions/workflows/ci.yml/badge.svg)
53
+ [![PyPI](https://img.shields.io/pypi/v/experiment-toolkit.svg)](https://pypi.org/project/experiment-toolkit/)
54
+ [![Python](https://img.shields.io/pypi/pyversions/experiment-toolkit.svg)](https://pypi.org/project/experiment-toolkit/)
55
+ ![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)
56
+
57
+ ## What's inside
58
+
59
+ | Module | Purpose |
60
+ |--------|---------|
61
+ | `sample_size` | Required per-arm sample size for a given MDE, and the inverse |
62
+ | `cuped` | Deng et al. (2013) CUPED variance reduction |
63
+ | `ratio` | Delta-method variance for ratio metrics (revenue/session, etc.) |
64
+ | `sequential` | mSPRT always-valid p-values for peeking-robust experiments |
65
+
66
+ Every function is tested, typed, and has a reference to the paper it implements.
67
+
68
+ ## Install
69
+
70
+ ```bash
71
+ pip install experiment-toolkit
72
+ ```
73
+
74
+ Or from source:
75
+
76
+ ```bash
77
+ pip install git+https://github.com/wavde/experiment-toolkit.git
78
+ ```
79
+
80
+ ## Quick start
81
+
82
+ ```python
83
+ from experiment_toolkit import sample_size_for_mde, apply_cuped, msprt_pvalue
84
+
85
+ # How many users do I need per arm to detect a 2% lift (sd=1.0)?
86
+ n = sample_size_for_mde(mde=0.02, std_dev=1.0, alpha=0.05, power=0.80)
87
+ # ~39,000 per arm
88
+
89
+ # Apply CUPED with a pre-experiment covariate
90
+ y_adj = apply_cuped(y, pre_period_y)
91
+
92
+ # Always-valid p-value — safe to peek
93
+ p = msprt_pvalue(delta_hat=0.015, sigma=1.0, n_per_arm=5000, tau=0.05)
94
+ ```
95
+
96
+ ## CLI
97
+
98
+ The CLI wraps `sample-size` and `mde`. The other modules (`cuped`, `ratio`, `sequential`) are library-only.
99
+
100
+ ```bash
101
+ experiment-toolkit sample-size --mde 0.02 --sd 1.0
102
+ # Required per-arm sample size: 39,244
103
+
104
+ experiment-toolkit mde --n 10000 --sd 1.0
105
+ # Detectable effect (MDE): 0.0396
106
+ ```
107
+
108
+ ## Development
109
+
110
+ ```bash
111
+ pip install -e ".[dev]"
112
+ pytest
113
+ ruff check .
114
+ ```
115
+
116
+ ## References
117
+
118
+ - Deng, Xu, Kohavi, Walker (2013) — CUPED
119
+ - Deng, Knoblich, Lu (2018) — Delta Method in Metric Analytics
120
+ - Johari, Pekelis, Walsh (2015) — Always Valid Inference
121
+ - Kohavi, Tang, Xu (2020) — *Trustworthy Online Controlled Experiments*
122
+
123
+ ## License
124
+
125
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ experiment_toolkit/__init__.py,sha256=KzLIFU9TeQFaYYgt3VcxHAkeoXced8RqpKiY89iIxaw,501
2
+ experiment_toolkit/cli.py,sha256=mcCe2my7tiTkdbLdy17lUvV9WobfYB6kWwKt0AoBtkI,1618
3
+ experiment_toolkit/cuped.py,sha256=MbrEx0a_bS0dlOPrA6FBRmBT8lcTecDKl2Tio07EkHY,852
4
+ experiment_toolkit/ratio.py,sha256=8pE8HwhoxvxV4U5rNs7JZAb_tttXSSIOUsNFEmGphyA,1798
5
+ experiment_toolkit/sample_size.py,sha256=hpC67qHnHj54tmvv89nckC-k-CTX1ZB_J2kx0HkV5Hw,1839
6
+ experiment_toolkit/sequential.py,sha256=NOIzdJTq2vf-TSZIa-20j34BXhR5owE5g5Czfh_i464,2129
7
+ experiment_toolkit-0.1.0.dist-info/METADATA,sha256=i4ipRPD-tCB-QIpu1KkHf_MoS6l5c4eje890cbraH9M,4543
8
+ experiment_toolkit-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
9
+ experiment_toolkit-0.1.0.dist-info/entry_points.txt,sha256=dE4b0Iz05GgJQSEhwQoWlttrxJqncY40ncX1ZlC58-o,67
10
+ experiment_toolkit-0.1.0.dist-info/licenses/LICENSE,sha256=ogBOvR3xaFA75eMZ7rl2ImlnViqXomYGXPdrKp8FJkc,1068
11
+ experiment_toolkit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ experiment-toolkit = experiment_toolkit.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tejas Wavde
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.