Is it trending? Mann–Kendall and Sen's slope
Test for a monotonic trend without assuming a straight line or normal errors, correct for autocorrelation, and handle seasons and covariates.
What runs in CodeSplash
- STAT226Mann–Kendall trend test Runs in CodeSplash
- STAT227Seasonal Kendall or Hirsch–Slack test Runs in CodeSplash
- STAT228Partial Mann–Kendall test Runs in CodeSplash
- STAT229Cox–Stuart trend test Runs in CodeSplash
- Monotonic trend tests (Mann–Kendall family) Verified in Python and R
You will be able to
- Compute Mann–Kendall's S on a short series, and estimate Sen's slope
- Explain why autocorrelation inflates the test, and choose a correction
- Pick seasonal, partial or Cox–Stuart versions when they fit
Count the pairs
ReadThe Mann–KendallMann–Kendall testA rank test of whether a series tends to rise (or fall) over time — S counts later values above earlier ones minus those below. test looks at every pair of times, and asks: did the later value go up or down?
is large and positive if later values tend to be higher. No line, no normal errors: a rising curve counts as much as a straight one. The price is that this test only looks for a monotonic trend.
For , the six pairs give , so .
Then ask how much
ReadA p-value doesn't say how fast. Sen's slopeSen's slopeThe median of the slopes between every pair of observations — a trend per period that one outlier cannot drag. is the median of all pairwise slopes:
For a simulated series with 60 values: S = 462, = 0.26, p = .003, and a Sen slope of 0.021 per step, with an interval from 0.008 to 0.036.
Exact p for short series
ReadThe usual p-value treats as normal. For a short series without ties you can count instead: under no trend every ordering of the values is equally likely, so the exact distribution of is known. Turn on Exact p for short series. On the same series the exact p is p = .003, against p = .003 from the normal approximation. With ties, a serial-correlation correction or more than 200 values, the card keeps the normal p and says why.
Check yourself
When can the exact Mann–Kendall p-value be used?
Show the answer
Answer: b
The exact distribution assumes every ordering of distinct values is equally likely under no trend. Ties break that count, and the corrections change the variance of S rather than its distribution.
Autocorrelation fools it
PredictPredict first
Mann–Kendall assumes independent values. A series has no trend but strong positive autocorrelation. At 0.05, how often does the plain test reject?
Reveal
Far more than 5%. Runs of high values look like a trend, and the variance of is understated. This matters for almost any real series. Check on your card first.
Corrections, side by side
In the appOn a simulated series with a real trend plus autocorrelation, = 0.62:
| Serial correlation | z |
|---|---|
| Hamed–Rao variance correction | 4.65 |
| Yue–Wang effective sample size | 4.38 |
| Prewhitening (von Storch) | 2.97 |
| Trend-free prewhitening | 9.87 |
Mann–Kendall (Hamed–Rao): z = 4.65, p < .001
- z
- 4.648
- p
- 3.353e-6
- S
- 5,796
- Kendall's τ
- 0.4557
Effect size
- Sen's slope (per observation) 0.0183 95% CI [0.0150, 0.0218]
Plots
View data
| week | ar_trend |
|---|---|
| 1,641,168,000,000 | −0.7249 |
| 1,641,772,800,000 | −0.8144 |
| 1,642,377,600,000 | −1.593 |
| 1,642,982,400,000 | −0.5502 |
| 1,643,587,200,000 | −1.424 |
| 1,644,192,000,000 | −2.052 |
| 1,644,796,800,000 | 0.2228 |
| 1,645,401,600,000 | −0.4542 |
| 1,646,006,400,000 | 0.0818 |
| 1,646,611,200,000 | 1.242 |
| 1,647,216,000,000 | 0.4796 |
| 1,647,820,800,000 | −0.0179 |
| 1,648,425,600,000 | 0.8580 |
| 1,649,030,400,000 | 0.5271 |
| 1,649,635,200,000 | 0.0796 |
| 1,650,240,000,000 | 0.2388 |
| 1,650,844,800,000 | 0.0424 |
| 1,651,449,600,000 | 1.527 |
| 1,652,054,400,000 | 0.9098 |
| 1,652,659,200,000 | 0.2442 |
| 1,653,264,000,000 | 0.4342 |
| 1,653,868,800,000 | 1.375 |
| 1,654,473,600,000 | 0.8262 |
| 1,655,078,400,000 | −0.2258 |
| 1,655,683,200,000 | 0.3760 |
| 1,656,288,000,000 | 0.1970 |
| 1,656,892,800,000 | 0.7933 |
| 1,657,497,600,000 | 1.574 |
| 1,658,102,400,000 | 1.804 |
| 1,658,707,200,000 | 1.891 |
| 1,659,312,000,000 | 2.481 |
| 1,659,916,800,000 | 1.821 |
| 1,660,521,600,000 | 0.3896 |
| 1,661,126,400,000 | −0.0543 |
| 1,661,731,200,000 | 1.336 |
| 1,662,336,000,000 | 2.357 |
| 1,662,940,800,000 | 1.321 |
| 1,663,545,600,000 | 1.419 |
| 1,664,150,400,000 | 2.183 |
| 1,664,755,200,000 | 2.816 |
| 1,665,360,000,000 | 2.618 |
| 1,665,964,800,000 | 1.906 |
| 1,666,569,600,000 | 1.853 |
| 1,667,174,400,000 | 2.077 |
| 1,667,779,200,000 | 1.353 |
| 1,668,384,000,000 | 1.436 |
| 1,668,988,800,000 | 1.159 |
| 1,669,593,600,000 | 2.082 |
| 1,670,198,400,000 | 1.115 |
| 1,670,803,200,000 | 0.5003 |
| 1,671,408,000,000 | −0.2215 |
| 1,672,012,800,000 | 1.073 |
| 1,672,617,600,000 | 1.159 |
| 1,673,222,400,000 | 0.6409 |
| 1,673,827,200,000 | 2.863 |
| 1,674,432,000,000 | 4.018 |
| 1,675,036,800,000 | 2.575 |
| 1,675,641,600,000 | 3.407 |
| 1,676,246,400,000 | 3.640 |
| 1,676,851,200,000 | 2.079 |
First 60 of 160 rows.
Assumptions
- Independent values — Lag-1 autocorrelation 0.62 — accounted for by the hamed–rao correction.
- Enough observations — 160 observations
Trend tests
| Test | S | Var(S) | z | p |
|---|---|---|---|---|
| Mann–Kendall (Hamed–Rao) | 5,796 | 1.554e+6 | 4.648 | < .001 |
| Mann–Kendall (uncorrected, for comparison) | 5,796 | 459333.33 | 8.550 | < .001 |
- The tests use ranks, so outliers and the shape of the trend (straight or curved) do not matter; they detect monotonic change only.
- This correction still rejects too often on autocorrelated series: about 15–17% at the 5% level with lag-1 autocorrelation .3 and 100 values, in simulations with no trend. Pre-whitening held near 5%.
The exact R script · R R version 4.5.1 (2025-06-13)
# Monotonic trend tests (Mann–Kendall family)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.trend 2.1.0 · spec f54db6b6b0242243
# Dataset: s3_shifts (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/s3_shifts.parquet", col_select = c("ar_trend", "week")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("ar_trend", "week")]), , 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("ar_trend", "week")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "ar_trend"
TIME <- "week"
TEMPORAL <- TRUE
SEASON <- NULL
COVARIATE <- NULL
TEST <- "mann_kendall"
CORRECTION <- "hamed_rao"
PERIOD <- NULL
HIRSCH_SLACK <- FALSE
SPLIT <- "halves"
EXACT <- TRUE
MK_EXACT <- FALSE
ALTERNATIVE <- "two-sided"
CONF <- 0.95
s <- cs_ts_ordered(df, VALUE, TIME, TEMPORAL)
d <- s$df
keep <- !is.na(d[[VALUE]])
if (TEST == "partial") {
if (is.null(COVARIATE)) stop("The partial Mann–Kendall test needs a covariate.")
keep <- keep & !is.na(d[[COVARIATE]])
}
if (sum(!keep) > 0) warnings <- c(warnings, sprintf("%d rows with missing values were left out; the tests assume one value per evenly spaced time.", sum(!keep)))
d <- d[keep, , drop = FALSE]
x <- as.numeric(d[[VALUE]])
labels <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]], TEMPORAL) else seq_along(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))
cs_check_rows(n, 4, "A trend test") # stops with a catalog message (registry/errors.yaml)
NUMERIC_TIME <- !is.null(TIME) && !TEMPORAL
tvals <- if (NUMERIC_TIME) as.numeric(d[[TIME]]) else seq_len(n)
unit <- if (NUMERIC_TIME) sprintf("per unit of %s", TIME) else "per observation"
LABELS <- list(mann_kendall = "Mann–Kendall", seasonal = "Seasonal Kendall", partial = "Partial Mann–Kendall", cox_stuart = "Cox–Stuart")
CORR_LABELS <- list(none = "", hamed_rao = " (Hamed–Rao)", yue_wang = " (Yue–Wang)", prewhiten = " (prewhitened)", tfpw = " (trend-free prewhitened)")
fmt4 <- function(v) formatC(v, digits = 4, format = "g")
# %% Test
values <- list(n_obs = n, test = TEST)
rows <- list()
eff <- list()
slope_line <- NULL
exact_note <- NULL
if (TEST == "mann_kendall") {
r <- cs_tr_mann_kendall(x, tvals, ALTERNATIVE, CORRECTION, CONF)
label <- paste0(LABELS[[TEST]], CORR_LABELS[[CORRECTION]])
values <- c(values, list(stat = r$z, p = r$p, s = r$s, var_s = r$var_s, tau = r$tau, sen_slope = r$sen_slope, sen_low = r$sen_low,
sen_high = r$sen_high, intercept = r$intercept, slope_unit = unit, ratio = r$ratio, n_used = r$n_used))
if (!is.null(r$r1)) values$r1 <- r$r1
if (MK_EXACT) { # exact null distribution of S (twin of codesplash.stats.trend_exact)
if (CORRECTION != "none") {
exact_note <- "The exact p-value is for independent values, so with a serial-correlation correction the corrected normal p is reported."
} else if (length(unique(x)) < n) {
exact_note <- "The series has tied values, so the exact p-value (which assumes distinct values) is not available; the tie-corrected normal p is reported."
} else if (n > cs_mk_exact_max_n()) {
exact_note <- sprintf("With more than %d values the normal approximation is used; it is accurate at this size.", cs_mk_exact_max_n())
} else {
values$p_normal <- r$p
r$p <- cs_mk_exact_p(r$s, n, ALTERNATIVE)
values$p <- r$p
label <- paste0(label, ", exact p")
exact_note <- "The p-value is exact: it counts the orderings of distinct values with an S at least as extreme (Kendall 1975); z is shown for reference."
}
}
rows[[1]] <- list(test = label, s = r$s, var_s = r$var_s, z = r$z, p = r$p)
if (CORRECTION != "none") {
cc <- cs_tr_mann_kendall(x, tvals, ALTERNATIVE, "none", CONF)
rows[[2]] <- list(test = "Mann–Kendall (uncorrected, for comparison)", s = cc$s, var_s = cc$var_s, z = cc$z, p = cc$p)
}
eff <- list(list(key = "sen_slope", label = sprintf("Sen's slope (%s)", unit), value = r$sen_slope, ciLow = r$sen_low, ciHigh = r$sen_high,
ciLevel = CONF, method = "Median of pairwise slopes; Gilbert's (1987) rank interval from Var(S)"))
if (!NUMERIC_TIME) slope_line <- c(r$sen_slope, r$intercept)
} else if (TEST == "seasonal") {
period <- NULL
if (!is.null(SEASON)) {
season <- as.character(d[[SEASON]])
} else {
period <- if (!is.null(PERIOD)) as.integer(PERIOD) else if (!is.null(TIME)) cs_ts_guess_period(d[[TIME]], TEMPORAL) else NULL
if (is.null(period)) stop("Choose a season column or set the season length: it could not be read from the time column.")
season <- (seq_len(n) - 1) %% period
}
r <- cs_tr_seasonal_kendall(x, season, ALTERNATIVE, HIRSCH_SLACK, CONF)
if (HIRSCH_SLACK && !r$hirsch_slack) warnings <- c(warnings, "Seasons were not all observed in the same number of years: the Hirsch–Slack covariance was not used.")
label <- paste0("Seasonal Kendall", if (r$hirsch_slack) " (Hirsch–Slack covariance)" else "")
values <- c(values, list(stat = r$z, p = r$p, s = r$s, var_s = r$var_s, seasons = r$seasons, hirsch_slack = as.integer(r$hirsch_slack),
sen_slope = r$sen_slope, slope_unit = "per cycle"))
if (!is.null(period)) values$period <- period
rows[[1]] <- list(test = label, s = r$s, var_s = r$var_s, z = r$z, p = r$p)
eff <- list(list(key = "sen_slope", label = "Seasonal Sen slope (per cycle)", value = r$sen_slope,
method = "Median of within-season pairwise slopes per cycle (Hirsch et al. 1982)"))
if (!NUMERIC_TIME) {
per <- if (is.null(period)) r$seasons else period
b <- r$sen_slope / per
slope_line <- c(b, stats::median(x - b * seq_len(n)))
}
} else if (TEST == "partial") {
cs_check_not_constant(d[[COVARIATE]], COVARIATE) # the adjustment divides by the covariate's variance (registry/errors.yaml)
r <- cs_tr_partial_mann_kendall(x, as.numeric(d[[COVARIATE]]), ALTERNATIVE)
label <- LABELS[[TEST]]
values <- c(values, list(stat = r$z, p = r$p, s = r$s, var_s = r$var_s, cor = r$cor, s_covariate = r$s_covariate))
rows[[1]] <- list(test = sprintf("%s (adjusted for %s)", label, COVARIATE), s = r$s, var_s = r$var_s, z = r$z, p = r$p)
cc <- cs_tr_mann_kendall(x, tvals, ALTERNATIVE, "none", 0.95)
rows[[2]] <- list(test = "Mann–Kendall (unadjusted, for comparison)", s = cc$s, var_s = cc$var_s, z = cc$z, p = cc$p)
} else {
r <- cs_tr_cox_stuart(x, ALTERNATIVE, SPLIT, EXACT)
label <- paste0(LABELS[[TEST]], if (EXACT) " (exact)" else "")
values <- c(values, list(stat = r$z, p = r$p, pairs = r$pairs, increases = r$s))
if (r$pairs == 0) {
values["stat"] <- list(NULL)
values["p"] <- list(NULL)
warnings <- c(warnings, "Every paired difference is zero, so the Cox–Stuart test has no informative pairs and no p-value.")
}
rows[[1]] <- list(test = label, s = r$s, var_s = r$pairs / 4, z = r$z, p = r$p)
}
values$test_label <- label
values$reject <- as.integer(isTRUE(values$p < 0.05))
s_sign <- if (!is.null(values$s)) values$s else values$increases - values$pairs / 2
values$direction <- if (s_sign > 0) "increasing" else if (s_sign < 0) "decreasing" else "flat"
# %% Assumptions
sen_idx <- cs_tr_sen_slope(x)$slope
if (is.null(values$sen_slope)) values$sen_slope <- sen_idx # per time step when the test has no slope of its own
detr <- x - sen_idx * seq_len(n)
dm <- detr - mean(detr)
# A detrended series without variation (a constant or exactly linear series) has no autocorrelation: rho1 is
# left empty in both engines (the 1e-12 relative floor ignores rounding noise).
flat <- max(abs(dm)) <= 1e-12 * max(1, max(abs(detr)))
rho1 <- if (flat) NA else sum(dm[-1] * dm[-n]) / sum(dm * dm)
values$rho1 <- rho1
crit <- 1.959963984540054 / sqrt(n)
corrected <- TEST == "mann_kendall" && CORRECTION != "none"
if (flat) {
ind <- c("info", "The detrended series has no variation, so its lag-1 autocorrelation is undefined.")
} else if (abs(rho1) <= crit) {
ind <- c("pass", sprintf("Lag-1 autocorrelation of the detrended series is %.2f (|ρ₁| ≤ %.2f).", rho1, crit))
} else if (corrected) {
ind <- c("pass", sprintf("Lag-1 autocorrelation %.2f — accounted for by the %s correction.", rho1, gsub("_", "–", CORRECTION)))
} else if (TEST == "seasonal") {
ind <- c("info", sprintf("Lag-1 autocorrelation %.2f: consecutive seasons move together; the Hirsch–Slack covariance allows for it between seasons.", rho1))
} else {
ind <- c("warn", sprintf("Lag-1 autocorrelation of the detrended series is %.2f (> %.2f): the classic variance is too small, so p is too optimistic.", rho1, crit))
}
assumptions <- list(list(key = "independence", label = "Independent values", status = ind[1], detail = ind[2]),
list(key = "length", label = "Enough observations", status = if (n >= 10) "pass" else "warn",
detail = paste0(n, " observations", if (n >= 10) "" else " — the normal approximation to S is rough below about 10.")))
# %% Report
verdict <- if (values$reject == 1) sprintf("a monotonic %s trend", values$direction) else "no evidence of a monotonic trend"
z_txt <- if (!is.null(values$stat)) sprintf("z = %.2f", values$stat) else "z undefined"
summary <- sprintf("%s for %s (%d observations): %s, %s — %s.", label, VALUE, n, z_txt, cs_fmt_p(values$p), verdict)
if (TEST == "mann_kendall") {
summary <- paste0(summary, sprintf(" Sen's slope %s %s (%d%% CI %s to %s).", fmt4(values$sen_slope), unit, round(CONF * 100), fmt4(values$sen_low), fmt4(values$sen_high)))
} else if (TEST == "seasonal") {
summary <- paste0(summary, sprintf(" Seasonal Sen slope %s per cycle.", fmt4(values$sen_slope)))
}
kind <- if (TEMPORAL) "temporal" else "numeric"
xcol <- cs_col(if (is.null(TIME)) "index" else TIME, labels, kind = kind)
controls <- list(confLevel = if (TEST == "mann_kendall") CONF else 0.95)
roles <- list(x = xcol, y = cs_col(VALUE, x))
if (!is.null(slope_line) && TEST == "seasonal") roles$fit <- cs_col("seasonal Sen trend", slope_line[2] + slope_line[1] * seq_len(n))
charts <- list(cs_chart("trend", "mann-kendall-sen", sprintf("%s with Sen's slope", VALUE), roles, controls = controls))
if (TEST == "partial") charts[[2]] <- cs_chart("covariate", "series-line", sprintf("%s over time", COVARIATE), list(x = xcol, y = cs_col(COVARIATE, as.numeric(d[[COVARIATE]]))))
notes <- list("The tests use ranks, so outliers and the shape of the trend (straight or curved) do not matter; they detect monotonic change only.")
if (TEST == "mann_kendall" && CORRECTION %in% c("hamed_rao", "yue_wang", "tfpw")) notes <- c(notes, "This correction still rejects too often on autocorrelated series: about 15–17% at the 5% level with lag-1 autocorrelation .3 and 100 values, in simulations with no trend. Pre-whitening held near 5%.")
if (!is.null(exact_note)) notes <- c(notes, exact_note)
if (TEST == "seasonal") notes <- c(notes, "Each season is compared only with itself (January with January), so a seasonal cycle is not mistaken for a trend.")
stats_list <- list(list(key = "stat", label = "z", value = values$stat), list(key = "p", label = "p", value = values$p))
if (!is.null(values$s)) stats_list <- c(stats_list, list(list(key = "s", label = "S", value = values$s)))
if (!is.null(values$tau)) stats_list <- c(stats_list, list(list(key = "tau", label = "Kendall's τ", value = values$tau)))
cs_publish(list(
method = "ts.trend",
methodVersion = "2.1.0",
title = "Trend test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s: %s, %s", label, z_txt, cs_fmt_p(values$p)),
statistics = stats_list,
tables = list(list(
key = "tests", title = "Trend tests",
columns = list(list(key = "test", label = "Test", type = "string"), list(key = "s", label = "S", type = "number"),
list(key = "var_s", label = "Var(S)", type = "number"), list(key = "z", label = "z", type = "number"),
list(key = "p", label = "p", type = "pvalue")),
rows = rows
)),
effectSizes = eff,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Mann–Kendall (Hamed–Rao): z = 4.65, p < .001
- z
- 4.648
- p
- 3.353e-6
- S
- 5,796
- Kendall's τ
- 0.4557
Effect size
- Sen's slope (per observation) 0.0183 95% CI [0.0150, 0.0218]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent values — Lag-1 autocorrelation 0.62 — accounted for by the hamed–rao correction.
- Enough observations — 160 observations
Trend tests
| Test | S | Var(S) | z | p |
|---|---|---|---|---|
| Mann–Kendall (Hamed–Rao) | 5,796 | 1.554e+6 | 4.648 | < .001 |
| Mann–Kendall (uncorrected, for comparison) | 5,796 | 459333.33 | 8.550 | < .001 |
- The tests use ranks, so outliers and the shape of the trend (straight or curved) do not matter; they detect monotonic change only.
- This correction still rejects too often on autocorrelated series: about 15–17% at the 5% level with lag-1 autocorrelation .3 and 100 values, in simulations with no trend. Pre-whitening held near 5%.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Monotonic trend tests (Mann–Kendall family)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.trend 2.1.0 · spec f54db6b6b0242243
# Dataset: s3_shifts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import trend, ts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s3_shifts.parquet", columns=["ar_trend", "week"])
n_input = len(df)
df = df.dropna(subset=["ar_trend", "week"]) # 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, ["ar_trend", "week"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "ar_trend"
TIME = "week"
TEMPORAL = True
SEASON = None
COVARIATE = None
TEST = "mann_kendall"
CORRECTION = "hamed_rao"
PERIOD = None
HIRSCH_SLACK = False
SPLIT = "halves"
EXACT = True
MK_EXACT = False
ALTERNATIVE = "two-sided"
CONF = 0.95
s = ts.ordered(df, VALUE, TIME, TEMPORAL)
d = s["df"].reset_index(drop=True)
keep = d[VALUE].notna()
if TEST == "partial":
if not COVARIATE:
raise ValueError("The partial Mann–Kendall test needs a covariate.")
keep &= d[COVARIATE].notna()
if (~keep).sum():
warnings.append(f"{int((~keep).sum())} rows with missing values were left out; the tests assume one value per evenly spaced time.")
d = d[keep].reset_index(drop=True)
x = d[VALUE].to_numpy(dtype=float)
labels = ts.time_labels(d[TIME].to_numpy(), TEMPORAL) if TIME else list(range(1, len(x) + 1))
n = len(x)
if s["dups"]:
warnings.append(f"{s['dups']} repeated time values: the tests assume one observation per evenly spaced time.")
cs.check_rows(n, 4, "A trend test") # stops with a catalog message (registry/errors.yaml)
NUMERIC_TIME = bool(TIME) and not TEMPORAL
tvals = d[TIME].to_numpy(dtype=float) if NUMERIC_TIME else np.arange(1.0, n + 1.0)
unit = f"per unit of {TIME}" if NUMERIC_TIME else "per observation"
LABELS = {"mann_kendall": "Mann–Kendall", "seasonal": "Seasonal Kendall", "partial": "Partial Mann–Kendall", "cox_stuart": "Cox–Stuart"}
CORR_LABELS = {"none": "", "hamed_rao": " (Hamed–Rao)", "yue_wang": " (Yue–Wang)", "prewhiten": " (prewhitened)", "tfpw": " (trend-free prewhitened)"}
# %% Test
values = {"n_obs": n, "test": TEST}
rows = []
eff = []
slope_line = None # (slope, intercept) on the observation index, for the chart
exact_note = None
if TEST == "mann_kendall":
r = trend.mann_kendall(x, tvals, ALTERNATIVE, CORRECTION, CONF)
label = LABELS[TEST] + CORR_LABELS[CORRECTION]
values.update({"stat": r["z"], "p": r["p"], "s": r["s"], "var_s": r["var_s"], "tau": r["tau"], "sen_slope": r["sen_slope"],
"sen_low": r["sen_low"], "sen_high": r["sen_high"], "intercept": r["intercept"], "slope_unit": unit,
"ratio": r["ratio"], "n_used": r["n_used"]})
if r["r1"] is not None:
values["r1"] = r["r1"]
if MK_EXACT:
from codesplash.stats import trend_exact as tex # exact null distribution of S (twin of R's cs_mk_exact_p)
if CORRECTION != "none":
exact_note = "The exact p-value is for independent values, so with a serial-correlation correction the corrected normal p is reported."
elif len(np.unique(x)) < n:
exact_note = "The series has tied values, so the exact p-value (which assumes distinct values) is not available; the tie-corrected normal p is reported."
elif n > tex.MAX_N:
exact_note = f"With more than {tex.MAX_N} values the normal approximation is used; it is accurate at this size."
else:
values["p_normal"] = r["p"]
r = {**r, "p": tex.mk_exact_p(r["s"], n, ALTERNATIVE)}
values["p"] = r["p"]
label += ", exact p"
exact_note = "The p-value is exact: it counts the orderings of distinct values with an S at least as extreme (Kendall 1975); z is shown for reference."
rows.append({"test": label, "s": r["s"], "var_s": r["var_s"], "z": r["z"], "p": r["p"]})
if CORRECTION != "none":
c = trend.mann_kendall(x, tvals, ALTERNATIVE, "none", CONF)
rows.append({"test": "Mann–Kendall (uncorrected, for comparison)", "s": c["s"], "var_s": c["var_s"], "z": c["z"], "p": c["p"]})
eff.append({"key": "sen_slope", "label": f"Sen's slope ({unit})", "value": r["sen_slope"], "ciLow": r["sen_low"], "ciHigh": r["sen_high"],
"ciLevel": CONF, "method": "Median of pairwise slopes; Gilbert's (1987) rank interval from Var(S)"})
if not NUMERIC_TIME:
slope_line = (r["sen_slope"], r["intercept"])
elif TEST == "seasonal":
if SEASON:
season = d[SEASON].astype(str).to_numpy()
period = None
else:
period = int(PERIOD) if PERIOD is not None else ts.guess_period(d[TIME].to_numpy(), TEMPORAL) if TIME else None
if period is None:
raise ValueError("Choose a season column or set the season length: it could not be read from the time column.")
season = np.arange(n) % period
r = trend.seasonal_kendall(x, season, ALTERNATIVE, HIRSCH_SLACK, CONF)
if HIRSCH_SLACK and not r["hirsch_slack"]:
warnings.append("Seasons were not all observed in the same number of years: the Hirsch–Slack covariance was not used.")
label = "Seasonal Kendall" + (" (Hirsch–Slack covariance)" if r["hirsch_slack"] else "")
values.update({"stat": r["z"], "p": r["p"], "s": r["s"], "var_s": r["var_s"], "seasons": r["seasons"], "hirsch_slack": int(r["hirsch_slack"]),
"sen_slope": r["sen_slope"], "slope_unit": "per cycle"})
if period is not None:
values["period"] = period
rows.append({"test": label, "s": r["s"], "var_s": r["var_s"], "z": r["z"], "p": r["p"]})
eff.append({"key": "sen_slope", "label": "Seasonal Sen slope (per cycle)", "value": r["sen_slope"],
"method": "Median of within-season pairwise slopes per cycle (Hirsch et al. 1982)"})
if not NUMERIC_TIME:
per = r["seasons"] if period is None else period
b = r["sen_slope"] / per
slope_line = (b, float(np.median(x - b * np.arange(1.0, n + 1.0))))
elif TEST == "partial":
check_not_constant(d[COVARIATE], COVARIATE) # the adjustment divides by the covariate's variance (registry/errors.yaml)
r = trend.partial_mann_kendall(x, d[COVARIATE].to_numpy(dtype=float), ALTERNATIVE)
label = LABELS[TEST]
values.update({"stat": r["z"], "p": r["p"], "s": r["s"], "var_s": r["var_s"], "cor": r["cor"], "s_covariate": r["s_covariate"]})
rows.append({"test": f"{label} (adjusted for {COVARIATE})", "s": r["s"], "var_s": r["var_s"], "z": r["z"], "p": r["p"]})
c = trend.mann_kendall(x, tvals, ALTERNATIVE, "none", 0.95)
rows.append({"test": "Mann–Kendall (unadjusted, for comparison)", "s": c["s"], "var_s": c["var_s"], "z": c["z"], "p": c["p"]})
else:
r = trend.cox_stuart(x, ALTERNATIVE, SPLIT, EXACT)
label = LABELS[TEST] + (" (exact)" if EXACT else "")
values.update({"stat": r["z"], "p": r["p"], "pairs": r["pairs"], "increases": r["s"]})
if r["pairs"] == 0:
values.update({"stat": None, "p": None})
warnings.append("Every paired difference is zero, so the Cox–Stuart test has no informative pairs and no p-value.")
rows.append({"test": label, "s": r["s"], "var_s": r["pairs"] / 4.0, "z": r["z"], "p": r["p"]})
values["test_label"] = label
values["reject"] = int(values["p"] is not None and values["p"] < 0.05)
s_sign = values.get("s", values.get("increases", 0) - values.get("pairs", 0) / 2.0)
values["direction"] = "increasing" if s_sign > 0 else "decreasing" if s_sign < 0 else "flat"
# %% Assumptions
sen_idx = trend.sen_slope(x)["slope"]
values.setdefault("sen_slope", float(sen_idx)) # per time step when the test has no slope of its own
detr = x - sen_idx * np.arange(1.0, n + 1.0)
dm = detr - detr.mean()
# A detrended series without variation (a constant or exactly linear series) has no autocorrelation: ρ₁ is
# left empty in both engines (the 1e-12 relative floor ignores rounding noise).
flat = float(np.max(np.abs(dm))) <= 1e-12 * max(1.0, float(np.max(np.abs(detr))))
rho1 = None if flat else float((dm[1:] @ dm[:-1]) / (dm @ dm))
values["rho1"] = rho1
crit = 1.959963984540054 / math.sqrt(n)
corrected = TEST == "mann_kendall" and CORRECTION != "none"
if rho1 is None:
ind_status, ind_detail = "info", "The detrended series has no variation, so its lag-1 autocorrelation is undefined."
elif abs(rho1) <= crit:
ind_status, ind_detail = "pass", f"Lag-1 autocorrelation of the detrended series is {rho1:.2f} (|ρ₁| ≤ {crit:.2f})."
elif corrected:
ind_status, ind_detail = "pass", f"Lag-1 autocorrelation {rho1:.2f} — accounted for by the {CORRECTION.replace('_', '–')} correction."
elif TEST == "seasonal":
ind_status, ind_detail = "info", f"Lag-1 autocorrelation {rho1:.2f}: consecutive seasons move together; the Hirsch–Slack covariance allows for it between seasons."
else:
ind_status, ind_detail = "warn", f"Lag-1 autocorrelation of the detrended series is {rho1:.2f} (> {crit:.2f}): the classic variance is too small, so p is too optimistic."
assumptions = [{"key": "independence", "label": "Independent values", "status": ind_status, "detail": ind_detail},
{"key": "length", "label": "Enough observations", "status": "pass" if n >= 10 else "warn",
"detail": f"{n} observations" + ("" if n >= 10 else " — the normal approximation to S is rough below about 10.")}]
# %% Report
verdict = f"a monotonic {values['direction']} trend" if values["reject"] else "no evidence of a monotonic trend"
z_txt = f"z = {values['stat']:.2f}" if values["stat"] is not None else "z undefined"
summary = f"{label} for {VALUE} ({n} observations): {z_txt}, {cs.fmt_p(values['p'])} — {verdict}."
if TEST == "mann_kendall":
summary += f" Sen's slope {values['sen_slope']:.4g} {unit} ({round(CONF * 100)}% CI {values['sen_low']:.4g} to {values['sen_high']:.4g})."
elif TEST == "seasonal":
summary += f" Seasonal Sen slope {values['sen_slope']:.4g} per cycle."
kind = "temporal" if TEMPORAL else "numeric"
xcol = cs.col(TIME or "index", labels, kind=kind)
controls = {"confLevel": CONF if TEST == "mann_kendall" else 0.95}
roles = {"x": xcol, "y": cs.col(VALUE, x)}
if slope_line is not None and TEST == "seasonal":
roles["fit"] = cs.col("seasonal Sen trend", slope_line[1] + slope_line[0] * np.arange(1.0, n + 1.0))
charts = [cs.chart("trend", "mann-kendall-sen", f"{VALUE} with Sen's slope", roles, controls=controls)]
if TEST == "partial":
charts.append(cs.chart("covariate", "series-line", f"{COVARIATE} over time", {"x": xcol, "y": cs.col(COVARIATE, d[COVARIATE].to_numpy(dtype=float))}))
notes = ["The tests use ranks, so outliers and the shape of the trend (straight or curved) do not matter; they detect monotonic change only."]
if TEST == "mann_kendall" and CORRECTION in ("hamed_rao", "yue_wang", "tfpw"):
notes.append("This correction still rejects too often on autocorrelated series: about 15–17% at the 5% level with lag-1 autocorrelation .3 and 100 values, in simulations with no trend. Pre-whitening held near 5%.")
if exact_note:
notes.append(exact_note)
if TEST == "seasonal":
notes.append("Each season is compared only with itself (January with January), so a seasonal cycle is not mistaken for a trend.")
cs.publish({
"method": "ts.trend",
"methodVersion": "2.1.0",
"title": "Trend test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{label}: {z_txt}, {cs.fmt_p(values['p'])}",
"statistics": [{"key": "stat", "label": "z", "value": values["stat"]}, {"key": "p", "label": "p", "value": values["p"]}]
+ ([{"key": "s", "label": "S", "value": values["s"]}] if "s" in values else [])
+ ([{"key": "tau", "label": "Kendall's τ", "value": values["tau"]}] if "tau" in values else []),
"tables": [{
"key": "tests", "title": "Trend tests",
"columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "s", "label": "S", "type": "number"},
{"key": "var_s", "label": "Var(S)", "type": "number"}, {"key": "z", "label": "z", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}],
"rows": rows,
}],
"effectSizes": eff,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
The Hamed–Rao variance is 3.4 times the naive one. Trend-free prewhitening gives a much larger z here. Which row would you trust, and why not choose after seeing them?
Picking a correction
ReadVariance corrections keep and widen its variance. Prewhitening removes the AR(1) first, which also removes part of a real trend, so it loses power. Trend-free prewhitening tries to avoid that, and it can over-reject, as the table hints.
The default is None (independent values), so choose a correction yourself when is non-trivial. Hamed–Rao is a reasonable first choice for most series.
On Lake Huron, = 0.76 with no correction. How much would you trust its z = −5.16?
Seasons
PredictPredict first
Monthly water quality rises and falls with the season. If you compare every pair of months, the season adds noise to . What should the seasonal Kendall test compare?
Reveal
January against January, February against February, and so on, summed over seasons. For 12 seasons, z = 0.96, p = .339. Allow correlation between seasons adds Hirsch and Slack's correction: p = .369.
Covariates, and a simpler test
ReflectPartial Mann–Kendall adjusts for a covariate. For river flow and concentration, you might ask if concentration trends after allowing for flow. On simulated data: z = 2.96, p = .003.
Cox–Stuart pairs each value in the first half with its partner in the second half and runs a sign test on the increases, with an exact binomial p-value. On that same series, with 30 pairs and 19 increases, it gives p = .200.
R's trend::cs.test is a different test: first and last thirds, normal p (Compare: First and last thirds). Serial dependence breaks either.
Compare that with Mann–Kendall above. Why might it have less power? When might you still want its simplicity?
Check your understanding
CheckpointCheck yourself
Compute for .
Show the answer
Answer: -4
Pairs: 5→3 (−1), 5→4 (−1), 5→1 (−1), 3→4 (+1), 3→1 (−1), 4→1 (−1). The sum is −4, so the series tends to fall.
Check yourself
Three values at times 1, 2, 3 are . The pairwise slopes are 2, 0 and 1. What is Sen's slope?
Show the answer
Answer: 1
The median of 0, 1 and 2 is 1.
Check yourself
Your card shows = 0.7 and p = 0.002 with no correction. What's your next step?
Show the answer
Answer: b
With strong autocorrelation, the uncorrected p is too small.
Check yourself
A metric rises for two years, then falls for two years. Mann–Kendall gives p = 0.6. What can you say?
Show the answer
Answer: b
Mann–Kendall only looks for a monotonic trend. Plot the series, and consider a change-point test.
Do it in CodeSplash
In the appSet Series and Time, then Test and Serial correlation. This is the Trend step in the Series lab, and the Quality studio's Trend & change step uses it too.
# pip install pymannkendall
import pandas as pd
import pymannkendall as mk
y = pd.read_csv("lakehuron.csv")["level"]
print(mk.original_test(y))
print(mk.hamed_rao_modification_test(y))# install.packages(c("trend", "modifiedmk"))
y <- as.numeric(LakeHuron)
trend::mk.test(y)
trend::sens.slope(y)
modifiedmk::mmkh(y)Recap
Recap- Mann–Kendall counts rises and falls across all pairs, with no line and no normal errors.
- Report Sen's slope with its interval, not only p.
- Autocorrelation inflates the test: check , and choose a correction ahead of time.
- Use the seasonal version for seasonal data, the partial version for a covariate.
Concepts in this lesson