Runs Test for Randomness
Nonparametric Tests
Is the order of outcomes random, or merely balanced?
A sequence can have exactly the right number of heads and still be obviously not random. If every head is followed by a tail, the count is perfect and the pattern is anything but. The runs test detects precisely this: it counts how many uninterrupted streaks โ runs โ the sequence contains and asks whether that count is what random order would produce. Too few runs means clustering; too many means alternation.
The test is one of the oldest in nonparametric statistics and remains one of the most practical, because the null hypothesis it evaluates is genuinely about order rather than about location or spread. In quality control it is the standard check for whether a process is producing outputs in an unpredictable sequence; in time series it is a quick screen for the kind of structure that more elaborate tests will later quantify.
- Counts runs โ maximal streaks of the same symbol โ and compares to the random-order expectation.
- Works on binary sequences directly, and on continuous data via a median split.
- Detects clustering and alternation, which balance-based statistics miss entirely.
What a run is and why it detects non-randomness
The definition is almost too simple, which is why the test's power is easy to underestimate. A run is a maximal block of identical symbols, and the total number of runs in a sequence is a single integer that summarises its order. Under random ordering, that integer has a known distribution determined only by the counts of each symbol โ not by any assumption about the underlying data-generating process beyond exchangeability.
import numpy as np
import pandas as pd
from scipy import stats
def count_runs(sequence):
"""Count runs in a sequence of comparable values."""
if len(sequence) == 0:
return 0
runs = 1
for prev, curr in zip(sequence, sequence[1:]):
if curr != prev:
runs += 1
return runs
def runs_breakdown(sequence):
"""Return the lengths of each run, for inspection."""
if len(sequence) == 0:
return []
lengths, current = [], 1
for prev, curr in zip(sequence, sequence[1:]):
if curr == prev:
current += 1
else:
lengths.append(current)
current = 1
lengths.append(current)
return lengths
# A balanced but patterned sequence
patterned = ["H", "H", "T", "T", "H", "H", "T", "T", "H", "H"]
randomish = ["H", "H", "H", "T", "H", "T", "T", "T", "H", "T"]
for name, seq in [("patterned", patterned), ("randomish", randomish)]:
n_runs = count_runs(seq)
print(f"{name:<10} {''.join(s[0] for s in seq)} runs = {n_runs} "
f"lengths = {runs_breakdown(seq)}")
# The intuition: expected runs under random ordering
def expected_runs(n1, n2):
"""Expected number of runs given counts of the two symbols."""
n = n1 + n2
return (2 * n1 * n2) / n + 1
print(f"\nExpected runs for 5 H and 5 T: {expected_runs(5, 5):.2f}")
print("Fewer than this suggests clustering; more suggests alternation.")
Comparing the two example sequences makes the mechanism plain. Both have five heads and five tails, so any statistic based only on totals treats them identically. The runs counts differ, and that difference is exactly what the test formalises.
The statistic and its distribution
Under the null hypothesis of random ordering, the number of runs has a known mean and variance determined by the two symbol counts. The test statistic standardises the observed run count against that distribution, and for moderate samples the resulting quantity is approximately standard normal.
With n1 and n2 the counts of the two symbols and n their sum, the standardised statistic is (R โ E[R]) / sqrt(Var[R]), which is compared to the standard normal distribution. A significantly negative value indicates too few runs โ clustering; a significantly positive value indicates too many โ alternation.
def runs_test_binary(sequence, positive="H"):
"""Two-sided runs test on a binary sequence."""
seq = [positive if s == positive else "negative" for s in sequence]
n1 = sum(1 for s in seq if s == positive)
n2 = len(seq) - n1
n = n1 + n2
r = count_runs(seq)
if n1 == 0 or n2 == 0 or n < 2:
raise ValueError("Both symbols must appear at least twice.")
mean_r = (2 * n1 * n2) / n + 1
var_r = (2 * n1 * n2 * (2 * n1 * n2 - n)) / (n ** 2 * (n - 1))
z = (r - mean_r) / np.sqrt(var_r)
p_two = 2 * (1 - stats.norm.cdf(abs(z)))
return {"n1": n1, "n2": n2, "runs": r,
"expected": mean_r, "variance": var_r,
"z": z, "p_value": p_two}
sequence = list("HHHTHHTTHTHHHHHTHTT")
result = runs_test_binary(sequence)
print(f"Sequence: {''.join(sequence)}")
for k, v in result.items():
if isinstance(v, float):
print(f" {k:<10} {v:.4f}")
else:
print(f" {k:<10} {v}")
# The library implementation, which should agree
try:
from statsmodels.sandbox.stats.runs import runstest_1samp
# Map to +/-1 for statsmodels
mapped = np.array([1 if s == "H" else -1 for s in sequence])
z_sm, p_sm = runstest_1samp(mapped, correction=False)
print(f"\nstatsmodels: z = {z_sm:.4f}, p = {p_sm:.4f}")
except ImportError:
print("\nInstall statsmodels for runstest_1samp; the manual version above matches it.")
The correction argument in statsmodels applies a continuity correction for the discrete-to-continuous approximation. With the correction disabled the two implementations agree to several decimal places; with it enabled the p-value shifts slightly, which is worth knowing if your results must match a specific package's defaults.
The binary case in practice
Most applications reduce a continuous or multi-valued sequence to binary by splitting at a meaningful threshold โ the median, a specification limit, or a target. Each choice defines a different question, so the split must be justified rather than automatic.
rng = np.random.default_rng(2026)
# Manufacturing: thickness measurements against a specification limit
thickness = rng.normal(10.0, 0.3, size=40)
spec_limit = 10.0
above = ["+" if x >= spec_limit else "-" for x in thickness]
res = runs_test_binary(above, positive="+")
print(f"Spec-limit split: runs = {res['runs']}, expected = {res['expected']:.2f}, "
f"z = {res['z']:.2f}, p = {res['p_value']:.4f}")
# Median split: always balanced, different question
median = np.median(thickness)
above_med = ["+" if x >= median else "-" for x in thickness]
res_med = runs_test_binary(above_med, positive="+")
print(f"Median split: runs = {res_med['runs']}, expected = {res_med['expected']:.2f}, "
f"z = {res_med['z']:.2f}, p = {res_med['p_value']:.4f}")
# A process that is drifting: too few runs, same mean
drift = 10.0 + np.concatenate([
np.linspace(0, 0.6, 20),
np.linspace(0.6, 0, 20),
]) + rng.normal(0, 0.15, 40)
above_drift = ["+" if x >= 10.0 else "-" for x in drift]
res_drift = runs_test_binary(above_drift, positive="+")
print(f"Drifting process: runs = {res_drift['runs']}, expected = {res_drift['expected']:.2f}, "
f"z = {res_drift['z']:.2f}, p = {res_drift['p_value']:.4f}")
The drifting-process example is the one quality engineers recognise instantly. The mean is on target, so a control chart on the mean looks fine; the runs count collapses because successive measurements are positively correlated, and the runs test catches what the mean chart cannot. This is why the test appears in standard control-chart routines as a companion check rather than a replacement.
Continuous data: the Wald-Wolfowitz extension
For sequences with more than two distinct values, the original Wald-Wolfowitz formulation counts runs of identical values directly. In practice, with continuous data every value is distinct and every observation becomes its own run, so the useful version again reduces to a binary split โ or to a rank-based variant that asks a slightly different question.
# Three distinct symbols: generalise the counting
def count_runs_general(sequence):
return count_runs(list(sequence))
seq3 = list("AABBCAACBBAA")
print(f"Sequence: {seq3}")
print(f"Runs: {count_runs_general(seq3)}")
# Wald-Wolfowitz on three symbols, comparing to permutation expectation
def wald_wolfowitz_p(sequence, n_perm=5000, seed=0):
"""Monte Carlo p-value for the runs statistic on a multi-symbol sequence."""
seq = np.array(sequence)
observed = count_runs(seq)
rng = np.random.default_rng(seed)
sim_runs = np.array([count_runs(rng.permutation(seq)) for _ in range(n_perm)])
p_lower = (sim_runs <= observed).mean()
p_upper = (sim_runs >= observed).mean()
return observed, sim_runs.mean(), min(1.0, 2 * min(p_lower, p_upper))
obs, mean_sim, p_mc = wald_wolfowitz_p(seq3)
print(f"Observed runs: {obs}, permutation mean: {mean_sim:.2f}, "
f"two-sided Monte Carlo p = {p_mc:.4f}")
# Continuous values: every point unique, so split is mandatory
continuous = rng.normal(size=30)
unique_ratio = len(np.unique(continuous)) / len(continuous)
print(f"\nContinuous data: {unique_ratio:.0%} unique values "
"-> use a threshold or median split.")
The Monte Carlo permutation version sidesteps the distributional approximation entirely: shuffle the sequence many times, count runs each time, and ask how often the shuffled count is as extreme as the observed one. For small samples or unusual symbol configurations it is the safer calculation, and it costs nothing modern hardware cannot absorb.
Small-sample exact distribution
The normal approximation is unreliable when either symbol count is small โ the conventional guidance is that both n1 and n2 should be at least about ten. Below that, the exact distribution of the run count should be used, and it can be computed by enumeration or looked up in classical tables.
from math import comb
def exact_runs_distribution(n1, n2):
"""Exact distribution of the number of runs under random ordering."""
total_arrangements = comb(n1 + n2, n1)
# For small n, enumerate distinct arrangements directly: clear and safe
from itertools import permutations
counts = {}
seq = np.array(["A"] * n1 + ["B"] * n2)
seen = set()
for perm in permutations(seq):
key = "".join(perm)
if key in seen:
continue
seen.add(key)
r = count_runs(key)
counts[r] = counts.get(r, 0) + 1
return {r: c / total_arrangements for r, c in sorted(counts.items())}
dist = exact_runs_distribution(3, 3)
print("Exact distribution of R for n1 = n2 = 3:")
for r, p in dist.items():
print(f" P(R = {r}) = {p:.4f}")
# Exact two-sided p-value for an observed count of 2 runs
p_exact = sum(p for r, p in dist.items() if p <= dist[2] + 1e-12)
print(f"\nExact two-sided p-value for R = 2: {p_exact:.4f}")
# Compare with the normal approximation at this tiny sample
approx = runs_test_binary(["A", "A", "A", "B", "B", "B"], positive="A")
print(f"Normal approximation at n=6: z = {approx['z']:.2f}, p = {approx['p_value']:.4f}")
print("The approximation is unreliable here; prefer the exact value.")
The contrast at the bottom of that script is the pedagogical point. At six observations the normal approximation produces a plausible-looking p-value that does not match the exact one, and the discrepancy is large enough to flip a decision at the five per cent level. Checking sample size before choosing the approximation is not optional hygiene; it is the difference between a valid test and a decorative one.
Applications beyond quality control
The runs test's strength is that it interrogates order specifically, which makes it complementary to tests that interrogate level or dependence. Three settings use it routinely, and each illustrates a different way of constructing the sequence.
# 1. Clinical trials: is the allocation sequence properly randomised?
allocation = list("ABBAABBABAABBAABABBAABBAABBAAB")
res = runs_test_binary(allocation, positive="A")
print(f"Trial allocation: runs = {res['runs']}, expected = {res['expected']:.2f}, "
f"p = {res['p_value']:.4f}")
# 2. Time series: screen for residual structure after fitting
from statsmodels.tsa.arima_process import arma_generate_process
phi = [1, -0.6] # AR(1)
residuals = arma_generate_process(ar=phi, ma=[1, 0], nsample=100, burnin=20,
random_state=7)
signs = ["+" if r >= 0 else "-" for r in residuals]
res_ts = runs_test_binary(signs, positive="+")
print(f"Residual signs: runs = {res_ts['runs']}, expected = {res_ts['expected']:.1f}, "
f"p = {res_ts['p_value']:.4f}")
# 3. A/B test logs: check the exposure sequence is not predictable
exposure = list("BAABABBBAAABBABAABBAABABBAAABBABAABBAABB")
res_ab = runs_test_binary(exposure, positive="A")
print(f"A/B exposures: runs = {res_ab['runs']}, expected = {res_ab['expected']:.1f}, "
f"p = {res_ab['p_value']:.4f}")
The trial-allocation application deserves particular emphasis. Proper randomisation produces an unpredictable sequence, and a sequence with too few runs is a signature of alternation or of block allocation that was not properly concealed. Regulators and reviewers increasingly expect a runs check on the allocation log precisely because it detects a class of implementation errors that the allocation ratio alone cannot reveal.
Mistakes that hollow out the test
Common Mistakes
Using the normal approximation with small symbol counts
Fix: Require roughly ten of each symbol, or compute the exact distribution.
Splitting continuous data at a threshold chosen after seeing the sequence
Fix: Fix the split from domain knowledge or the median, stated in advance.
Interpreting a significant result as proof of non-randomness
Fix: It indicates order structure of a specific kind; identify the mechanism separately.
Running the test on data with ties at the split point
Fix: Decide the tie rule in advance, since it changes n1, n2, and the run count.
Applying the test to a sequence that is not exchangeable under the null
Fix: Trending or seasonally varying series violate the null by construction.
Ignoring the direction of the deviation
Fix: Too few runs and too many runs mean opposite things; always report which occurred.
Reporting only the p-value
Fix: Give the observed run count, the expected count, and the symbol totals.
Expecting the test to detect all forms of dependence
Fix: It detects run-length structure specifically; pair it with autocorrelation checks.
Practices that keep the analysis meaningful
Best Practices
- Report observed and expected run counts, not just the p-value.
- State how the sequence was dichotomised and why, before testing.
- Use the exact distribution whenever either symbol count is below about ten.
- Check for trends first; a trending series fails the null by construction.
- Pair the runs test with an autocorrelation check for a fuller picture of order.
- Use Monte Carlo permutation p-values for multi-symbol or unusual sequences.
- In trial contexts, run the test on the allocation log as a standing quality check.
- Remember the test is two-sided: clustering and alternation are different diagnoses.
Key takeaways
Key Takeaways
- A run is a maximal streak of identical symbols; the run count summarises a sequence's order.
- Balanced counts say nothing about order, which is why runs detect what totals cannot.
- The expected run count is 2ยทn1ยทn2/n + 1, with a variance determined by the same totals.
- Fewer runs than expected means clustering; more means alternation.
- Continuous data needs a threshold split, justified before the sequence is examined.
- Below roughly ten of each symbol, use the exact distribution or a permutation p-value.
- Trending or seasonal series violate the null by construction, so check for trends first.
- In trials, the runs test on allocation logs catches implementation errors the ratio cannot.
Where to go next
- Autocorrelation โ measuring dependence in continuous sequences.
- Time Series Stationarity โ the broader assumption the runs test screens for.
- Permutation Tests โ the exact alternative underlying the Monte Carlo version.
- P-Values โ interpreting the probabilities this test produces.