Why order matters
Shuffling a series keeps its mean and destroys its story. See what autocorrelation does to the amount of information in your data, and what that does to ordinary tests.
What runs in CodeSplash
- Randomness and serial-dependence tests Verified in Python and R
You will be able to
- Explain what autocorrelation is and read a first-order value
- Work out how much autocorrelation shrinks the effective sample size
- Say why tests that assume independence mislead on a series
Read first
Same numbers, different series
ReadTake a year of daily sales and sort them at random. The mean, the SD and the histogram don't change. But the runs, the seasons and any drift are gone.
A summary that ignores order can't tell the two apart. A time series carries information in its order, so methods for series have to use that order.
The key idea is autocorrelationAutocorrelationCorrelation of a series with its own past; it breaks independence and shrinks the effective sample size.: the correlation between the series and itself shifted by steps.
How much is 240 values worth?
PredictPredict first
You have 240 monthly values. Each is strongly related to the last, with = 0.8.
For estimating the mean, how many independent values are they worth?
Reveal
About 27. With first-order autocorrelation , the effective sample sizeEffective sample sizeHow many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count. is roughly . That's . Neighboring values mostly repeat each other's information.
Two simulated series
In the appBoth of these have 240 simulated monthly values. One is white noise, with no memory at all. The other depends on its own past.
Runs test z = 0.91, p = .365; Bartels rank z = 0.38, p = .707; Turning points z = 0.97, p = .330; von Neumann ratio z = 0.77, p = .440; Ljung–Box Q = 8.74, p = .557; McLeod–Li Q = 19.25, p = .037; ARCH LM = 12.51, p = .014
- Runs test z
- 0.9056
- p
- 0.3652
Plots
View data
| white_noise |
|---|
| 0.2740 |
| −0.1581 |
| 0.2012 |
| 1.002 |
| −0.3188 |
| −0.0540 |
| 1.259 |
| −0.8742 |
| 0.4343 |
| −1.159 |
| −0.6030 |
| 0.6557 |
| −0.0975 |
| −1.159 |
| 0.1470 |
| −0.0478 |
| −1.064 |
| −0.2931 |
| −0.4380 |
| −0.4016 |
| 1.522 |
| −0.1217 |
| −1.526 |
| 0.7239 |
| −0.9991 |
| 2.088 |
| 1.123 |
| 0.9391 |
| 0.8723 |
| 0.7839 |
| −0.4039 |
| 0.2029 |
| −0.7618 |
| 1.176 |
| −0.2773 |
| 0.3084 |
| 1.066 |
| −0.4970 |
| 0.0464 |
| −0.5603 |
| 0.4396 |
| −1.042 |
| 0.0725 |
| −0.2518 |
| −0.0689 |
| −2.454 |
| −0.2056 |
| 0.0711 |
| 0.1655 |
| −0.2585 |
| 0.3485 |
| 1.420 |
| 0.9025 |
| 0.8410 |
| −0.7922 |
| −1.178 |
| 0.0866 |
| 1.892 |
| 0.5380 |
| −0.3651 |
First 60 of 240 rows.
View data
| white_noise |
|---|
| 0.2740 |
| −0.1581 |
| 0.2012 |
| 1.002 |
| −0.3188 |
| −0.0540 |
| 1.259 |
| −0.8742 |
| 0.4343 |
| −1.159 |
| −0.6030 |
| 0.6557 |
| −0.0975 |
| −1.159 |
| 0.1470 |
| −0.0478 |
| −1.064 |
| −0.2931 |
| −0.4380 |
| −0.4016 |
| 1.522 |
| −0.1217 |
| −1.526 |
| 0.7239 |
| −0.9991 |
| 2.088 |
| 1.123 |
| 0.9391 |
| 0.8723 |
| 0.7839 |
| −0.4039 |
| 0.2029 |
| −0.7618 |
| 1.176 |
| −0.2773 |
| 0.3084 |
| 1.066 |
| −0.4970 |
| 0.0464 |
| −0.5603 |
| 0.4396 |
| −1.042 |
| 0.0725 |
| −0.2518 |
| −0.0689 |
| −2.454 |
| −0.2056 |
| 0.0711 |
| 0.1655 |
| −0.2585 |
| 0.3485 |
| 1.420 |
| 0.9025 |
| 0.8410 |
| −0.7922 |
| −1.178 |
| 0.0866 |
| 1.892 |
| 0.5380 |
| −0.3651 |
First 60 of 240 rows.
Randomness tests
| Test | Sensitive to | Statistic | df | p | At α = .05 |
|---|---|---|---|---|---|
| Runs test z | clustering or alternation | 0.9056 | — | .365 | no evidence |
| Bartels rank z | trend or serial dependence | 0.3758 | — | .707 | no evidence |
| Turning points z | too few or many peaks and troughs | 0.9733 | — | .330 | no evidence |
| von Neumann ratio z | successive values too alike or too different | 0.7729 | — | .440 | no evidence |
| Ljung–Box Q | autocorrelation | 8.741 | 10 | .557 | no evidence |
| McLeod–Li Q | autocorrelation of squares (volatility) | 19.246 | 10 | .037 | not random |
| ARCH LM | volatility clustering | 12.507 | 4 | .014 | not random |
- Portmanteau tests use 10 lags.
- Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence.
The exact R script · R R version 4.5.1 (2025-06-13)
# Randomness and serial-dependence tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.randomness 1.1.1 · spec 9fb366354bac4990
# Dataset: ts_truth (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ts_truth.parquet", col_select = c("white_noise", "month")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("white_noise", "month")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("white_noise", "month")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "white_noise"
TIME <- "month"
TEMPORAL <- TRUE
TEST <- "battery"
LAG <- NULL
FITDF <- 0
WM_CORRECTION <- "always"
ARCH_LAGS <- 4
BDS_DIM <- 2
BDS_DIST <- 1.5
s <- cs_ts_ordered(df, VALUE, TIME, TEMPORAL)
x <- s$x
n <- length(x)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: the tests assume one observation per evenly spaced time.", s$dups))
lag <- if (!is.null(LAG)) as.integer(LAG) else max(1L, min(10L, n %/% 5L))
if (TEST %in% c("ljung_box", "box_pierce", "battery") && lag - FITDF < 1) {
stop(sprintf("Portmanteau tests need more lags (%d) than the model's degrees of freedom (%d); use at least %d lags.", as.integer(lag), as.integer(FITDF), as.integer(FITDF + 1)))
}
LABELS <- list(runs = "Runs test z", bartels = "Bartels rank z", wallis_moore = "Wallis–Moore z", turning_points = "Turning points z",
von_neumann = "von Neumann ratio z", ljung_box = "Ljung–Box Q", box_pierce = "Box–Pierce Q", mcleod_li = "McLeod–Li Q",
arch = "ARCH LM", bds = "BDS z", battery = "Battery")
LOOKS <- list(runs = "clustering or alternation", bartels = "trend or serial dependence", wallis_moore = "too few or many rises and falls",
turning_points = "too few or many peaks and troughs", von_neumann = "successive values too alike or too different",
ljung_box = "autocorrelation", box_pierce = "autocorrelation", mcleod_li = "autocorrelation of squares (volatility)",
arch = "volatility clustering", bds = "any dependence, including nonlinear")
run_test <- function(t) switch(t,
runs = cs_ts_runs(x), bartels = cs_ts_bartels(x), wallis_moore = cs_ts_wallis_moore(x, WM_CORRECTION), turning_points = cs_ts_turning_points(x),
von_neumann = cs_ts_von_neumann(x), ljung_box = cs_ts_portmanteau(x, lag, "ljung", FITDF), box_pierce = cs_ts_portmanteau(x, lag, "box", FITDF),
mcleod_li = cs_ts_mcleod_li(x, lag), arch = cs_ts_arch_lm(x, ARCH_LAGS), cs_ts_bds(x, BDS_DIM, BDS_DIST))
# %% Tests
tests <- if (TEST == "battery") c("runs", "bartels", "turning_points", "von_neumann", "ljung_box", "mcleod_li", "arch") else TEST
# The shortest series each test can use (the portmanteau tests need more values than lags, the ARCH regression
# more rows than coefficients), and a series that varies (registry/errors.yaml; the same checks in Python).
MIN_N <- c(runs = 3, bartels = 3, wallis_moore = 3, turning_points = 3, von_neumann = 3, ljung_box = lag + 2,
box_pierce = lag + 2, mcleod_li = lag + 2, arch = 2 * ARCH_LAGS + 2, bds = BDS_DIM + 2)
cs_check_rows(n, max(MIN_N[tests]), "The randomness tests")
cs_check_not_constant(x, VALUE)
res <- lapply(stats::setNames(tests, tests), run_test)
rows <- lapply(tests, function(t) list(test = LABELS[[t]], looks_for = LOOKS[[t]], statistic = res[[t]]$stat, df = res[[t]]$df, p = res[[t]]$p,
verdict = if (res[[t]]$p < 0.05) "not random" else "no evidence"))
values <- list(n_obs = n, test = TEST, test_label = LABELS[[TEST]], lag = lag)
main <- res[[tests[1]]]
values$stat <- main$stat
values$p <- main$p
values$reject <- as.integer(main$p < 0.05)
if (!is.null(main$df)) values$df <- main$df
if (TEST == "runs") values$runs <- main$runs
if (TEST == "battery") {
for (t in tests) {
values[[paste0(t, "_stat")]] <- res[[t]]$stat
values[[paste0(t, "_p")]] <- res[[t]]$p
}
values$n_reject <- sum(vapply(tests, function(t) res[[t]]$p < 0.05, logical(1)))
flagged <- unlist(lapply(tests, function(t) if (res[[t]]$p < 0.05) LOOKS[[t]]))
summary <- paste0(sprintf("%d of %d randomness tests reject at α = .05 for %s (%d observations)", values$n_reject, length(tests), VALUE, n),
if (length(flagged)) paste0(": ", paste(flagged, collapse = "; "), ".") else " — consistent with independent noise.")
} else {
summary <- paste0(sprintf("%s for %s: %.3f, %s — ", LABELS[[TEST]], VALUE, main$stat, cs_fmt_p(main$p)),
if (main$p < 0.05) sprintf("evidence of %s.", LOOKS[[TEST]]) else "no evidence against randomness.")
}
charts <- list(cs_chart("acf", "acf", sprintf("Autocorrelation of %s", VALUE), list(y = cs_col(VALUE, x))),
cs_chart("lb", "ljung-box-p", sprintf("Ljung–Box p by lag: %s", VALUE), list(y = cs_col(VALUE, x)), controls = list(fitdf = FITDF)))
cs_publish(list(
method = "ts.randomness",
methodVersion = "1.1.1",
title = "Randomness and serial-dependence tests",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = paste(vapply(rows, function(r) sprintf("%s = %.2f, %s", r$test, r$statistic, cs_fmt_p(r$p)), ""), collapse = "; "),
statistics = list(list(key = "stat", label = LABELS[[tests[1]]], value = main$stat), list(key = "p", label = "p", value = main$p)),
tables = list(list(
key = "tests", title = "Randomness tests",
columns = list(list(key = "test", label = "Test", type = "string"), list(key = "looks_for", label = "Sensitive to", type = "string"),
list(key = "statistic", label = "Statistic", type = "number"), list(key = "df", label = "df", type = "integer"),
list(key = "p", label = "p", type = "pvalue"), list(key = "verdict", label = "At α = .05", type = "string")),
rows = rows
)),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = list(paste0(sprintf("Portmanteau tests use %d lags", lag), if (FITDF > 0) sprintf(" and %d model degrees of freedom", FITDF) else "", "."),
"Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence."),
charts = charts,
values = values
))
Runs test z = 0.91, p = .365; Bartels rank z = 0.38, p = .707; Turning points z = 0.97, p = .330; von Neumann ratio z = 0.77, p = .440; Ljung–Box Q = 8.74, p = .557; McLeod–Li Q = 19.25, p = .037; ARCH LM = 12.51, p = .014
- Runs test z
- 0.9056
- p
- 0.3652
To keep this page light, the plots are shown once, under the R tab.
Randomness tests
| Test | Sensitive to | Statistic | df | p | At α = .05 |
|---|---|---|---|---|---|
| Runs test z | clustering or alternation | 0.9056 | — | .365 | no evidence |
| Bartels rank z | trend or serial dependence | 0.3758 | — | .707 | no evidence |
| Turning points z | too few or many peaks and troughs | 0.9733 | — | .330 | no evidence |
| von Neumann ratio z | successive values too alike or too different | 0.7729 | — | .440 | no evidence |
| Ljung–Box Q | autocorrelation | 8.741 | 10 | .557 | no evidence |
| McLeod–Li Q | autocorrelation of squares (volatility) | 19.246 | 10 | .037 | not random |
| ARCH LM | volatility clustering | 12.507 | 4 | .014 | not random |
- Portmanteau tests use 10 lags.
- Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Randomness and serial-dependence tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.randomness 1.1.1 · spec 9fb366354bac4990
# Dataset: ts_truth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ts_truth.parquet", columns=["white_noise", "month"])
n_input = len(df)
df = df.dropna(subset=["white_noise", "month"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["white_noise", "month"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "white_noise"
TIME = "month"
TEMPORAL = True
TEST = "battery"
LAG = None
FITDF = 0
WM_CORRECTION = "always"
ARCH_LAGS = 4
BDS_DIM = 2
BDS_DIST = 1.5
s = ts.ordered(df, VALUE, TIME, TEMPORAL)
x = s["x"]
n = len(x)
if s["dups"]:
warnings.append(f"{s['dups']} repeated time values: the tests assume one observation per evenly spaced time.")
lag = int(LAG) if LAG is not None else max(1, min(10, n // 5))
if TEST in ("ljung_box", "box_pierce", "battery") and lag - FITDF < 1:
raise ValueError(f"Portmanteau tests need more lags ({lag}) than the model's degrees of freedom ({FITDF}); use at least {FITDF + 1} lags.")
LABELS = {"runs": "Runs test z", "bartels": "Bartels rank z", "wallis_moore": "Wallis–Moore z", "turning_points": "Turning points z",
"von_neumann": "von Neumann ratio z", "ljung_box": "Ljung–Box Q", "box_pierce": "Box–Pierce Q", "mcleod_li": "McLeod–Li Q",
"arch": "ARCH LM", "bds": "BDS z", "battery": "Battery"}
LOOKS = {"runs": "clustering or alternation", "bartels": "trend or serial dependence", "wallis_moore": "too few or many rises and falls",
"turning_points": "too few or many peaks and troughs", "von_neumann": "successive values too alike or too different",
"ljung_box": "autocorrelation", "box_pierce": "autocorrelation", "mcleod_li": "autocorrelation of squares (volatility)",
"arch": "volatility clustering", "bds": "any dependence, including nonlinear"}
def run(t):
if t == "runs":
return ts.runs_test(x)
if t == "bartels":
return ts.bartels(x)
if t == "wallis_moore":
return ts.wallis_moore(x, WM_CORRECTION)
if t == "turning_points":
return ts.turning_points(x)
if t == "von_neumann":
return ts.von_neumann(x)
if t == "ljung_box":
return ts.portmanteau(x, lag, "ljung", FITDF)
if t == "box_pierce":
return ts.portmanteau(x, lag, "box", FITDF)
if t == "mcleod_li":
return ts.mcleod_li(x, lag)
if t == "arch":
return ts.arch_lm(x, ARCH_LAGS)
return ts.bds(x, BDS_DIM, BDS_DIST)
# %% Tests
tests = ["runs", "bartels", "turning_points", "von_neumann", "ljung_box", "mcleod_li", "arch"] if TEST == "battery" else [TEST]
# The shortest series each test can use (the portmanteau tests need more values than lags, the ARCH regression
# more rows than coefficients), and a series that varies (registry/errors.yaml; the same checks in R).
MIN_N = {"runs": 3, "bartels": 3, "wallis_moore": 3, "turning_points": 3, "von_neumann": 3, "ljung_box": lag + 2,
"box_pierce": lag + 2, "mcleod_li": lag + 2, "arch": 2 * ARCH_LAGS + 2, "bds": BDS_DIM + 2}
cs.check_rows(n, max(MIN_N[t] for t in tests), "The randomness tests")
check_not_constant(x, VALUE)
res = {t: run(t) for t in tests}
rows = [{"test": LABELS[t], "looks_for": LOOKS[t], "statistic": res[t]["stat"], "df": res[t].get("df"), "p": res[t]["p"],
"verdict": "not random" if res[t]["p"] < 0.05 else "no evidence"} for t in tests]
values = {"n_obs": n, "test": TEST, "test_label": LABELS[TEST], "lag": lag}
main = res[tests[0]]
values.update({"stat": main["stat"], "p": main["p"], "reject": int(main["p"] < 0.05)})
if main.get("df") is not None:
values["df"] = main["df"]
if TEST == "runs":
values["runs"] = main["runs"]
if TEST == "battery":
for t in tests:
values[f"{t}_stat"] = res[t]["stat"]
values[f"{t}_p"] = res[t]["p"]
values["n_reject"] = sum(1 for t in tests if res[t]["p"] < 0.05)
flagged = [LOOKS[t] for t in tests if res[t]["p"] < 0.05]
summary = (f"{values['n_reject']} of {len(tests)} randomness tests reject at α = .05 for {VALUE} ({n} observations)"
+ (": " + "; ".join(flagged) + "." if flagged else " — consistent with independent noise."))
else:
summary = f"{LABELS[TEST]} for {VALUE}: {main['stat']:.3f}, {cs.fmt_p(main['p'])} — " + (f"evidence of {LOOKS[TEST]}." if main["p"] < 0.05 else "no evidence against randomness.")
kind = "temporal" if TEMPORAL else "numeric"
charts = [cs.chart("acf", "acf", f"Autocorrelation of {VALUE}", {"y": cs.col(VALUE, x)}),
cs.chart("lb", "ljung-box-p", f"Ljung–Box p by lag: {VALUE}", {"y": cs.col(VALUE, x)}, controls={"fitdf": FITDF})]
cs.publish({
"method": "ts.randomness",
"methodVersion": "1.1.1",
"title": "Randomness and serial-dependence tests",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": "; ".join(f"{r['test']} = {r['statistic']:.2f}, {cs.fmt_p(r['p'])}" for r in rows),
"statistics": [{"key": "stat", "label": LABELS[tests[0]], "value": main["stat"]}, {"key": "p", "label": "p", "value": main["p"]}],
"tables": [{
"key": "tests", "title": "Randomness tests",
"columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "looks_for", "label": "Sensitive to", "type": "string"},
{"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "df", "label": "df", "type": "integer"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "verdict", "label": "At α = .05", "type": "string"}],
"rows": rows,
}],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": [f"Portmanteau tests use {lag} lags" + (f" and {FITDF} model degrees of freedom" if FITDF else "") + ".",
"Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence."],
"charts": charts,
"values": values,
})
Runs test z = -6.47, p < .001; Bartels rank z = -9.35, p < .001; Turning points z = -3.64, p < .001; von Neumann ratio z = -9.65, p < .001; Ljung–Box Q = 161.99, p < .001; McLeod–Li Q = 48.95, p < .001; ARCH LM = 44.11, p < .001
- Runs test z
- −6.469
- p
- 9.897e-11
Plots
View data
| ar1 |
|---|
| −0.4250 |
| 1.219 |
| 0.2020 |
| 1.143 |
| 1.697 |
| 1.334 |
| 1.462 |
| 1.251 |
| 0.2316 |
| 0.5952 |
| −1.872 |
| −0.5941 |
| 0.3111 |
| −0.1341 |
| 0.4192 |
| −1.666 |
| 0.4987 |
| −0.1621 |
| 0.7605 |
| 2.646 |
| 1.156 |
| −0.1409 |
| 1.716 |
| −0.0456 |
| −0.7597 |
| −0.5606 |
| −1.727 |
| −2.224 |
| −2.179 |
| 0.3599 |
| −0.2623 |
| −0.4415 |
| −1.350 |
| −2.075 |
| −1.176 |
| −0.7529 |
| −1.467 |
| −3.162 |
| −3.024 |
| −2.120 |
| −1.922 |
| −1.820 |
| −1.500 |
| −0.5368 |
| −0.6994 |
| −0.5904 |
| 2.038 |
| −0.2871 |
| −0.0107 |
| 1.875 |
| 0.7885 |
| 0.1344 |
| 0.0554 |
| −0.7248 |
| 1.049 |
| 1.447 |
| 1.034 |
| 0.3486 |
| 1.127 |
| 0.9216 |
First 60 of 240 rows.
View data
| ar1 |
|---|
| −0.4250 |
| 1.219 |
| 0.2020 |
| 1.143 |
| 1.697 |
| 1.334 |
| 1.462 |
| 1.251 |
| 0.2316 |
| 0.5952 |
| −1.872 |
| −0.5941 |
| 0.3111 |
| −0.1341 |
| 0.4192 |
| −1.666 |
| 0.4987 |
| −0.1621 |
| 0.7605 |
| 2.646 |
| 1.156 |
| −0.1409 |
| 1.716 |
| −0.0456 |
| −0.7597 |
| −0.5606 |
| −1.727 |
| −2.224 |
| −2.179 |
| 0.3599 |
| −0.2623 |
| −0.4415 |
| −1.350 |
| −2.075 |
| −1.176 |
| −0.7529 |
| −1.467 |
| −3.162 |
| −3.024 |
| −2.120 |
| −1.922 |
| −1.820 |
| −1.500 |
| −0.5368 |
| −0.6994 |
| −0.5904 |
| 2.038 |
| −0.2871 |
| −0.0107 |
| 1.875 |
| 0.7885 |
| 0.1344 |
| 0.0554 |
| −0.7248 |
| 1.049 |
| 1.447 |
| 1.034 |
| 0.3486 |
| 1.127 |
| 0.9216 |
First 60 of 240 rows.
Randomness tests
| Test | Sensitive to | Statistic | df | p | At α = .05 |
|---|---|---|---|---|---|
| Runs test z | clustering or alternation | −6.469 | — | < .001 | not random |
| Bartels rank z | trend or serial dependence | −9.347 | — | < .001 | not random |
| Turning points z | too few or many peaks and troughs | −3.637 | — | < .001 | not random |
| von Neumann ratio z | successive values too alike or too different | −9.646 | — | < .001 | not random |
| Ljung–Box Q | autocorrelation | 161.99 | 10 | < .001 | not random |
| McLeod–Li Q | autocorrelation of squares (volatility) | 48.952 | 10 | < .001 | not random |
| ARCH LM | volatility clustering | 44.106 | 4 | < .001 | not random |
- Portmanteau tests use 10 lags.
- Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence.
The exact R script · R R version 4.5.1 (2025-06-13)
# Randomness and serial-dependence tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.randomness 1.1.1 · spec a875ea3a466b6526
# Dataset: ts_truth (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ts_truth.parquet", col_select = c("ar1", "month")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("ar1", "month")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("ar1", "month")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "ar1"
TIME <- "month"
TEMPORAL <- TRUE
TEST <- "battery"
LAG <- NULL
FITDF <- 0
WM_CORRECTION <- "always"
ARCH_LAGS <- 4
BDS_DIM <- 2
BDS_DIST <- 1.5
s <- cs_ts_ordered(df, VALUE, TIME, TEMPORAL)
x <- s$x
n <- length(x)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: the tests assume one observation per evenly spaced time.", s$dups))
lag <- if (!is.null(LAG)) as.integer(LAG) else max(1L, min(10L, n %/% 5L))
if (TEST %in% c("ljung_box", "box_pierce", "battery") && lag - FITDF < 1) {
stop(sprintf("Portmanteau tests need more lags (%d) than the model's degrees of freedom (%d); use at least %d lags.", as.integer(lag), as.integer(FITDF), as.integer(FITDF + 1)))
}
LABELS <- list(runs = "Runs test z", bartels = "Bartels rank z", wallis_moore = "Wallis–Moore z", turning_points = "Turning points z",
von_neumann = "von Neumann ratio z", ljung_box = "Ljung–Box Q", box_pierce = "Box–Pierce Q", mcleod_li = "McLeod–Li Q",
arch = "ARCH LM", bds = "BDS z", battery = "Battery")
LOOKS <- list(runs = "clustering or alternation", bartels = "trend or serial dependence", wallis_moore = "too few or many rises and falls",
turning_points = "too few or many peaks and troughs", von_neumann = "successive values too alike or too different",
ljung_box = "autocorrelation", box_pierce = "autocorrelation", mcleod_li = "autocorrelation of squares (volatility)",
arch = "volatility clustering", bds = "any dependence, including nonlinear")
run_test <- function(t) switch(t,
runs = cs_ts_runs(x), bartels = cs_ts_bartels(x), wallis_moore = cs_ts_wallis_moore(x, WM_CORRECTION), turning_points = cs_ts_turning_points(x),
von_neumann = cs_ts_von_neumann(x), ljung_box = cs_ts_portmanteau(x, lag, "ljung", FITDF), box_pierce = cs_ts_portmanteau(x, lag, "box", FITDF),
mcleod_li = cs_ts_mcleod_li(x, lag), arch = cs_ts_arch_lm(x, ARCH_LAGS), cs_ts_bds(x, BDS_DIM, BDS_DIST))
# %% Tests
tests <- if (TEST == "battery") c("runs", "bartels", "turning_points", "von_neumann", "ljung_box", "mcleod_li", "arch") else TEST
# The shortest series each test can use (the portmanteau tests need more values than lags, the ARCH regression
# more rows than coefficients), and a series that varies (registry/errors.yaml; the same checks in Python).
MIN_N <- c(runs = 3, bartels = 3, wallis_moore = 3, turning_points = 3, von_neumann = 3, ljung_box = lag + 2,
box_pierce = lag + 2, mcleod_li = lag + 2, arch = 2 * ARCH_LAGS + 2, bds = BDS_DIM + 2)
cs_check_rows(n, max(MIN_N[tests]), "The randomness tests")
cs_check_not_constant(x, VALUE)
res <- lapply(stats::setNames(tests, tests), run_test)
rows <- lapply(tests, function(t) list(test = LABELS[[t]], looks_for = LOOKS[[t]], statistic = res[[t]]$stat, df = res[[t]]$df, p = res[[t]]$p,
verdict = if (res[[t]]$p < 0.05) "not random" else "no evidence"))
values <- list(n_obs = n, test = TEST, test_label = LABELS[[TEST]], lag = lag)
main <- res[[tests[1]]]
values$stat <- main$stat
values$p <- main$p
values$reject <- as.integer(main$p < 0.05)
if (!is.null(main$df)) values$df <- main$df
if (TEST == "runs") values$runs <- main$runs
if (TEST == "battery") {
for (t in tests) {
values[[paste0(t, "_stat")]] <- res[[t]]$stat
values[[paste0(t, "_p")]] <- res[[t]]$p
}
values$n_reject <- sum(vapply(tests, function(t) res[[t]]$p < 0.05, logical(1)))
flagged <- unlist(lapply(tests, function(t) if (res[[t]]$p < 0.05) LOOKS[[t]]))
summary <- paste0(sprintf("%d of %d randomness tests reject at α = .05 for %s (%d observations)", values$n_reject, length(tests), VALUE, n),
if (length(flagged)) paste0(": ", paste(flagged, collapse = "; "), ".") else " — consistent with independent noise.")
} else {
summary <- paste0(sprintf("%s for %s: %.3f, %s — ", LABELS[[TEST]], VALUE, main$stat, cs_fmt_p(main$p)),
if (main$p < 0.05) sprintf("evidence of %s.", LOOKS[[TEST]]) else "no evidence against randomness.")
}
charts <- list(cs_chart("acf", "acf", sprintf("Autocorrelation of %s", VALUE), list(y = cs_col(VALUE, x))),
cs_chart("lb", "ljung-box-p", sprintf("Ljung–Box p by lag: %s", VALUE), list(y = cs_col(VALUE, x)), controls = list(fitdf = FITDF)))
cs_publish(list(
method = "ts.randomness",
methodVersion = "1.1.1",
title = "Randomness and serial-dependence tests",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = paste(vapply(rows, function(r) sprintf("%s = %.2f, %s", r$test, r$statistic, cs_fmt_p(r$p)), ""), collapse = "; "),
statistics = list(list(key = "stat", label = LABELS[[tests[1]]], value = main$stat), list(key = "p", label = "p", value = main$p)),
tables = list(list(
key = "tests", title = "Randomness tests",
columns = list(list(key = "test", label = "Test", type = "string"), list(key = "looks_for", label = "Sensitive to", type = "string"),
list(key = "statistic", label = "Statistic", type = "number"), list(key = "df", label = "df", type = "integer"),
list(key = "p", label = "p", type = "pvalue"), list(key = "verdict", label = "At α = .05", type = "string")),
rows = rows
)),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = list(paste0(sprintf("Portmanteau tests use %d lags", lag), if (FITDF > 0) sprintf(" and %d model degrees of freedom", FITDF) else "", "."),
"Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence."),
charts = charts,
values = values
))
Runs test z = -6.47, p < .001; Bartels rank z = -9.35, p < .001; Turning points z = -3.64, p < .001; von Neumann ratio z = -9.65, p < .001; Ljung–Box Q = 161.99, p < .001; McLeod–Li Q = 48.95, p < .001; ARCH LM = 44.11, p < .001
- Runs test z
- −6.469
- p
- 9.897e-11
To keep this page light, the plots are shown once, under the R tab.
Randomness tests
| Test | Sensitive to | Statistic | df | p | At α = .05 |
|---|---|---|---|---|---|
| Runs test z | clustering or alternation | −6.469 | — | < .001 | not random |
| Bartels rank z | trend or serial dependence | −9.347 | — | < .001 | not random |
| Turning points z | too few or many peaks and troughs | −3.637 | — | < .001 | not random |
| von Neumann ratio z | successive values too alike or too different | −9.646 | — | < .001 | not random |
| Ljung–Box Q | autocorrelation | 161.99 | 10 | < .001 | not random |
| McLeod–Li Q | autocorrelation of squares (volatility) | 48.952 | 10 | < .001 | not random |
| ARCH LM | volatility clustering | 44.106 | 4 | < .001 | not random |
- Portmanteau tests use 10 lags.
- Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Randomness and serial-dependence tests
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.randomness 1.1.1 · spec a875ea3a466b6526
# Dataset: ts_truth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ts_truth.parquet", columns=["ar1", "month"])
n_input = len(df)
df = df.dropna(subset=["ar1", "month"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["ar1", "month"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "ar1"
TIME = "month"
TEMPORAL = True
TEST = "battery"
LAG = None
FITDF = 0
WM_CORRECTION = "always"
ARCH_LAGS = 4
BDS_DIM = 2
BDS_DIST = 1.5
s = ts.ordered(df, VALUE, TIME, TEMPORAL)
x = s["x"]
n = len(x)
if s["dups"]:
warnings.append(f"{s['dups']} repeated time values: the tests assume one observation per evenly spaced time.")
lag = int(LAG) if LAG is not None else max(1, min(10, n // 5))
if TEST in ("ljung_box", "box_pierce", "battery") and lag - FITDF < 1:
raise ValueError(f"Portmanteau tests need more lags ({lag}) than the model's degrees of freedom ({FITDF}); use at least {FITDF + 1} lags.")
LABELS = {"runs": "Runs test z", "bartels": "Bartels rank z", "wallis_moore": "Wallis–Moore z", "turning_points": "Turning points z",
"von_neumann": "von Neumann ratio z", "ljung_box": "Ljung–Box Q", "box_pierce": "Box–Pierce Q", "mcleod_li": "McLeod–Li Q",
"arch": "ARCH LM", "bds": "BDS z", "battery": "Battery"}
LOOKS = {"runs": "clustering or alternation", "bartels": "trend or serial dependence", "wallis_moore": "too few or many rises and falls",
"turning_points": "too few or many peaks and troughs", "von_neumann": "successive values too alike or too different",
"ljung_box": "autocorrelation", "box_pierce": "autocorrelation", "mcleod_li": "autocorrelation of squares (volatility)",
"arch": "volatility clustering", "bds": "any dependence, including nonlinear"}
def run(t):
if t == "runs":
return ts.runs_test(x)
if t == "bartels":
return ts.bartels(x)
if t == "wallis_moore":
return ts.wallis_moore(x, WM_CORRECTION)
if t == "turning_points":
return ts.turning_points(x)
if t == "von_neumann":
return ts.von_neumann(x)
if t == "ljung_box":
return ts.portmanteau(x, lag, "ljung", FITDF)
if t == "box_pierce":
return ts.portmanteau(x, lag, "box", FITDF)
if t == "mcleod_li":
return ts.mcleod_li(x, lag)
if t == "arch":
return ts.arch_lm(x, ARCH_LAGS)
return ts.bds(x, BDS_DIM, BDS_DIST)
# %% Tests
tests = ["runs", "bartels", "turning_points", "von_neumann", "ljung_box", "mcleod_li", "arch"] if TEST == "battery" else [TEST]
# The shortest series each test can use (the portmanteau tests need more values than lags, the ARCH regression
# more rows than coefficients), and a series that varies (registry/errors.yaml; the same checks in R).
MIN_N = {"runs": 3, "bartels": 3, "wallis_moore": 3, "turning_points": 3, "von_neumann": 3, "ljung_box": lag + 2,
"box_pierce": lag + 2, "mcleod_li": lag + 2, "arch": 2 * ARCH_LAGS + 2, "bds": BDS_DIM + 2}
cs.check_rows(n, max(MIN_N[t] for t in tests), "The randomness tests")
check_not_constant(x, VALUE)
res = {t: run(t) for t in tests}
rows = [{"test": LABELS[t], "looks_for": LOOKS[t], "statistic": res[t]["stat"], "df": res[t].get("df"), "p": res[t]["p"],
"verdict": "not random" if res[t]["p"] < 0.05 else "no evidence"} for t in tests]
values = {"n_obs": n, "test": TEST, "test_label": LABELS[TEST], "lag": lag}
main = res[tests[0]]
values.update({"stat": main["stat"], "p": main["p"], "reject": int(main["p"] < 0.05)})
if main.get("df") is not None:
values["df"] = main["df"]
if TEST == "runs":
values["runs"] = main["runs"]
if TEST == "battery":
for t in tests:
values[f"{t}_stat"] = res[t]["stat"]
values[f"{t}_p"] = res[t]["p"]
values["n_reject"] = sum(1 for t in tests if res[t]["p"] < 0.05)
flagged = [LOOKS[t] for t in tests if res[t]["p"] < 0.05]
summary = (f"{values['n_reject']} of {len(tests)} randomness tests reject at α = .05 for {VALUE} ({n} observations)"
+ (": " + "; ".join(flagged) + "." if flagged else " — consistent with independent noise."))
else:
summary = f"{LABELS[TEST]} for {VALUE}: {main['stat']:.3f}, {cs.fmt_p(main['p'])} — " + (f"evidence of {LOOKS[TEST]}." if main["p"] < 0.05 else "no evidence against randomness.")
kind = "temporal" if TEMPORAL else "numeric"
charts = [cs.chart("acf", "acf", f"Autocorrelation of {VALUE}", {"y": cs.col(VALUE, x)}),
cs.chart("lb", "ljung-box-p", f"Ljung–Box p by lag: {VALUE}", {"y": cs.col(VALUE, x)}, controls={"fitdf": FITDF})]
cs.publish({
"method": "ts.randomness",
"methodVersion": "1.1.1",
"title": "Randomness and serial-dependence tests",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": "; ".join(f"{r['test']} = {r['statistic']:.2f}, {cs.fmt_p(r['p'])}" for r in rows),
"statistics": [{"key": "stat", "label": LABELS[tests[0]], "value": main["stat"]}, {"key": "p", "label": "p", "value": main["p"]}],
"tables": [{
"key": "tests", "title": "Randomness tests",
"columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "looks_for", "label": "Sensitive to", "type": "string"},
{"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "df", "label": "df", "type": "integer"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "verdict", "label": "At α = .05", "type": "string"}],
"rows": rows,
}],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": [f"Portmanteau tests use {lag} lags" + (f" and {FITDF} model degrees of freedom" if FITDF else "") + ".",
"Several tests on one series inflate false alarms: a single rejection at p near .05 is weak evidence."],
"charts": charts,
"values": values,
})
Compare the two Autocorrelation charts. Ljung–Box, which sums squared autocorrelations, gives Q = 8.7 for the noise and Q = 162.0 for the series with memory. Where do you see the difference first in the charts?
What breaks
ReadMost of the tests you've met assume independent rows. With positive autocorrelation:
- Standard errors come out too small, since overstates the information.
- p-values come out too small, and confidence intervals too narrow.
- Regressions between unrelated series look strong.
Larger samples don't repair this. They make the mistake look more confident.
Your own series
ReflectThink of a metric you track over time. If you compared this month with last month using a t test on daily values, what would be wrong with that test?
Write down what you think the value of today depends on: yesterday, the same day last week, or something outside the series.
Time must be evenly spaced
ReflectMost series methods assume one value per period. A daily series with missing days isn't the same as one with zeros on those days.
If a store was closed, zero may be right. If a sensor failed, the value is unknown. Forecast methods in CodeSplash fill gaps by interpolation, and report how many they filled.
What does a gap mean in your own series?
Check your understanding
CheckpointCheck yourself
You have values with . Using , what is the effective sample size?
Show the answer
Answer: 40
.
Check yourself
A t test treats 365 strongly autocorrelated daily values as independent. What's the likely result?
Show the answer
Answer: b
The mean is fine. Its uncertainty is understated, because the values hold less information than their count suggests.
Check yourself
You shuffle a strongly autocorrelated series. What happens to ?
Show the answer
Answer: b
Shuffling keeps the values and destroys their order, and autocorrelation depends on the order alone.
In code
Readimport pandas as pd
from statsmodels.tsa.stattools import acf
df = pd.read_csv("series.csv")
print(acf(df["value"], nlags=12))df <- read.csv("series.csv")
acf(df$value, lag.max = 12)Recap
Recap- A series carries information in its order, and summaries that ignore it can't see that.
- Autocorrelation shrinks the effective sample size, sometimes by a lot.
- Tests that assume independence then give standard errors and p-values that are too small.
- Decide what gaps mean before you model.
Concepts in this lesson