Chapter 17: 3 Must-Know Algorithms for Automating Chart Pattern Trading in Python
- Source: 3 Must-Know Algorithms for Automating Chart Pattern Trading in Python
- Channel: NeuroTrader
- Duration: 9:28
- Language: English
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:
- The Rolling Window Method (Order-based Local Extrema): A time-centric approach comparing points to fixed neighboring horizons.
- Directional Change (ZigZag): A price-centric approach enforcing alternating extrema via minimum retracement thresholds.
- 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:
The single tuning parameter is (), representing the number of adjacent candles inspected on either side:
- Order 1: Compares candle against and . Identifies micro-swings and noisy fluctuations.
- Order 2: Compares candle against and .
- 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 points into the future relative to candle , a turning point of order can only be confirmed after a deterministic lag of exactly bars:
In live trading or rigorous backtesting, the signal is only actionable at bar . Using point before bar 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
argrelextremascipy.signal.argrelextrema(data, np.greater, order=n)operates across the entire array at once and returns the indices of the peaks (). If backtesting, never enter a trade at index ; you must offset execution to index .
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 ()
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 (), typically expressed as a percentage (e.g., or ):
Last Confirmed Bottom
●
\ Pending Top (Highest High seen so far)
\ ▲
\ / \
\ / \ Retracement >= σ
\ / ▼
\ / [ Confirmation Line: Peak * (1 - σ) ]
\ / --> Top confirmed at Peak!
\ / --> Next phase searches for Bottom
- Top Tracking Phase:
- The algorithm tracks the highest high () achieved since the last confirmed bottom.
- It maintains a confirmation line at .
- If price pushes higher, updates and the confirmation line moves up.
- If price closes below the confirmation line, the peak at is officially confirmed. The algorithm immediately switches to Bottom Tracking Phase.
- Bottom Tracking Phase:
- Tracks the lowest low () since the confirmed top.
- Confirmation line sits at .
- When price closes above this threshold, the trough at is confirmed, and the state flips back to Top Tracking.
Variable Confirmation Lag
Unlike the Rolling Window method where confirmation lag is a constant bars, Directional Change has dynamic, undefined lag. In an aggressive flash crash, a 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 , the retracement threshold can be scaled dynamically using the Average True Range (ATR): 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 and a target number of points (where ):
- Initialize: The first two PIPs ( and ) are fixed as the first point and last point of the window:
- First Iteration: Draw a line connecting and . Calculate the distance from every intermediate point in the slice to this line. The point with the maximum distance becomes the 3rd PIP ().
- 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.
- Termination: Repeat until exactly 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 and the line connecting to :
- Vertical Distance:
- Euclidean Distance: Standard straight-line geometric distance.
- Perpendicular Distance: Orthogonal distance from 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:
| Dimension | Rolling Window (Local Extrema) | Directional Change (ZigZag) | Perceptually Important Points (PIP) |
|---|---|---|---|
| Primary Focus | Time (Window order ) | Price (Retracement % ) | Hybrid Geometry (Shape compression) |
| Confirmation Lag | Constant ( bars) | Variable / Dynamic | Window-dependent (operates on fixed slices) |
| Magnitude Sensitivity | Blind to height; small ripples qualify if | High; rejects moves below | High; selects the most salient geometric outliers |
| Extrema Alternation | Not guaranteed (can find consecutive highs) | Strictly guaranteed (Peak Trough) | Ordered by time, but shape depends on |
| Scoring Input | Continuous stream | Continuous stream | Segmented 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
- Horizontal Support & Resistance Levels:
- Best choice: Directional Change. Because support and resistance represent significant price rejection levels, filtering by percentage move () isolates genuine institutional liquidity pools rather than intraday micro-swings.
- 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.
- Data Mining Novel Patterns & Template Matching:
- Best choice: Perceptually Important Points (PIP). By fixing (e.g., or ) on a sliding window of historical bars, PIP compresses varying-length candles into standardized coordinate vectors . 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
- No Free Lunch with Real-Time Extrema: Real-time turning point identification always entails latency. Choose Rolling Windows when you need predictable, constant lag ( bars); choose Directional Change when you need price-significant turns regardless of time taken.
- 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.
- 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.