OPEN-SOURCE SCRIPT

Runs Test Z-Score

327
# Runs Test Z-Score

## What It Is

The Runs Test Z-Score is a statistical time-series indicator that applies the Wald-Wolfowitz Runs Test to directional price change sequences to measure departures from randomness.

Advantages: The Runs Test is non-parametric, simple to compute, and does not require assumptions about the distribution of returns.

Limitations: It considers only the direction of price changes, ignoring their magnitude, and may have limited power to detect more complex forms of dependence.

Runs are uninterrupted sequences of the same directional state. For example, the sequence (+, +, +, −, −, +, +) forms three runs: (+++), (--), and (++). The Runs Test compares the observed number of runs to the number expected under pure randomness to determine whether price changes exhibit persistence, anti-persistence (alternation), or random sequencing.

The indicator evaluates the **sequential randomness of price changes** to determine whether directional movements occur in a manner consistent with a random walk, or whether they exhibit persistent or alternating structural behavior.

The indicator produces a standardized Z-score:
**Negative values** indicate persistence (fewer directional state changes than expected under randomness).
**Values near zero** indicate random-like sequencing.
**Positive values** indicate anti-persistence (more directional state changes than expected under randomness).

Three independent price sequences can be analyzed:

### 1. Close-to-Close
Measures the sequential pattern of where price closed on the current bar relative to the previous bar's close. It captures the net directional outcome between consecutive intervals, incorporating all activity—including overnight or weekend gaps—while ignoring the path taken within the bar itself. This is typically the broadest, most aggregated mode.

### 2. Open-to-Close
Measures the sequential pattern of directional movement strictly *within* each bar by comparing the close to the open. Positive states indicate an upward drive during the session; negative states indicate a downward drive. This sequence reveals whether intraday or intra-bar directional drive tends to persist or alternate through time.

### 3. Midpoint Position
Measures where price closes relative to the high-low midpoint of each bar. A close above the midpoint indicates that buyers controlled the final portion of the bar's range, while a close below indicates seller control. This pattern captures whether range-control dominance tends to persist or alternate across consecutive bars, regardless of the net change between closes.

---

## What Divergence Means in Practice

Divergence is not a failure of the indicator. It is the indicator revealing something more precise than any single sequence could.

The three sequences measure distinct aspects of price behavior. When they diverge, they reveal structural differences in how directional progression, intra-bar drive, and range control are expressed through sequential price changes.

**All Three Agree:** Sequential structure is highly coherent across inter-bar direction, intra-bar drive, and range control. Price changes are expressing a consistent behavioral pattern across all three dimensions of price action.

**Close-to-Close Persists | Open-to-Close is Random:** The broader trend is being carried primarily by net bar-to-bar advances — including gap contributions — rather than persistent intra-bar directional drive.

**Open-to-Close Persists | Close-to-Close is Random:** Bars exhibit consistent internal directional drive, but that drive does not translate into sequential progress across bars. Strong movement occurs within sessions, but net inter-session direction remains inconsistent.

**Midpoint Position Diverges From Both:** Intra-bar auction control is decoupled from directional movement. Buyers or sellers may be consistently dominating the close of the bar's range even while net trend progression and intra-bar drive remain mixed or random.

**Close-to-Close & Open-to-Close Agree | Midpoint Disagrees:** Directional movement is consistent both within and between bars, but closing location within the range suggests underlying auction dynamics are less consistent with the prevailing directional movement. Trend progression and range control are actively diverging.

**Open-to-Close & Midpoint Agree | Close-to-Close Disagrees:** Intra-bar directional drive and range control are aligned, but that internal behavior fails to translate into persistent directional progression across consecutive bars.

**Close-to-Close & Midpoint Agree | Open-to-Close Disagrees:** Directional progression and range control are aligned, but movement occurring within individual bars lacks persistence. Price changes are making net progress despite inconsistent intra-bar drive.

**All Three Disagree:** Structural signals are mixed across all three dimensions, indicating low agreement regarding the prevailing sequential regime.

---

## Why It Was Built

Most technical indicators focus on trend strength, momentum, volatility, or price efficiency. Far fewer attempt to quantify the underlying sequencing structure of consecutive price changes.

Sequential price changes can produce identical net price movements while exhibiting entirely different internal structures:

**Persistent sequences** contain fewer directional state changes than expected under a random process.
**Random sequences** exhibit no detectable departure from random ordering.
**Alternating sequences** contain more directional state changes than expected under a random process.

Understanding which structural environment currently dominates provides objective, statistical context for trend-following systems, mean-reversion approaches, pattern analysis, and price structure assessment.

---

## Core Concepts

### Persistence
Persistence occurs when directional moves tend to continue. In a persistent environment, state changes occur less frequently than expected under randomness. This produces fewer overall runs and yields a negative Z-score.

### Randomness
Randomness refers to the *ordering* of directional outcomes, not the overall trend vector. Prices can trend strongly while still exhibiting random directional sequencing. Trend direction and sequential randomness are separate price properties. Price may trend upward while directional changes remain statistically random. Z-scores near zero indicate no detectable departure from random sequencing.

### Anti-Persistence
Anti-persistence occurs when directional states alternate more frequently than expected under randomness. This produces more runs than predicted by a random process and results in a positive Z-score.

### Partition Methods

The indicator offers two distinct classification models:

**Zero-Split:** Partitions observations around zero. This mode preserves directional bias and trend influence, measuring randomness while retaining directional drift. Useful when directional bias is core to the analysis.

**Median-Split:** Partitions observations around the rolling median. This removes directional imbalance from the classification process, isolating sequencing behavior from the overarching trend direction.

Comparing both modes helps distinguish persistence arising from directional drift from persistence arising from the sequencing structure itself.

---

## Z-Score Interpretation

| Zone | Z-Score | Structural Interpretation |

🟦 **Strong Persistence** | Z ≤ −1.96 | Sequential changes tend to persist (+/+ or −/−) rather than alternate.

🔵 **Mild Persistence** | −1.96 < Z ≤ −1.0 | Increasing evidence of continuations in sequential price changes.

⬜ **Random-Like** | −1.0 < Z ≤ 1.0 | No detectable sequential structure; outcomes occur with similar frequency.

🟨 **Mild Anti-Persistence** | 1.0 < Z < 1.96 | Increasing evidence of alternations (+/− or −/+) in price changes.

🟧 **Strong Anti-Persistence** | Z ≥ 1.96 | Sequential changes alternate (+/− or −/+) rather than persist.

Color Legend: Dark Blue = Strong Persistence, Light Blue = Mild Persistence, Gray = Random-Like, Light Orange = Mild Anti-Persistence, Dark Orange = Strong Anti-Persistence.

**Statistical Note:** The ±1.96 thresholds correspond to the conventional 5% two-tailed significance level. Values beyond these thresholds indicate statistically significant departures from randomness under the assumptions of the Runs Test. Intermediate zones represent varying degrees of structural evidence but should be interpreted as descriptive rather than formally significant.

---

## Empirical Validation

Validation was conducted using approximately 150,000 daily observations across 50 liquid U.S. equities, ETFs, and sector funds spanning roughly ten years of market history. Lookback periods of 20, 30, and 40 bars were evaluated. Results confirmed that runs-based measurements reliably isolate structural shifts in sequential price behavior.

The study demonstrated:
* Correct regime ordering across all 50 tested securities.
* Stable structural readings that persist beyond short-term noise.
* Consistent behavior across multiple lookback settings.
* Strong correspondence with serial dependence metrics.
*Essentially no correlation with Efficiency Ratio (Kaufman) measurements.**

This final finding strongly suggests that sequential randomness and trend efficiency measure distinct price sequence properties. Price changes can exhibit highly efficient directional travel while still displaying random sequencing, or vice versa. This makes the Runs Test Z-Score a valuable complementary tool rather than a duplicate of existing efficiency or momentum indicators.

---

## How To Use It

**Contextualizing Chart Patterns:** Continuation patterns (flags, channels) implicitly assume a persistent environment. Reversal patterns (double tops and exhaustion structures) are often associated with a breakdown in persistent directional movement, making alternating price changes more likely than continued runs in the same direction. Use the Z-score to determine if the price sequence structure statistically supports the pattern type forming on your chart. When the Runs Test indicates randomness, apparent technical patterns should be interpreted with caution, since their formation may be attributable to chance rather than persistent price behavior.

**Selecting Lookback Periods:** Shorter lookbacks increase responsiveness to structural change but are more sensitive to sampling variability. Longer lookbacks improve stability by filtering short-term noise and highlighting broader regime behavior.

**Applying Partitions:** Monitor the gap between Zero-Split and Median-Split. If Zero-Split shows strong persistence but Median-Split looks random, the non-randomness is entirely driven by directional drift (the trend), not the underlying sequencing mechanics.

**EMA Smoothing:** The optional EMA smoothing layer serves as a visual aid, improving interpretability and helping users track the indicator's underlying trend. Statistical interpretation should always remain anchored to the raw Z-score levels.

---

## Disclaimers & Limitations

This indicator is a descriptive statistical measurement tool, not a predictive trading system. The Runs Test Z-Score evaluates historical directional sequencing and does not forecast future price behavior. Persistent, random, or alternating conditions observed in the past do not guarantee the continuation of those regimes. It should be utilized as contextual analysis alongside proper risk management protocols.

免责声明

这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。