Skip to content

DPredict · Guide test 229

Cox–Stuart trend test

Tests trend using signs of differences between early and late observations.

Runs in CodeSplashPython (calls R) example not runR example not run 3 corrections in edition 2

Do it in CodeSplash

In the app, set it up in Analyze with this method:

In Monotonic trend tests (Mann–Kendall family), choose Compare = First and second halves or choose Exact binomial p on or choose Test = Cox–Stuart sign test.

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Cox–Stuart trend test

40
0.040
0.00

Each error carries φ × the previous one; 1 is a random walk.

0.0
0.050

Alternative

Your data

Simulated with a known ρ

If H₀ were true

increases = 10
  1. The reference: how increases varies across samples when H₀ is true.
  2. Your statistic, from the data above.
  3. The p-value: the total probability of outcomes no more likely than yours (p = 1.000).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

S=#{yi+c>yi},c=⌈n/2⌉,S∼Binomial(m,12)S = \#\{y_{i+c}>y_i\},\quad c = \lceil n/2\rceil,\quad S\sim\mathrm{Binomial}\left(m,\tfrac12\right)

With your numbers

S=10S = 10
cc
offset pairing each value with one half a series later
mm
number of non-tied pairs

The verdict

increases = 10 of 20, p = 1.000

p > α = .050: compatible with H₀

A sign test on paired halves: very simple, very robust, low powered.

Statistic
10.000
p-value
1.0000
Cox–Stuart trend test on 40 (x, y) pairs: increases = 10 of 20, p = 1.000. The p-value is above α = .050, so the data are compatible with H0.

Cox–Stuart trend test on 40 (x, y) pairs: increases = 10 of 20, p = 1.000. The p-value is above α = .050, so the data are compatible with H₀.

Question and hypotheses

H0: no systematic increase or decrease between early and late observations.

Assumptions

Independent comparable observations for the standard sign test; deterministic pairing of early and late halves.

Formula

Di=xi+⌈n/2⌉−xiB=∑iI(Di>0)\begin{gathered}D_i=x_{i+\lceil n/2\rceil}-x_i\\[5pt] B=\sum_iI(D_i>0)\end{gathered}

Parameters and notation

Pair first and last halves; omit the middle observation if n is odd. Remove zero differences under the conventional conditional sign version.

Structure of the method

Pair corresponding observations from the first and last halves, omit a middle observation when required, discard zero paired differences under the stated convention, and count positive versus negative differences. Conditional on the number of informative pairs, the standard null reduces to a binomial sign test.

Estimated and nuisance parameters

The procedure estimates no mean, variance, or slope parameter. Observed quantities are the number of nonzero paired differences and the positive-sign count. Report discarded ties and an effect summary such as the proportion of positive differences; this is not a direct numerical estimate of trend per unit time.

Settings and design choices

Prespecify chronological half-pairing, odd-length handling, one/two-sided alternative, and exact binomial calibration. Pairing is part of the variant definition; first/last thirds, offset searches, or different endpoints change it. The replacement code conditions on nonzero differences and reports informative-pair count; a high tie fraction reduces effective information.

Fitting and adaptation

There are no weights to fine-tune. Recreate the chosen half-pairing when the observation window changes, recognizing that a changed window may alter the question. The former trend::cs.test example used first/last thirds and a normal approximation; it has been replaced with the displayed exact half-pair variant. Serial dependence still requires a justified alternative.

Sensitivity and robustness

Assess ties, seasonal pairing artifacts, uneven observation spacing, dependence, and sensitivity to broad shifts versus gradual trend. The method deliberately loses magnitude information and may have low power. A large step between halves can produce significance without demonstrating a persistent smooth monotonic trajectory.

How to use and calibrate

Test B against Binomial(n*,1/2) with the selected direction.

Example application

Test a broad increasing/decreasing pattern in a short series.

Interpretation and pitfalls

Watch out

Discarding magnitudes loses power; serial dependence invalidates the simple binomial model.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.
  • Rewritten in the review: Python code, R code, interpretation and pitfalls.
  • Python codesearch.r-project.org

    Replace the R launcher for a different first/last-thirds approximation with the exact first/last-halves binomial variant displayed in the entry. New Python code executed and checked; this is newly modified code.

    Corrected Python code
    import numpy as np
    from scipy.stats import binomtest
    
    def cox_stuart_half(x):
        x = np.asarray(x, dtype=float)
        if x.ndim != 1 or len(x) < 2 or not np.isfinite(x).all():
            raise ValueError("Use at least two finite, time-ordered observations.")
        m = len(x) // 2
        differences = x[-m:] - x[:m]  # omit the middle value for odd n
        nonzero = differences[differences != 0]
        if len(nonzero) == 0:
            return {"positive": 0, "informative_pairs": 0, "p_value": None}
        positive = int(np.sum(nonzero > 0))
        result = binomtest(positive, n=len(nonzero), p=0.5, alternative="two-sided")
        return {"positive": positive, "informative_pairs": len(nonzero), "p_value": result.pvalue}
    
    rng = np.random.default_rng(2026)
    x = np.arange(1, 61)*0.02 + rng.normal(size=60)
    print(cox_stuart_half(x))
    # This exact half-pair variant matches the entry's displayed definition.
    # It is not trend::cs.test's first/last-third approximation.
    
  • R codesearch.r-project.org

    Match the displayed half-pair definition, omit an odd middle value, and condition on nonzero pairs. This replacement R code was reviewed but not executed because Rscript is unavailable; do not inherit the baseline execution label.

    Corrected R code
    cox_stuart_half <- function(x) {
        stopifnot(is.numeric(x), length(x)>=2L, all(is.finite(x)))
        n <- length(x); m <- n %/% 2L
        differences <- x[(n-m+1L):n] - x[seq_len(m)]
        nonzero <- differences[differences != 0]
        if (length(nonzero)==0L) {
            return(list(positive=0L, informative_pairs=0L, p_value=NA_real_))
        }
        positive <- sum(nonzero>0)
        result <- binom.test(positive, length(nonzero), p=0.5, alternative="two.sided")
        list(positive=positive, informative_pairs=length(nonzero), p_value=result$p.value)
    }
    set.seed(2026)
    x <- seq_len(60)*0.02+rnorm(60)
    print(cox_stuart_half(x))
    # Exact half-pair variant; not trend::cs.test's first/last-third approximation.
    
  • Interpretation and pitfallssearch.r-project.org

    Distinguish documented Cox–Stuart variants and avoid the baseline mismatch/tie issue.

    Corrected text

    Discarding magnitudes loses power; serial dependence invalidates the simple binomial model. The examples implement the first/last-halves exact conditional sign variant described here. trend::cs.test is a different first/last-thirds normal-approximation variant, and its manual warns about many ties; do not substitute it and claim the same computation. With no nonzero differences, the examples report an undefined p value rather than evidence from informative pairs.

Python and R

Keep observations in temporal order. Serial correlation and seasonality can invalidate the default independent-error calibration; do not treat the selected change point as known in advance.

Python · invokes R

Not run — Python launcher syntax checked; R backend runtime not verified · needs Python standard library + Rscript; R packages: trend

# Python launcher for the complete R implementation below.
# Requires Rscript on PATH and the listed R packages.
import shutil
import subprocess
rscript = shutil.which("Rscript")
if rscript is None:
    raise RuntimeError("Install R and make Rscript available on PATH.")
r_code = r"""
set.seed(2026)
x<-seq_len(60)*.02+rnorm(60)
print(trend::cs.test(x))
"""
# No shell interpolation. A failed R execution raises an error in Python.
result = subprocess.run([rscript, "--vanilla", "-"], input=r_code,
                        text=True, capture_output=True)
print(result.stdout)
if result.stderr:
    print(result.stderr)
result.check_returncode()
R

Not run — Syntax checked; runtime not verified in the final environment · needs trend

set.seed(2026)
x<-seq_len(60)*.02+rnorm(60)
print(trend::cs.test(x))

Sources

Reference's record:
Edition 2 review: Python: executed · R: not executed (Rscript unavailable). Python: Ran in the reference's review, on this exact code. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 229, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT229.