Xem Tiếng Việt
Chương 13Original (EN)

Chapter 13: Ordinal Patterns and Permutation Entropy


Chapter Overview — 00:00

Financial price series are notorious for non-stationarity, heavy tails, and dynamic regime changes. Traditional statistical and technical indicators rely heavily on absolute metric magnitudes (e.g., moving average differences, standard deviations, or candle heights), making them sensitive to volatility shocks and scaling distortions.

Ordinal patterns provide a powerful non-parametric alternative: instead of analyzing raw price values, they encode the relative ranking and ordering of consecutive data points. When combined with information theory, ordinal patterns allow us to compute Permutation Entropy—an indicator of structural market complexity and regime stability.

In this chapter, you will learn:

  1. The Combinatorics of Ordinal Patterns: How subsequences are mapped into discrete permutations based on the embedding dimension DD.
  2. Generalized Pattern Mapping Algorithm: An algorithmic formulation to convert consecutive price sequences into unique integer indices without combinatorial explosion.
  3. Practical Trading Applications Beyond Price Bars: Mapping moving average alignments and swing high/low market structures.
  4. Formulation of Permutation Entropy: Calculating Shannon entropy across ordinal pattern distributions to quantify market chaos versus trending order.
  5. Empirical Strategy Integration: Using Permutation Entropy as a regime filter on Bitcoin hourly data for mean-reversion and trend systems.

1. What Are Ordinal Patterns? — 00:45

1.1 Embedding Dimension and Factorial Scaling

Given a continuous time series {xt}\{x_t\}, we extract subsequences of length DD, known as the embedding dimension. An ordinal pattern represents the unique permutation of ranks of the values within that subsequence.

The total number of possible ordinal patterns for an embedding dimension DD equals the factorial of DD:

Npatterns=D!N_{\text{patterns}} = D!

Embedding Dimension (DD)Number of Possible Patterns (D!D!)Practical Feasibility in Algorithmic Trading
D=2D = 22!=22! = 2Binary up/down step; too simple to capture multi-bar shape.
D=3D = 33!=63! = 6Excellent for high-frequency or small sample windows.
D=4D = 44!=244! = 24Standard sweet spot for hourly and daily financial data.
D=5D = 55!=1205! = 120Requires vast data lookback to avoid sample sparsity.
Examples of D=3 Ordinal Patterns:
 Pattern 0 (0,1,2):   ▲          Pattern 1 (0,2,1):     ▲
                     /                                 / \
                    /                                 /   ▼
                   /                                 /
                  /                                 /

 Pattern 5 (2,1,0): \            Pattern 4 (2,0,1): \     ▲
                     \                               \   /
                      \                               \_/
                       ▼

Because factorial growth is explosive (6!=7206! = 720, 7!=50407! = 5040), financial trading applications typically restrict DD to 33 or 44 to ensure statistical reliability within realistic lookback windows.

1.2 Handling Identical Consecutive Values

In continuous bar prices, identical consecutive closes (xt=xt−1x_t = x_{t-1}) occur rarely. In the algorithm, a simple greater-than-or-equal (≥\ge) comparison assigns a deterministic tie-breaker without requiring dedicated equality patterns that would dramatically inflate model complexity.


2. Algorithmic Classification of Ordinal Patterns — 02:18

2.1 The Mathematical Ranking Engine

Classifying an arbitrary sequence into a permutation index from 00 to D!−1D!-1 is achieved through an efficient combinatorial mapping. Each element is compared against its preceding elements, weighted by dimensional factorials (Lehmer code / inversion vector).

import numpy as np

def calculate_ordinal_patterns(data: np.ndarray, d: int = 4) -> np.ndarray:
    """
    Maps each subsequence of length d to an ordinal pattern symbol in [0, d! - 1].
    
    :param data: 1D array of numerical prices (e.g. closing prices)
    :param d: Embedding dimension (default 4)
    :return: 1D array of ordinal pattern symbols
    """
    n = len(data)
    total_patterns = np.math.factorial(d)
    d1 = d - 1
    
    # Precompute multipliers for inversion counting
    multipliers = [np.math.factorial(d - 1 - i) for i in range(d1)]
    
    pattern_ordinals = np.full(n, np.nan)
    
    for i in range(d1, n):
        window = data[i - d1 : i + 1]
        ordinal_val = 0
        
        # Count preceding smaller elements and apply factorial weights
        for j in range(d1):
            count = 0
            for k in range(j + 1, d):
                if window[j] >= window[k]:
                    count += 1
            ordinal_val += count * multipliers[j]
            
        pattern_ordinals[i] = ordinal_val
        
    return pattern_ordinals

2.2 Empirical Pattern Distribution in Price Data

If price movements were pure Gaussian random walks, every one of the 24 ordinal patterns (D=4D=4) would occur with roughly equal probability (≈4.17%\approx 4.17\%).

However, empirical backtests on financial assets reveal severe statistical bias:

  • Persistent Trend Patterns: Monotonically increasing (x0<x1<x2<x3x_0 < x_1 < x_2 < x_3) and monotonically decreasing (x0>x1>x2>x3x_0 > x_1 > x_2 > x_3) sequences appear significantly more frequently than alternating zig-zag patterns.
  • Microstructure Reversions: Alternating chop patterns cluster heavily during low-volatility Asian sessions or consolidation regimes.

3. Alternative Trading Applications of Ordinal Mapping — 03:36

Ordinal mapping is a versatile mathematical framework that extends well beyond raw close prices:

3.1 Moving Average Structural Alignment

Instead of tracking raw crossover events between multiple moving averages, an ordinal pattern can represent their global topological order:

  • Consider 3 moving averages: MA(10), MA(20), MA(30).
  • Dimension D=3  ⟹  6D = 3 \implies 6 possible arrangements.
  • Pattern [0,1,2][0, 1, 2] corresponds to a perfect bullish stack (MA10>MA20>MA30\text{MA}_{10} > \text{MA}_{20} > \text{MA}_{30}).
  • Pattern [2,1,0][2, 1, 0] corresponds to a perfect bearish stack (MA10<MA20<MA30\text{MA}_{10} < \text{MA}_{20} < \text{MA}_{30}).
  • Intermediate patterns quantify transitions, providing early warning of trend unraveling before lagging crossovers occur.

3.2 Market Structure & Swing Extrema

By first identifying local swing peaks and troughs, the resulting sequence of alternating extrema can be mapped into ordinal patterns:

  • Quantifies complex formations like Higher Highs / Higher Lows (HH/HL), Lower Highs / Lower Lows (LH/LL), or expansive broadening wedges.

4. Permutation Entropy: Measuring Time Series Complexity — 04:08

4.1 Theoretical Formulation (Bandt & Pompe)

First introduced by Christoph Bandt and Bernd Pompe (2002), Permutation Entropy (PE) measures the disorder and information content of a dynamic system based purely on the probability distribution of its ordinal patterns.

  1. In a rolling lookback window of length WW, count the frequency cic_i of each ordinal pattern i∈[0,D!−1]i \in [0, D!-1].
  2. Calculate the empirical probability:

pi=ciWp_i = \frac{c_i}{W}

  1. Compute the Shannon Entropy of the distribution:

H(D)=−∑i=1D!piln⁡(pi)(with 0ln⁡0≡0)H(D) = -\sum_{i=1}^{D!} p_i \ln(p_i) \quad (\text{with } 0 \ln 0 \equiv 0)

  1. Normalize H(D)H(D) by the maximum theoretical entropy ln⁡(D!)\ln(D!) to constrain the index to [0,1][0, 1]:

PE=H(D)ln⁡(D!)PE = \frac{H(D)}{\ln(D!)}

Permutation Entropy Scale:
  0.0 ────────────────────────────────────────── 1.0
  Deterministic / Ordered                      Uniformly Random / Chaotic
  (Dominated by single pattern streak)          (All D! patterns appear equally)

4.2 Lookback Window Scaling Rule

To ensure valid probability estimation, the lookback window WW must be a multiple MM of D!D!:

W=M×D!W = M \times D!

For example:

  • For D=4D=4 (2424 patterns) with multiplier M=7  ⟹  W=168M=7 \implies W = 168 candles (exactly 1 week on hourly data).
  • For D=3D=3 (66 patterns) with multiplier M=28  ⟹  W=168M=28 \implies W = 168 candles.
import numpy as np
import pandas as pd

def rolling_permutation_entropy(
    data: np.ndarray, 
    d: int = 3, 
    multiplier: int = 28
) -> np.ndarray:
    """
    Computes rolling normalized Permutation Entropy.
    """
    total_patterns = np.math.factorial(d)
    lookback = multiplier * total_patterns
    patterns = calculate_ordinal_patterns(data, d)
    
    pe_out = np.full(len(data), np.nan)
    max_entropy = np.log(total_patterns)
    
    for i in range(lookback, len(data)):
        window = patterns[i - lookback + 1 : i + 1]
        
        # Calculate pattern probabilities
        counts = pd.Series(window).value_counts()
        probs = (counts / lookback).to_numpy()
        
        # Shannon Entropy
        entropy = -np.sum(probs * np.log(probs))
        pe_out[i] = entropy / max_entropy
        
    return pe_out

5. Trading Integration & Regime Filtering — 06:29

5.1 Price Evolution and Entropy Dynamics

Tested on 1-hour Bitcoin data (D=3,W=168D=3, W=168 hours):

  • During Sustained Trends: Permutation entropy drops substantially. Monotonic ordinal patterns dominate the lookback window, driving the probability distribution away from uniformity.
  • During Range-Bound Consolidation: Permutation entropy rises toward 1.01.0. Prices oscillate randomly, generating an even dispersion of all permutation states.

5.2 Application as a Strategy Filter

Because the relationship between permutation entropy and forward returns is non-linear, it should not be traded as a standalone directional signal. Instead, its primary value is as a conditioning regime filter:

  • Mean Reversion Systems: Frequently exhibit superior risk-adjusted returns when filtered for low entropy regimes, where order flow structures are stable and predictable rather than chaotic.
  • Trend Following Systems: Can use entropy drops as a confirmation that price action has transitioned from noise into a structured directional phase.

5.3 Extension to Volume Entropy

The permutation entropy formulation is agnostic to the input series. Computing PE on trading volume reveals periods of uniform volume dispersion versus burst-dominated regimes. While volume entropy is less universally established than price entropy, it serves as an intriguing input for volume-profile and liquidity-seeking models.


6. Key Takeaways & Practical Rules — 07:49

  1. Scale Invariance: Ordinal patterns are completely invariant to monotonic transformations and scaling changes (e.g., whether Bitcoin is trading at \1,000oror$60,000$), making them exceptionally robust across long historical datasets.
  2. Dimension Selection: Keep embedding dimensions modest (D=3D=3 or D=4D=4). Higher dimensions require exponential data volume to populate probability bins, resulting in noisy, sparse estimators.
  3. Non-Linear Edge: Treat Permutation Entropy as a macro complexity gauge to modulate strategy risk: throttle capital or avoid mean reversion during peak entropy (maximum noise), and deploy capital when market dynamics organize into lower-entropy regimes.

Nguồn duy nhất: Kênh YouTube chính thức của neurotrader. Nội dung được hệ thống hóa phục vụ học tập & tra cứu — bấm các mốc thời gian trong bài để xem trực tiếp video gốc của tác giả.