DTime series · ts.trend
Monotonic trend tests (Mann–Kendall family)
Is the series drifting steadily up or down over time — after allowing for seasons, a covariate or serial correlation — and by how much per period?
Mann–Kendall's rank test of a monotonic trend with Sen's slope and its interval, with corrections for serial correlation (Hamed–Rao, Yue–Wang, prewhitening, trend-free prewhitening); the seasonal Kendall (Hirsch–Slack) test for seasonal data; the partial Mann–Kendall test adjusting for a covariate; and the Cox–Stuart sign test. No normality and no straight-line form are assumed.
A real result
Example “Mk guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Mann–Kendall: z = 2.94, p = .003
- z
- 2.940
- p
- 0.0033
- S
- 462
- Kendall's τ
- 0.2610
Effect size
- Sen's slope (per unit of t) 0.0207 95% CI [0.0076, 0.0364]
Plots
View data
| t | x |
|---|---|
| 1 | 0.5406 |
| 2 | −1.040 |
| 3 | 0.1992 |
| 4 | −0.0047 |
| 5 | −0.5666 |
| 6 | −2.396 |
| 7 | −0.5951 |
| 8 | −0.8601 |
| 9 | 0.2936 |
| 10 | −0.2738 |
| 11 | −0.1882 |
| 12 | −0.4904 |
| 13 | 0.0386 |
| 14 | 0.0542 |
| 15 | −2.247 |
| 16 | 1.667 |
| 17 | 0.9564 |
| 18 | 0.5776 |
| 19 | −0.4247 |
| 20 | 1.090 |
| 21 | 0.0913 |
| 22 | 0.2753 |
| 23 | −0.9320 |
| 24 | 1.946 |
| 25 | 0.5482 |
| 26 | 2.428 |
| 27 | 2.271 |
| 28 | 0.6181 |
| 29 | 1.225 |
| 30 | 2.326 |
| 31 | 0.0910 |
| 32 | 0.8064 |
| 33 | 0.4053 |
| 34 | 1.013 |
| 35 | 0.8824 |
| 36 | 1.885 |
| 37 | 1.333 |
| 38 | −0.1318 |
| 39 | 1.357 |
| 40 | −0.0249 |
| 41 | −0.3373 |
| 42 | 1.618 |
| 43 | −0.3442 |
| 44 | 1.187 |
| 45 | 0.0663 |
| 46 | 2.338 |
| 47 | 1.652 |
| 48 | 0.5575 |
| 49 | 1.779 |
| 50 | 1.426 |
| 51 | −0.1499 |
| 52 | 0.8338 |
| 53 | 0.1294 |
| 54 | 1.529 |
| 55 | 0.4552 |
| 56 | 0.8886 |
| 57 | −0.0964 |
| 58 | 0.1990 |
| 59 | 1.314 |
| 60 | 0.2009 |
Assumptions
- Independent values — Lag-1 autocorrelation of the detrended series is 0.01 (|ρ₁| ≤ 0.25).
- Enough observations — 60 observations
Trend tests
| Test | S | Var(S) | z | p |
|---|---|---|---|---|
| Mann–Kendall | 462 | 24583.33 | 2.940 | .003 |
- The tests use ranks, so outliers and the shape of the trend (straight or curved) do not matter; they detect monotonic change only.
Mann–Kendall: z = 2.94, p = .003
- z
- 2.940
- p
- 0.0033
- S
- 462
- Kendall's τ
- 0.2610
Effect size
- Sen's slope (per unit of t) 0.0207 95% CI [0.0076, 0.0364]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent values — Lag-1 autocorrelation of the detrended series is 0.01 (|ρ₁| ≤ 0.25).
- Enough observations — 60 observations
Trend tests
| Test | S | Var(S) | z | p |
|---|---|---|---|---|
| Mann–Kendall | 462 | 24583.33 | 2.940 | .003 |
- The tests use ranks, so outliers and the shape of the trend (straight or curved) do not matter; they detect monotonic change only.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Mk guides3_trend · time: t · value: x
- Mk lakehuronts_lakehuron · time: year · value: level
- Mk hamed raos3_shifts · time: week · value: ar_trend
- Mk yue wangs3_shifts · time: week · value: ar_trend
- Mk tfpws3_shifts · time: week · value: ar_trend
- Mk prewhitens3_shifts · value: ar_trend
- Seasonal guides3_seasonal · season: season · time: month · value: x
- Seasonal hirsch slacks3_seasonal · time: month · value: x
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Seriesnumeric · 1 column
- The values over time (one per period).
- Timetemporal / numeric · 0–1 column
- Orders the rows (omit to use the row order). A numeric time sets the unit of Sen's slope.
- Seasoncategorical / numeric · 0–1 column
- Season of each row (month, quarter …) for the seasonal test; omit to use the period below.
- Covariatenumeric · 0–1 column
- A variable that moves with the series (flow for concentrations, say) for the partial test.
Choices you make
hypothesis
- Testdefault mann_kendall
H₀: no monotonic trend (values are exchangeable in time).
- Mann–Kendall with Sen's slope(default) — Counts how often later values exceed earlier ones; robust to outliers and any monotonic shape.
- Seasonal Kendall (Hirsch–Slack) — Compares each season only with itself (January with January), so seasonality is not mistaken for trend.
- Partial Mann–Kendall (adjust for a covariate) — Trend in the series beyond what a related variable explains (Libiseller & Grimvall).
- Cox–Stuart sign test — Compares each value in the first half with its partner in the second half (a sign test): simple, low power, for very short series.
- Serial correlationdefault none
Positive autocorrelation makes the classic test reject too often. Only pre-whitening held near 5% in simulation; the others reach 15–17%.
- None (independent values)(default) — Assumes independent values; use it only when the series shows no autocorrelation, since positive autocorrelation fakes trends.
- Hamed–Rao variance correction — Inflates Var(S) using significant autocorrelations of the ranks of the detrended series.
- Yue–Wang effective sample size — Inflates Var(S) using significant autocorrelations of the detrended values.
- Prewhitening (von Storch) — Removes lag-1 autocorrelation first; can also remove part of a real trend.
- Trend-free prewhitening (Yue et al.) — Removes the trend, prewhitens, then adds the trend back — keeps the trend's power.
- Directiondefault two-sided
Test for any trend, or only an increase or a decrease fixed in advance.
- Any trend(default) — Tests for a trend in either direction; keep it unless you fixed a direction before seeing the data.
- Increasing — Tests only for an increasing trend; pick it only if you fixed this direction before seeing the data.
- Decreasing — Tests only for a decreasing trend; pick it only if you fixed this direction before seeing the data.
options
- Season lengthdefault —
Observations per cycle (12 for monthly) when no season column is given.
- Allow correlation between seasonsdefault off
Hirsch & Slack (1984) covariance: needs every season observed in the same years.
- Comparedefault halves
Which parts of the series the Cox–Stuart test compares.
- First and second halves(default) — Pairs each value in the first half with its partner in the second half; uses all the data (Cox & Stuart 1955, the reference's version).
- First and last thirds — Leaves out the middle third, as trend::cs.test does.
- Exact binomial pdefault on
Use the binomial distribution (the default); turn off for the normal approximation.
- Exact p for short seriesdefault off
Exact p from the null distribution of S (no ties, up to 200 values, no correction); otherwise the normal p is kept.
- Interval level for Sen's slopedefault 0.95
Confidence level of the interval for Sen's slope.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Independent values
The classic variance assumes no serial correlation once the trend is removed; positive autocorrelation inflates false trends.
- If violated → Correct for autocorrelation (Hamed–Rao) — Keeps the same trend statistic and widens its variance by the effective-sample-size factor implied by the significant autocorrelations, so the p-value stops overstating evidence for a trend.
Enough observations
Below about 10 values the normal approximation to S is rough.
What it reports
- n_obs
- How many independent units the analysis used; it sets precision and power.
- stat
- A single number that summarizes how far your data are from what H₀ predicts.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- reject
- A p-value below the chosen α; it says the data are hard to explain by chance alone, not that the effect matters.
- sen_slope
- The median of the slopes between every pair of observations — a trend per period that one outlier cannot drag.
Per group, level or term: test, test_label, s, var_s, tau, sen_slope, sen_low, sen_high, intercept, slope_unit, ratio, r1, rho1, n_used, p_normal, seasons, period, hirsch_slack, cor, s_covariate, pairs, increases, direction
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- With AR(1) errors (ρ = .3, n = 100, no trend, 1,000 series) Hamed–Rao rejects 14.5%, Yue–Wang 14.9% and trend-free pre-whitening 17.2% at the 5% level; pre-whitening stays in the band. The formulas match modifiedmk; this is how those corrections behave (Serinaldi & Kilsby 2016). The card says so when one is chosen.
- Same twin in both engines. Values equal trend::mk.test / sens.slope / smk.test / csmk.test / partial.mk.test / cs.test (cs.test with split = thirds and the normal p; the default since 2.0 is halves with the exact binomial p) (τ is S over n(n−1)/2; z continuity-corrected except for the partial test, as trend).
- Partial Mann–Kendall with tied values: the platform uses the tie-corrected variances and the Hirsch–Slack covariance (Libiseller & Grimvall 2002), while trend::partial.mk.test uses the untied variance n(n−1)(2n+5)/18, so the two agree only without ties (z = 3.593 here vs 3.591 in trend on airquality Temp adjusted for Wind; equal on the guide's example).
- Hamed–Rao and Yue–Wang count autocorrelations at every lag with |ρ_k| > z.975/√n, as modifiedmk::mmkh / mmky; pymannkendall uses all lags by default.
The exact script CodeSplash ran for example “Mk guide” · 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 b9ffcc96363acb3b
# Dataset: s3_trend (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_trend.parquet", columns=["x", "t"])
n_input = len(df)
df = df.dropna(subset=["x", "t"]) # 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, ["x", "t"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "x"
TIME = "t"
TEMPORAL = False
SEASON = None
COVARIATE = None
TEST = "mann_kendall"
CORRECTION = "none"
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 exact script CodeSplash ran for example “Mk guide” · 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 b9ffcc96363acb3b
# Dataset: s3_trend (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_trend.parquet", col_select = c("x", "t")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "t")]), , 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("x", "t")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "x"
TIME <- "t"
TEMPORAL <- FALSE
SEASON <- NULL
COVARIATE <- NULL
TEST <- "mann_kendall"
CORRECTION <- "none"
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
))
Sources
- Serinaldi, F., & Kilsby, C. G. (2016). The importance of prewhitening in change point analysis under persistence. Stochastic Environmental Research and Risk Assessment, 30, 763–777.
- Mann, H. B. (1945). Nonparametric tests against trend. Econometrica, 13, 245–259.
- Kendall, M. G. (1975). Rank correlation methods (4th ed.). Griffin.
- Sen, P. K. (1968). Estimates of the regression coefficient based on Kendall's tau. JASA, 63, 1379–1389.
- Gilbert, R. O. (1987). Statistical methods for environmental pollution monitoring. Van Nostrand Reinhold.
- Hamed, K. H., & Rao, A. R. (1998). A modified Mann–Kendall trend test for autocorrelated data. J. Hydrology, 204, 182–196.
- Yue, S., & Wang, C. Y. (2004). The Mann–Kendall test modified by effective sample size to detect trend in serially correlated hydrological series. Water Resources Management, 18, 201–218.
- Yue, S., Pilon, P., Phinney, B., & Cavadias, G. (2002). The influence of autocorrelation on the ability to detect trend in hydrological series. Hydrological Processes, 16, 1807–1829.
- Hirsch, R. M., Slack, J. R., & Smith, R. A. (1982). Techniques of trend analysis for monthly water quality data. Water Resources Research, 18, 107–121.
- Hirsch, R. M., & Slack, J. R. (1984). A nonparametric trend test for seasonal data with serial dependence. Water Resources Research, 20, 727–732.
- Libiseller, C., & Grimvall, A. (2002). Performance of partial Mann–Kendall tests for trend detection in the presence of covariates. Environmetrics, 13, 71–84.
- Cox, D. R., & Stuart, A. (1955). Some quick sign tests for trend in location and dispersion. Biometrika, 42, 80–95.
From the CodeSplash method registry · ts.trend v2.1.0.