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

Chapter 17: 3 Must-Know Algorithms for Automating Chart Pattern Trading in Python


Chapter Overview — 00:00

Virtually all classical technical analysis—from classical chart patterns like Head & Shoulders and Double Tops to horizontal support and resistance levels—relies on identifying local turning points (tops and bottoms) in price series.

For a human discretionary trader, spotting a swing high or swing low on a visual chart is intuitive. For an algorithmic trading system, however, turning points must be defined mathematically and extracted programmatically without future data leakage (look-ahead bias).

This chapter examines three foundational algorithms in quantitative chart pattern automation:

  1. The Rolling Window Method (Order-based Local Extrema): A time-centric approach comparing points to fixed neighboring horizons.
  2. Directional Change (ZigZag): A price-centric approach enforcing alternating extrema via minimum retracement thresholds.
  3. Perceptually Important Points (PIP): A geometric dimension-reduction algorithm that extracts the most prominent structural points from a price slice.

Understanding the mechanics, mathematical nuances, lag characteristics, and optimal use cases of these three algorithms is prerequisite to automating complex patterns and data mining market behavior.


1. The Core Challenge of Turning Point Detection — 00:15

A multi-point chart pattern (such as a 5-point Head and Shoulders) is fundamentally a geometric arrangement of local peaks and troughs:

                  Head (Peak 2)
                       ▲
         Left Shoulder |   Right Shoulder
           (Peak 1)    |     (Peak 3)
              ▲        |        ▲
             / \       |       / \
            /   \     / \     /   \
           /     ▼   /   ▼   /     ▼
                Trough 1 Trough 2
          ───────────────────────── Neckline

Before an algorithm can check geometric ratios, neckline slopes, or breakout levels, it must first discretize continuous bar data into discrete turning points.

Crucially, no real-time algorithm can identify a local extreme at the exact moment it occurs. An extreme can only ever be confirmed in hindsight after subsequent price action proves that the point was indeed a peak or a trough. The fundamental trade-off between turning point algorithms lies in how they define the confirmation condition and how much lag they introduce.


2. Algorithm 1: Rolling Window (Local Extrema) — 00:46

Mechanics & Parameters

The rolling window method checks whether a candidate candle is the maximum or minimum value within a symmetric neighborhood of adjacent points:

Top if Pt>Pt+kandPt>Pt−k∀k∈[1,order]\text{Top if } P_t > P_{t+k} \quad \text{and} \quad P_t > P_{t-k} \quad \forall k \in [1, \text{order}] Bottom if Pt<Pt+kandPt<Pt−k∀k∈[1,order]\text{Bottom if } P_t < P_{t+k} \quad \text{and} \quad P_t < P_{t-k} \quad \forall k \in [1, \text{order}]

The single tuning parameter is order\text{order} (nn), representing the number of adjacent candles inspected on either side:

  • Order 1: Compares candle tt against t−1t-1 and t+1t+1. Identifies micro-swings and noisy fluctuations.
  • Order 2: Compares candle tt against t−2,t−1t-2, t-1 and t+1,t+2t+1, t+2.
  • Order 3+: Filters out minor noise, returning fewer, more macro turning points.
 Order 1 Window:   [ t-1 ]  <  [  t  ]  >  [ t+1 ]
 Order 2 Window:   [ t-2 , t-1 ]  <  [  t  ]  >  [ t+1 , t+2 ]

Confirmation Lag

Because the algorithm requires inspecting nn points into the future relative to candle tt, a turning point of order nn can only be confirmed after a deterministic lag of exactly nn bars:

Confirmation Index=t+order\text{Confirmation Index} = t + \text{order}

In live trading or rigorous backtesting, the signal is only actionable at bar t+ordert + \text{order}. Using point tt before bar t+nt+n introduces look-ahead bias.

Python Implementation & Scipy Comparison

In Python, this logic can be executed sequentially or via scipy.signal.argrelextrema:

import numpy as np

def find_extrema_rolling_window(prices: np.ndarray, order: int = 2):
    """
    Identifies confirmed local tops and bottoms without look-ahead bias.
    Confirmation occurs exactly 'order' bars after the extreme.
    """
    confirmed_tops = []
    confirmed_bottoms = []
    
    # Loop through historical data up to current bar minus order
    for i in range(order, len(prices) - order):
        candidate_price = prices[i]
        
        # Check if strictly higher than neighbors
        is_top = all(candidate_price > prices[i - k] and candidate_price > prices[i + k] for k in range(1, order + 1))
        # Check if strictly lower than neighbors
        is_bottom = all(candidate_price < prices[i - k] and candidate_price < prices[i + k] for k in range(1, order + 1))
        
        confirmation_idx = i + order
        if is_top:
            confirmed_tops.append((confirmation_idx, i, candidate_price))
        elif is_bottom:
            confirmed_bottoms.append((confirmation_idx, i, candidate_price))
            
    return confirmed_tops, confirmed_bottoms

[!WARNING] Look-Ahead Warning with argrelextrema scipy.signal.argrelextrema(data, np.greater, order=n) operates across the entire array at once and returns the indices of the peaks (tt). If backtesting, never enter a trade at index tt; you must offset execution to index t+nt + n.

Close vs. High/Low

While standard chartists look at candle wicks (high and low), applying rolling windows on High/Low arrays can produce contradictory results—such as identifying a local high and a local low on the exact same candle during high-volatility bars. Using closing prices (close) eliminates this ambiguity and produces cleaner structural turning points.


3. Algorithm 2: Directional Change (ZigZag) — 02:53

Mechanics & The Retracement Threshold (σ\sigma)

The Directional Change algorithm (commonly known as ZigZag) detects market turns based on price magnitude rather than fixed time windows. It enforces strict alternating tops and bottoms: a top must always follow a bottom, and a bottom must always follow a top.

The single parameter is the retracement threshold (σ\sigma), typically expressed as a percentage (e.g., 3%3\% or 0.030.03):

       Last Confirmed Bottom
               ●
                \         Pending Top (Highest High seen so far)
                 \             ▲
                  \           / \
                   \         /   \  Retracement >= σ
                    \       /     ▼
                     \     /    [ Confirmation Line: Peak * (1 - σ) ]
                      \   /     --> Top confirmed at Peak!
                       \ /      --> Next phase searches for Bottom
  1. Top Tracking Phase:
    • The algorithm tracks the highest high (Pmax⁡P_{\max}) achieved since the last confirmed bottom.
    • It maintains a confirmation line at Pmax⁡×(1−σ)P_{\max} \times (1 - \sigma).
    • If price pushes higher, Pmax⁡P_{\max} updates and the confirmation line moves up.
    • If price closes below the confirmation line, the peak at Pmax⁡P_{\max} is officially confirmed. The algorithm immediately switches to Bottom Tracking Phase.
  2. Bottom Tracking Phase:
    • Tracks the lowest low (Pmin⁡P_{\min}) since the confirmed top.
    • Confirmation line sits at Pmin⁡×(1+σ)P_{\min} \times (1 + \sigma).
    • When price closes above this threshold, the trough at Pmin⁡P_{\min} is confirmed, and the state flips back to Top Tracking.

Variable Confirmation Lag

Unlike the Rolling Window method where confirmation lag is a constant nn bars, Directional Change has dynamic, undefined lag. In an aggressive flash crash, a 3%3\% retracement might confirm in 1 bar. In a grinding, low-volatility trend, confirming a turn might take 30 bars.

Algorithmic Logic

def directional_change(close, high, low, sigma: float = 0.03):
    """
    Directional Change (ZigZag) algorithm.
    Returns alternating confirmed tops and bottoms with their confirmation bar.
    """
    up_zig = True  # State: True = looking for next Top, False = looking for next Bottom
    pending_extreme_idx = 0
    pending_extreme_price = high[0]
    
    confirmed_extremes = [] # List of tuples: (confirm_idx, extreme_idx, price, 'TOP'|'BOTTOM')
    
    for i in range(1, len(close)):
        if up_zig:
            # Updating peak
            if high[i] > pending_extreme_price:
                pending_extreme_price = high[i]
                pending_extreme_idx = i
            # Checking retracement threshold
            elif close[i] < pending_extreme_price * (1.0 - sigma):
                confirmed_extremes.append((i, pending_extreme_idx, pending_extreme_price, 'TOP'))
                up_zig = False
                pending_extreme_price = low[i]
                pending_extreme_idx = i
        else:
            # Updating trough
            if low[i] < pending_extreme_price:
                pending_extreme_price = low[i]
                pending_extreme_idx = i
            # Checking retracement threshold
            elif close[i] > pending_extreme_price * (1.0 + sigma):
                confirmed_extremes.append((i, pending_extreme_idx, pending_extreme_price, 'BOTTOM'))
                up_zig = True
                pending_extreme_price = high[i]
                pending_extreme_idx = i
                
    return confirmed_extremes

[!TIP] Volatility-Adaptive Retracements Instead of a static percentage σ\sigma, the retracement threshold can be scaled dynamically using the Average True Range (ATR): Threshold=Pextreme±(k×ATRt)\text{Threshold} = P_{\text{extreme}} \pm (k \times \text{ATR}_t) This automatically expands the required retracement during volatile regimes and compresses it during quiet consolidations.


4. Algorithm 3: Perceptually Important Points (PIP) — 05:29

Origin & Mathematical Definition

Introduced in 2001 (Chung et al., Financial time series data mining using perceptually important points), the PIP algorithm originates from computer vision and dimensionality reduction.

Given a discrete time series slice of length LL and a target number of points kk (where k≥3k \ge 3):

  1. Initialize: The first two PIPs (P1P_1 and P2P_2) are fixed as the first point and last point of the window: P1=(x0,y0),P2=(xL−1,yL−1)P_1 = (x_0, y_0), \quad P_2 = (x_{L-1}, y_{L-1})
  2. First Iteration: Draw a line connecting P1P_1 and P2P_2. Calculate the distance from every intermediate point in the slice to this line. The point with the maximum distance becomes the 3rd PIP (P3P_3).
  3. Subsequent Iterations: The selected points partition the window into segments. In each step, for each adjacent pair of already-selected points, find intermediate points' distance to their connecting segment. Select the single point with the global maximum distance across all segments as the next PIP.
  4. Termination: Repeat until exactly kk points have been extracted.
 Step 1: Connect Start (P1) and End (P2)
 P1 ●──────────────────────────────────────────────────────● P2
           \                     ▲ Max Dist
            \                   /
             \                 ● (Selected as P3)
 
 Step 2: Draw P1-P3 and P3-P2; find next furthest point (P4)
 P1 ●──────● P3────────────────────────────────────────────● P2
              \          ▲ Max Dist
               \        /
                \      ● (Selected as P4)

Distance Metrics

Three primary distance formulas can be used between a candidate point (x3,y3)(x_3, y_3) and the line connecting (x1,y1)(x_1, y_1) to (x2,y2)(x_2, y_2):

  1. Vertical Distance: dv=∣y3−yc∣=∣y3−(y1+y2−y1x2−x1(x3−x1))∣d_v = |y_3 - y_c| = \left| y_3 - \left( y_1 + \frac{y_2 - y_1}{x_2 - x_1}(x_3 - x_1) \right) \right|
  2. Euclidean Distance: Standard straight-line geometric distance.
  3. Perpendicular Distance: Orthogonal distance from (x3,y3)(x_3, y_3) to the line.

In practical financial time series, all three distance measures usually select identical or near-identical turning points. Vertical distance is computationally fastest because it avoids trigonometric or square root calculations.

def find_pips(data: np.ndarray, n_pips: int = 5):
    """
    Extracts n Perceptually Important Points from a 1D price series slice.
    Returns sorted indices of PIPs.
    """
    pips_x = [0, len(data) - 1]
    pips_y = [data[0], data[-1]]
    
    while len(pips_x) < n_pips:
        max_dist = -1.0
        best_idx = None
        
        # Check all adjacent segments formed by currently selected PIPs
        for i in range(len(pips_x) - 1):
            x1, y1 = pips_x[i], pips_y[i]
            x2, y2 = pips_x[i + 1], pips_y[i + 1]
            
            # Slope and intercept for vertical distance
            slope = (y2 - y1) / (x2 - x1)
            intercept = y1 - slope * x1
            
            for j in range(x1 + 1, x2):
                y_line = slope * j + intercept
                dist = abs(data[j] - y_line)
                
                if dist > max_dist:
                    max_dist = dist
                    best_idx = j
                    
        # Insert new PIP and keep list sorted by X coordinate
        insert_pos = np.searchsorted(pips_x, best_idx)
        pips_x.insert(insert_pos, best_idx)
        pips_y.insert(insert_pos, data[best_idx])
        
    return pips_x, pips_y

5. Comparative Evaluation & Trading Use Cases — 08:03

Each algorithm imposes a different structural lens on price action:

DimensionRolling Window (Local Extrema)Directional Change (ZigZag)Perceptually Important Points (PIP)
Primary FocusTime (Window order nn)Price (Retracement % σ\sigma)Hybrid Geometry (Shape compression)
Confirmation LagConstant (nn bars)Variable / DynamicWindow-dependent (operates on fixed slices)
Magnitude SensitivityBlind to height; small ripples qualify if Pt>Pt±kP_t > P_{t\pm k}High; rejects moves below σ\sigmaHigh; selects the most salient geometric outliers
Extrema AlternationNot guaranteed (can find consecutive highs)Strictly guaranteed (Peak ↔\leftrightarrow Trough)Ordered by time, but shape depends on kk
Scoring InputContinuous streamContinuous streamSegmented slice / rolling window buffer
       TIME FOCUS (Rolling Window)            PRICE FOCUS (Directional Change)
          order = 2                                  sigma = 3%
            Peak                                        Peak
             ▲                                           ▲
            / \                                         / \
           /   \                                       /   \
          /     \                                     /     \
    ●────●       ●────●                         ●────●       ●────●
    Ignored if nearby points are equal          Requires >= 3% drop to confirm

Optimal Use Cases in Algorithmic Trading

  1. Horizontal Support & Resistance Levels:
    • Best choice: Directional Change. Because support and resistance represent significant price rejection levels, filtering by percentage move (σ\sigma) isolates genuine institutional liquidity pools rather than intraday micro-swings.
  2. Fixed-Wave Chart Pattern Recognition (Head & Shoulders, Double Tops):
    • Rolling Window or Directional Change. A Head and Shoulders requires alternating highs and lows with distinct structural spacing. Rolling windows with order 3–5 or ZigZag with a 2–3% threshold cleanly extract the 5 critical anchors.
  3. Data Mining Novel Patterns & Template Matching:
    • Best choice: Perceptually Important Points (PIP). By fixing kk (e.g., k=5k=5 or k=7k=7) on a sliding window of historical bars, PIP compresses varying-length candles into standardized coordinate vectors (x1,y1),…,(xk,yk)(x_1, y_1), \dots, (x_k, y_k). These vectors can be fed into Euclidean distance clustering, Dynamic Time Warping (DTW), or machine learning classifiers to discover novel, recurring price patterns across decades of market history.

Key Takeaways

  1. No Free Lunch with Real-Time Extrema: Real-time turning point identification always entails latency. Choose Rolling Windows when you need predictable, constant lag (nn bars); choose Directional Change when you need price-significant turns regardless of time taken.
  2. Use Closing Prices for Clean Discretization: Candle wicks introduce contradictory dual-extrema on single high-volatility bars. Close-to-close calculations provide robust geometric anchors.
  3. PIP is the Bridge to Machine Learning: PIP transforms noisy, variable-length price series into uniform, low-dimensional coordinate spaces ideal for automated clustering and pattern data mining.

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ả.