experiment-toolkit 0.1.0__tar.gz

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,28 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.10", "3.11", "3.12"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ cache: pip
21
+ - name: Install
22
+ run: |
23
+ python -m pip install --upgrade pip
24
+ pip install -e ".[dev]"
25
+ - name: Lint
26
+ run: ruff check .
27
+ - name: Test
28
+ run: pytest
@@ -0,0 +1,42 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ build:
9
+ name: Build distribution
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: "3.12"
16
+ - name: Install build tools
17
+ run: python -m pip install --upgrade build
18
+ - name: Build sdist and wheel
19
+ run: python -m build
20
+ - name: Upload artifacts
21
+ uses: actions/upload-artifact@v4
22
+ with:
23
+ name: dist
24
+ path: dist/
25
+
26
+ publish:
27
+ name: Publish to PyPI
28
+ needs: build
29
+ runs-on: ubuntu-latest
30
+ environment:
31
+ name: pypi
32
+ url: https://pypi.org/p/experiment-toolkit
33
+ permissions:
34
+ id-token: write # required for OIDC trusted publishing
35
+ steps:
36
+ - name: Download artifacts
37
+ uses: actions/download-artifact@v4
38
+ with:
39
+ name: dist
40
+ path: dist/
41
+ - name: Publish to PyPI
42
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .Python
4
+ .venv/
5
+ venv/
6
+ .env
7
+ *.egg-info/
8
+ build/
9
+ dist/
10
+ .pytest_cache/
11
+ .ruff_cache/
12
+ .mypy_cache/
13
+ .coverage
14
+ .DS_Store
15
+ .idea/
16
+ .vscode/
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-04-19
9
+
10
+ ### Added
11
+ - `sample_size`: two-sample sample size / MDE / power calculations.
12
+ - `cuped`: variance reduction via pre-experiment covariate (Deng et al. 2013).
13
+ - `ratio`: delta-method variance for ratio metrics (Deng et al. 2018).
14
+ - `sequential`: always-valid mSPRT sequential test (Johari et al. 2017).
15
+ - `cli`: command-line wrapper exposing `sample-size` and `mde` subcommands.
16
+
17
+ ### Notes
18
+ - Tested on Python 3.10, 3.11, 3.12.
19
+ - mSPRT formula uses `V = 2σ²/n_per_arm` with shrinkage `τ²/(V+τ²)` — a corrected
20
+ variant of an earlier draft that had an off-by-2 in the prior scaling and
21
+ inflated Type-I error to ~17% at α=0.05. Empirical Type-I error of the
22
+ shipped formula is ≤ α under H0; see `tests/test_toolkit.py::test_msprt_always_valid_type1_error`.
@@ -0,0 +1,55 @@
1
+ # Contributing
2
+
3
+ Thanks for your interest. This package is maintained but small, so scope is narrow.
4
+
5
+ ## Development setup
6
+
7
+ ```bash
8
+ git clone https://github.com/wavde/experiment-toolkit.git
9
+ cd experiment-toolkit
10
+ python -m venv .venv
11
+ source .venv/bin/activate # or .venv\Scripts\activate on Windows
12
+ pip install -e ".[dev]"
13
+ ```
14
+
15
+ ## Before opening a PR
16
+
17
+ ```bash
18
+ ruff check .
19
+ pytest -q
20
+ ```
21
+
22
+ Both must pass. CI runs these on Python 3.10, 3.11, and 3.12.
23
+
24
+ ## What I'll accept
25
+
26
+ - Bug fixes with a regression test
27
+ - Numerically stable reformulations of existing methods
28
+ - Narrow feature additions **with a paper reference** (e.g., a new variance-reduction technique from a published paper)
29
+ - Documentation improvements
30
+ - New CLI subcommands that wrap existing library functions
31
+
32
+ ## What I won't accept (without prior discussion)
33
+
34
+ - New heavy dependencies (we stay lean on `numpy` + `scipy`)
35
+ - Methods that reinvent things `scipy.stats` or `statsmodels` already do well
36
+ - Scope expansion into ML / forecasting / dashboards — this package is scoped to **inference for online experiments**
37
+
38
+ ## Style
39
+
40
+ - Type hints on every public function
41
+ - Docstrings state the contract (inputs, outputs, failure modes), not just the function name
42
+ - Magic numbers go into named constants
43
+ - Each public function gets a known-answer test (not just "it runs")
44
+
45
+ ## Bug reports
46
+
47
+ Include:
48
+ 1. A minimal reproducer (fewer than 20 lines)
49
+ 2. Expected vs observed output
50
+ 3. Package version (`python -c "import experiment_toolkit; print(experiment_toolkit.__version__)"`)
51
+ 4. Python version
52
+
53
+ ## License
54
+
55
+ By contributing you agree your work is released under the MIT license (see `LICENSE`).
@@ -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.
@@ -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,78 @@
1
+ # experiment-toolkit
2
+
3
+ > Small, well-tested utilities for online controlled experiments.
4
+
5
+ ![CI](https://github.com/wavde/experiment-toolkit/actions/workflows/ci.yml/badge.svg)
6
+ [![PyPI](https://img.shields.io/pypi/v/experiment-toolkit.svg)](https://pypi.org/project/experiment-toolkit/)
7
+ [![Python](https://img.shields.io/pypi/pyversions/experiment-toolkit.svg)](https://pypi.org/project/experiment-toolkit/)
8
+ ![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)
9
+
10
+ ## What's inside
11
+
12
+ | Module | Purpose |
13
+ |--------|---------|
14
+ | `sample_size` | Required per-arm sample size for a given MDE, and the inverse |
15
+ | `cuped` | Deng et al. (2013) CUPED variance reduction |
16
+ | `ratio` | Delta-method variance for ratio metrics (revenue/session, etc.) |
17
+ | `sequential` | mSPRT always-valid p-values for peeking-robust experiments |
18
+
19
+ Every function is tested, typed, and has a reference to the paper it implements.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install experiment-toolkit
25
+ ```
26
+
27
+ Or from source:
28
+
29
+ ```bash
30
+ pip install git+https://github.com/wavde/experiment-toolkit.git
31
+ ```
32
+
33
+ ## Quick start
34
+
35
+ ```python
36
+ from experiment_toolkit import sample_size_for_mde, apply_cuped, msprt_pvalue
37
+
38
+ # How many users do I need per arm to detect a 2% lift (sd=1.0)?
39
+ n = sample_size_for_mde(mde=0.02, std_dev=1.0, alpha=0.05, power=0.80)
40
+ # ~39,000 per arm
41
+
42
+ # Apply CUPED with a pre-experiment covariate
43
+ y_adj = apply_cuped(y, pre_period_y)
44
+
45
+ # Always-valid p-value — safe to peek
46
+ p = msprt_pvalue(delta_hat=0.015, sigma=1.0, n_per_arm=5000, tau=0.05)
47
+ ```
48
+
49
+ ## CLI
50
+
51
+ The CLI wraps `sample-size` and `mde`. The other modules (`cuped`, `ratio`, `sequential`) are library-only.
52
+
53
+ ```bash
54
+ experiment-toolkit sample-size --mde 0.02 --sd 1.0
55
+ # Required per-arm sample size: 39,244
56
+
57
+ experiment-toolkit mde --n 10000 --sd 1.0
58
+ # Detectable effect (MDE): 0.0396
59
+ ```
60
+
61
+ ## Development
62
+
63
+ ```bash
64
+ pip install -e ".[dev]"
65
+ pytest
66
+ ruff check .
67
+ ```
68
+
69
+ ## References
70
+
71
+ - Deng, Xu, Kohavi, Walker (2013) — CUPED
72
+ - Deng, Knoblich, Lu (2018) — Delta Method in Metric Analytics
73
+ - Johari, Pekelis, Walsh (2015) — Always Valid Inference
74
+ - Kohavi, Tang, Xu (2020) — *Trustworthy Online Controlled Experiments*
75
+
76
+ ## License
77
+
78
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "experiment-toolkit"
7
+ version = "0.1.0"
8
+ description = "Small, well-tested utilities for online controlled experiments: sample size, CUPED, sequential testing, delta-method variance."
9
+ readme = "README.md"
10
+ license = { file = "LICENSE" }
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Tejas Wavde" }]
13
+ keywords = ["experimentation", "ab-testing", "causal-inference", "statistics"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Science/Research",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Scientific/Engineering :: Mathematics",
23
+ ]
24
+ dependencies = [
25
+ "numpy>=1.24",
26
+ "scipy>=1.10",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ dev = ["pytest>=7", "ruff>=0.3", "mypy>=1.8"]
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/wavde/experiment-toolkit"
34
+ Issues = "https://github.com/wavde/experiment-toolkit/issues"
35
+
36
+ [project.scripts]
37
+ experiment-toolkit = "experiment_toolkit.cli:main"
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/experiment_toolkit"]
41
+
42
+ [tool.ruff]
43
+ line-length = 100
44
+ target-version = "py310"
45
+
46
+ [tool.ruff.lint]
47
+ select = ["E", "F", "N", "W", "UP", "B", "SIM"]
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
51
+ addopts = "-q"
@@ -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,122 @@
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from experiment_toolkit import (
5
+ apply_cuped,
6
+ compute_theta,
7
+ mde_for_n,
8
+ msprt_pvalue,
9
+ ratio_metric_variance,
10
+ sample_size_for_mde,
11
+ )
12
+
13
+
14
+ # -- sample size ----------------------------------------------------------
15
+
16
+ def test_sample_size_roundtrip():
17
+ # n computed from mde should imply that mde back out
18
+ n = sample_size_for_mde(mde=0.1, std_dev=1.0, alpha=0.05, power=0.80)
19
+ mde = mde_for_n(n_per_arm=n, std_dev=1.0, alpha=0.05, power=0.80)
20
+ assert abs(mde - 0.1) < 0.001
21
+
22
+
23
+ def test_sample_size_textbook_value():
24
+ # Canonical rule of thumb: n ~ 16 * sigma^2 / mde^2 for alpha=0.05, power=0.80
25
+ n = sample_size_for_mde(mde=0.1, std_dev=1.0, alpha=0.05, power=0.80)
26
+ assert 1500 < n < 1700 # exact is ~1570
27
+
28
+
29
+ def test_sample_size_rejects_bad_inputs():
30
+ with pytest.raises(ValueError):
31
+ sample_size_for_mde(mde=0, std_dev=1.0)
32
+ with pytest.raises(ValueError):
33
+ sample_size_for_mde(mde=0.1, std_dev=-1.0)
34
+
35
+
36
+ # -- CUPED ----------------------------------------------------------------
37
+
38
+ def test_theta_zero_when_uncorrelated():
39
+ rng = np.random.default_rng(0)
40
+ y = rng.normal(size=10_000)
41
+ x = rng.normal(size=10_000)
42
+ assert abs(compute_theta(y, x)) < 0.05
43
+
44
+
45
+ def test_cuped_preserves_mean():
46
+ rng = np.random.default_rng(1)
47
+ x = rng.normal(100, 20, size=5_000)
48
+ y = 0.5 * x + rng.normal(0, 10, size=5_000)
49
+ y_adj = apply_cuped(y, x)
50
+ assert abs(y_adj.mean() - y.mean()) < 0.01
51
+
52
+
53
+ def test_cuped_reduces_variance():
54
+ rng = np.random.default_rng(2)
55
+ x = rng.normal(0, 1, size=10_000)
56
+ y = 0.8 * x + rng.normal(0, np.sqrt(1 - 0.8**2), size=10_000)
57
+ # rho = 0.8, expected variance reduction ~ 1 - 0.64 = 0.36
58
+ var_ratio = np.var(apply_cuped(y, x), ddof=1) / np.var(y, ddof=1)
59
+ assert 0.30 < var_ratio < 0.45
60
+
61
+
62
+ # -- ratio metric ----------------------------------------------------------
63
+
64
+ def test_ratio_metric_variance_basic():
65
+ rng = np.random.default_rng(3)
66
+ # sessions per user ~ Poisson(5), minutes per session ~ Normal(10, 2)
67
+ sessions = rng.poisson(5, size=10_000) + 1
68
+ minutes = sessions * rng.normal(10, 2, size=10_000)
69
+ ratio, se = ratio_metric_variance(minutes, sessions)
70
+ assert abs(ratio - 10) < 0.2
71
+ assert se > 0
72
+
73
+
74
+ def test_ratio_metric_variance_validates():
75
+ with pytest.raises(ValueError):
76
+ ratio_metric_variance([1, 2], [0, 0])
77
+ with pytest.raises(ValueError):
78
+ ratio_metric_variance([1], [1]) # too few observations
79
+
80
+
81
+ # -- sequential / mSPRT ----------------------------------------------------
82
+
83
+ def test_msprt_pvalue_in_unit_interval():
84
+ p = msprt_pvalue(delta_hat=0.1, sigma=1.0, n_per_arm=1000, tau=0.1)
85
+ assert 0.0 <= p <= 1.0
86
+
87
+
88
+ def test_msprt_pvalue_decreases_with_effect():
89
+ p_small = msprt_pvalue(delta_hat=0.01, sigma=1.0, n_per_arm=1000, tau=0.1)
90
+ p_large = msprt_pvalue(delta_hat=0.20, sigma=1.0, n_per_arm=1000, tau=0.1)
91
+ assert p_large < p_small
92
+
93
+
94
+ def test_msprt_pvalue_capped_at_one():
95
+ # No effect, small n: p should be 1 (can't reject)
96
+ p = msprt_pvalue(delta_hat=0.0, sigma=1.0, n_per_arm=10, tau=0.1)
97
+ assert p == 1.0
98
+
99
+
100
+ def test_msprt_always_valid_type1_error():
101
+ """Under the null and peeking at every step, naive z-test rejects often;
102
+ mSPRT should reject rarely (alpha-controlled at any stopping time)."""
103
+ rng = np.random.default_rng(42)
104
+ n_trials = 200
105
+ rejections = 0
106
+ for _ in range(n_trials):
107
+ # Simulate one null experiment with peeking
108
+ max_n = 2000
109
+ treatment = rng.normal(0, 1, size=max_n)
110
+ control = rng.normal(0, 1, size=max_n)
111
+ rejected = False
112
+ for n in range(50, max_n + 1, 50):
113
+ delta = treatment[:n].mean() - control[:n].mean()
114
+ sigma = np.std(np.concatenate([treatment[:n], control[:n]]), ddof=1)
115
+ p = msprt_pvalue(delta, sigma, n, tau=0.1)
116
+ if p < 0.05:
117
+ rejected = True
118
+ break
119
+ if rejected:
120
+ rejections += 1
121
+ # Always-valid p-values control Type-I error; expect < 10% even with peeking
122
+ assert rejections / n_trials < 0.10