audit-labs/audit-tools

A collection of scripts, queries, and other goodies you can use in an audit. audit automation compliance evidence scripts

sampling/sampling_tool/engine.py

124 lines · 5359 bytes

  1"""The sampling engine: one deterministic, standard-library selection algorithm.
  2
  3The same seed selects the same items on every install, with or without
  4pandas, in the `audit-sample` command and in audit-workbench. Each stream is
  5seeded from a string (`audit-sample:<seed>` and, per stratum,
  6`audit-sample:<seed>:<stratum>`), which Python's `random` hashes the same way
  7on every platform. Selections are lists of 0-based row positions.
  8
  9Also here: attribute sample sizes and upper deviation limits from the
 10binomial distribution (large-population tables, as in the AICPA Audit
 11Sampling guide), and default control-frequency sample sizes.
 12"""
 13
 14from __future__ import annotations
 15
 16import math
 17import random
 18from decimal import ROUND_CEILING, Decimal
 19
 20ENGINE = "audit-sample-engine"
 21ENGINE_VERSION = "2"
 22
 23# Sample sizes by control frequency, for controls tested without statistical sizing.
 24# Firms can override these (audit-workbench reads `sampling_presets` from engagement.yaml).
 25FREQUENCY_PRESETS = {
 26    "annual": 1,
 27    "quarterly": 2,
 28    "monthly": 2,
 29    "weekly": 5,
 30    "daily": 20,
 31    "multiple-times-daily": 25,
 32}
 33
 34
 35def _rng(seed: int, stratum: str | None = None) -> random.Random:
 36    return random.Random(f"audit-sample:{seed}" + ("" if stratum is None else f":{stratum}"))
 37
 38
 39def select_random(population_size: int, sample_size: int, seed: int) -> list[int]:
 40    """Positions of a simple random sample without replacement, in selection order."""
 41    if not 0 < sample_size <= population_size:
 42        raise ValueError(f"sample size {sample_size} must be between 1 and the population size {population_size}")
 43    return _rng(seed).sample(range(population_size), sample_size)
 44
 45
 46def select_systematic(population_size: int, sample_size: int, seed: int) -> list[int]:
 47    """Every k-th position (k = population / sample, fractional) from a random start."""
 48    if not 0 < sample_size <= population_size:
 49        raise ValueError(f"sample size {sample_size} must be between 1 and the population size {population_size}")
 50    interval = population_size / sample_size
 51    start = _rng(seed).random() * interval
 52    return [int(start + i * interval) for i in range(sample_size)]
 53
 54
 55def select_stratified(
 56    strata: list[str], counts: dict[str, int], seed: int, allow_shortfall: bool = False
 57) -> tuple[list[int], list[dict]]:
 58    """Positions sampled per stratum (`strata[i]` is row i's stratum), and a summary per stratum."""
 59    chosen: list[int] = []
 60    summary: list[dict] = []
 61    for stratum in sorted(counts):
 62        requested = counts[stratum]
 63        pool = [i for i, s in enumerate(strata) if s == stratum]
 64        actual = min(requested, len(pool))
 65        if actual < requested and not allow_shortfall:
 66            raise ValueError(f"Stratum '{stratum}' has {len(pool)} rows; requested {requested}.")
 67        chosen.extend(_rng(seed, stratum).sample(pool, actual) if actual else [])
 68        summary.append(
 69            {
 70                "Stratum": stratum,
 71                "Population Count": len(pool),
 72                "Requested Sample Count": requested,
 73                "Actual Sample Count": actual,
 74                "Shortfall": requested - actual,
 75            }
 76        )
 77    return chosen, summary
 78
 79
 80def _binomial_cdf(k: int, n: int, p: float) -> float:
 81    return sum(math.comb(n, i) * p**i * (1 - p) ** (n - i) for i in range(k + 1))
 82
 83
 84def attribute_sample_size(risk: float, tolerable_rate: float, expected_rate: float = 0.0) -> dict:
 85    """Smallest n whose upper deviation limit, with n × expected rate (rounded up) deviations, is within tolerance.
 86
 87    `risk` is the risk of overreliance (0.05 for 95% confidence). Large-population
 88    (binomial) sizes, as in the AICPA tables.
 89    """
 90    if not (0 < risk < 1 and 0 < tolerable_rate < 1 and 0 <= expected_rate < tolerable_rate):
 91        raise ValueError("need 0 < risk < 1, 0 < tolerable rate < 1, and 0 <= expected rate < tolerable rate")
 92    for n in range(1, 5001):
 93        k = math.ceil(n * expected_rate - 1e-12)
 94        if _binomial_cdf(k, n, tolerable_rate) <= risk:
 95            return {"sample_size": n, "expected_deviations": k}
 96    raise ValueError("no sample size up to 5000 meets these parameters")
 97
 98
 99def upper_deviation_limit(sample_size: int, deviations: int, risk: float) -> float:
100    """Upper deviation limit in percent, rounded up to one decimal (never understated)."""
101    if not (0 <= deviations <= sample_size and sample_size > 0 and 0 < risk < 1):
102        raise ValueError("need 0 <= deviations <= sample size and 0 < risk < 1")
103    if deviations == sample_size:
104        return 100.0
105    lo, hi = 0.0, 1.0
106    for _ in range(80):
107        mid = (lo + hi) / 2
108        if _binomial_cdf(deviations, sample_size, mid) > risk:
109            lo = mid
110        else:
111            hi = mid
112    return float(Decimal(hi * 100).quantize(Decimal("0.1"), rounding=ROUND_CEILING))
113
114
115def evaluate_attribute_sample(sample_size: int, deviations: int, risk: float, tolerable_rate: float) -> dict:
116    udl = upper_deviation_limit(sample_size, deviations, risk)
117    return {
118        "sample_size": sample_size,
119        "deviations": deviations,
120        "sample_rate_pct": round(100 * deviations / sample_size, 2),
121        "upper_deviation_limit_pct": udl,
122        "tolerable_rate_pct": round(100 * tolerable_rate, 2),
123        "supports_reliance": udl <= 100 * tolerable_rate,
124    }