Chapter 10: Harmonic Pattern Recognition with Python
- Source: Harmonic Pattern Recognition With Python
- Channel: NeuroTrader
- Duration: 23:58
- Language: English
Chapter Overview — 00:00
Harmonic pattern trading is widely practiced in discretionary retail circles, where five-point price formations () are identified using strict Fibonacci retracement and projection ratios (e.g., , , , ). However, the retail literature often surrounds these ratios with mystical or pseudo-scientific claims regarding "sacred geometry."
This chapter strips away the mysticism and subjects harmonic patterns to rigorous algorithmic recognition and empirical backtesting on Bitcoin:
- The Golden Ratio Hypothesis: Testing whether price swing retracements cluster around Fibonacci levels using Kernel Density Estimation (KDE).
- Deterministic Segmentation: Employing the Directional Change (zigzag) algorithm across multiple scale parameters ().
- The 7 Canonical XABCD Geometries: Algorithmic definitions for the Gartley, Bat, Butterfly, Crab, Deep Crab, Cypher, and Shark patterns.
- Causal Pattern Detection Without Look-Ahead Bias: Formalizing the transition from confirmed swing to floating candidate .
- Logarithmic Ratio Error Metrics: Constructing distance functions for point ratios and bounded intervals.
- Multi-Scale Ensemble Strategy: Combining pattern signals across multiple scales into a continuous position-sizing engine .
- The Error Tolerance Paradox: Demonstrating why loose tolerances outperform tight Fibonacci adherence, exposing the limits of sacred numerology while confirming the value of data-mined swing ratios.
1. Deconstructing the Golden Ratio in Financial Markets — 00:16
1.1 Mathematical Properties of the Fibonacci Sequence
The Fibonacci sequence is defined recurrence-wise as with seeds . The ratio of successive numbers converges asymptotically to the Golden Ratio:
The reciprocal is:
In trading lore, retracements of and extensions of are purported to dictate natural turning points. Before writing pattern matchers, we must test whether financial price swings genuinely exhibit excess statistical density at these specific values.
2. Segmenting Price via Directional Change — 01:18
2.1 The Directional Change (Zigzag) Algorithm
To compute retracement ratios between successive market movements, price must be segmented into alternating local extrema (peaks and troughs). Fixed time-based bars cannot do this without distortion. Instead, we use the Directional Change algorithm:
- A new peak or trough is confirmed only after price retraces by at least a fixed threshold percentage from its running extreme.
- : Captures high-frequency micro-swings.
- or : Filters noise, isolating structural macro-swings.
Price
▲ Peak (Extreme Top)
│ /\
│ / \
│ / \ Retrace >= σ
│ Retrace >= σ / \ (Confirmation Point)
│ (Confirmation) / v
│ ^ /
│ \ /
│ \ /
│ \ /
│ \/ Trough (Extreme Bottom)
└────────────────────────────────────────► Time
2.2 Segment Heights and Retracement Ratios — 03:42
Let extreme prices be . The vertical segment height of the -th price leg is:
The retracement ratio comparing the current segment to the preceding segment is:
Because ratios are strictly positive and multiplicative, we transform them into log-space:
A histogram of reveals a bimodal distribution: financial price swings tend to be either distinctly larger or distinctly smaller than the preceding swing; they are rarely of equal length ().
3. Empirical Test: Does the Golden Ratio Naturally Emerge? — 04:43
To evaluate whether retracement ratios cluster at and , we fit a Kernel Density Estimation (KDE) using SciPy's gaussian_kde on hourly Bitcoin data across varying thresholds:
import numpy as np
import pandas as pd
from scipy.stats import gaussian_kde
import matplotlib.pyplot as plt
def analyze_retracement_density(extremes_df: pd.DataFrame, sigma: float):
# 1. Compute segment heights
seg_height = (extremes_df['ext_p'] - extremes_df['ext_p'].shift(1)).abs()
# 2. Retracement ratio
ratio = seg_height / seg_height.shift(1)
log_ratio = np.log(ratio.dropna())
# 3. Fit KDE with small bandwidth to isolate narrow peaks
kde = gaussian_kde(log_ratio, bw_method=0.10)
# Evaluate across a dense evaluation grid
eval_points = np.linspace(log_ratio.min(), log_ratio.max(), 1000)
density = kde(eval_points)
# Convert evaluation points back to normal ratio scale
x_ratios = np.exp(eval_points)
return x_ratios, density
3.1 Findings Across Multi-Scale Thresholds — 05:47
- : A mild, negligible local bump around .
- : No distinct clustering at either or .
- : A notable, sharp spike occurs near the extension level.
- : A weak peak appears at , but remains statistically insignificant.
3.2 Interpretation
While there is mild empirical evidence for clustering at the extension during specific macro-scales (), the retracement fails to stand out.
Rather than indicating cosmic harmony, this localized spike is most plausibly explained by a self-fulfilling behavioral prophecy: thousands of technical traders and systematic algorithms anchor take-profit and reversal limit orders at standard Fibonacci extension levels, creating measurable structural market reactions.
4. The Anatomy of XABCD Harmonic Patterns — 06:52
Harmonic patterns consist of five geometric pivot points () connected by four consecutive price legs:
Bullish Gartley Structure:
X
/ \ C
/ \ / \
/ \ / \
/ \ / \
/ \ / \
/ \ / \
/ B \
/ v
A D (Entry Zone)
Each pattern mandates specific relationships across four key ratios:
- : Retracement of leg by leg .
- : Retracement of leg by leg .
- : Retracement or extension of leg by leg .
- : Overall retracement of the net move from to by point .
4.1 Canonical Ratios for 7 Major Harmonic Patterns — 07:08
| Pattern | Ratio | Range | Range | Ratio |
|---|---|---|---|---|
| Gartley | ||||
| Bat | ||||
| Butterfly | ||||
| Crab | ||||
| Deep Crab | ||||
| Cypher | ||||
| Shark | Ignored () |
Note: Bearish variations share identical numerical ratios but are inverted vertically.
5. Causal Pattern Recognition Without Look-Ahead Bias — 08:42
A major flaw in backtesting chart patterns is querying points before they have physically occurred in live trading. To remain strictly causal:
- Confirming Point : We must wait for the Directional Change algorithm to confirm the extreme top or bottom that forms point (requiring a retrace).
- Updating Floating Point — 09:44:
- For a Bullish Pattern: Once (a confirmed top) is established, each new bar's lowest low is evaluated as a potential candidate for point .
- For a Bearish Pattern: Once (a confirmed bottom) is established, each new bar's highest high is evaluated as potential point .
- Execution at Candle Close — 10:15: As soon as candidate point aligns with all pattern ratios within tolerance , a trade is entered immediately at that candle's close.
- Deterministic Exit Rule: The trade is held until the Directional Change algorithm confirms the subsequent swing extreme (the next bottom for longs, or next top for shorts). This ensures non-overlapping trade state transitions.
Timeline of Causal Execution:
Bar t0: Swing X confirmed
Bar t1: Swing A confirmed
Bar t2: Swing B confirmed
Bar t3: Price pulls back by >= σ ──► Peak C is now officially CONFIRMED
Bar t4: Bar low tested as D ──► Ratios fail tolerance
Bar t5: New lower low tested as D ──► Ratios MATCH Bullish Gartley!
► Enter Long at Close of Bar t5
...
Bar tN: Price rallies and retraces >= σ ──► Next Trough CONFIRMED
► Exit Long at Close of Bar tN
6. Python Pattern Recognition Engine — 10:45
6.1 Data Structures & Logarithmic Distance Metric
Because pattern targets can be single floats, bounded intervals , or unconstrained (), we define a dedicated data structure and error metric:
from dataclasses import dataclass
from typing import Optional, Union, List, Tuple
import numpy as np
@dataclass
class XABCDPattern:
name: str
xa_ab: Optional[Union[float, Tuple[float, float]]]
ab_bc: Optional[Union[float, Tuple[float, float]]]
bc_cd: Optional[Union[float, Tuple[float, float]]]
xa_ad: Optional[Union[float, Tuple[float, float]]]
def get_ratio_error(actual_ratio: float, ideal: Optional[Union[float, Tuple[float, float]]]) -> float:
"""
Computes logarithmic distance between observed ratio and ideal pattern specification.
"""
if ideal is None:
return 0.0
log_actual = np.log(actual_ratio)
# Case 1: Ideal ratio is an acceptable bounded interval [lower, upper]
if isinstance(ideal, (list, tuple)):
log_lower = np.log(ideal[0])
log_upper = np.log(ideal[1])
if log_lower <= log_actual <= log_upper:
return 0.0
elif log_actual < log_lower:
# Penalize deviation outside the already-lenient bounds by factor of 2.0
return 2.0 * (log_lower - log_actual)
else:
return 2.0 * (log_actual - log_upper)
# Case 2: Ideal ratio is a single fixed point
log_ideal = np.log(ideal)
return abs(log_actual - log_ideal)
6.2 Pattern Matching & Multi-Ratio Evaluation — 15:14
The error of a candidate pattern is the unweighted sum of errors across all four ratios:
If the candidate's total error is below the defined tolerance threshold (), and constitutes the best fit among all seven patterns, the pattern is registered for trade entry.
7. Backtest Results & Multi-Scale Signal Ensembling — 17:46
7.1 Single Parameter Baseline ()
On hourly Bitcoin data, the combined harmonic strategy generated positive returns in 2022, but historical performance remained generally weak and volatile.
7.2 Individual Pattern Performance Comparison — 18:48
Evaluating each pattern independently across multiple values of :
- The Shark Pattern: The only pattern that maintained a Profit Factor across every single tested value.
- The Crab Pattern: Showed occasional explosive profit factor spikes, but sample frequency was exceedingly rare (high variance, small sample size).
- Gartley, Bat, Butterfly, Cypher: Showed mixed, fragile results—profitable at certain scales, unprofitable at others.
7.3 Multi-Scale Ensembling (Eliminating Single-Scale Luck) — 19:50
Selecting a single "optimal" introduces severe curve-fitting. Instead, we ensemble the signals across an array of distinct scale thresholds ():
Scale σ = 1.0% Signal: [ +1 ] [ +1 ] [ 0 ] [ -1 ]
Scale σ = 2.0% Signal: [ 0 ] [ +1 ] [ +1 ] [ -1 ]
Scale σ = 3.0% Signal: [ 0 ] [ 0 ] [ +1 ] [ -1 ]
───────────────────────────────────────────────────
Averaged Position: +0.33 +0.67 +0.67 -1.00
(Continuous position size bounded between -1.0 and +1.0)
This multi-scale ensemble turns binary trades into a dynamic position-sizing model:
- When multiple scales align (e.g., both a 1% micro-Gartley and a 3% macro-Shark trigger simultaneously), allocation expands to or .
- Isolated, single-scale signals execute at fractional risk (e.g., or ).
On Bitcoin, this multi-scale baseline with produced a modest Profit Factor of .
8. The Error Tolerance Paradox & Final Verdict — 21:07
With the multi-scale ensemble holding constant across all scales, only one free hyperparameter remains: the error threshold .
8.1 The Hypothesis vs. Empirical Reality — 21:53
- The Classical Hypothesis: If Fibonacci ratios represent true underlying market harmonics, then enforcing tighter error tolerances () should isolate higher-quality reversals and increase the strategy's Profit Factor.
- The Empirical Finding: The exact opposite occurs.
- Tight error tolerances () performed the worst.
- As error tolerance was relaxed (), the Profit Factor steadily increased!
Profit Factor
▲
1.15 │ ╭── Peak Performance at ε = 0.50
1.10 │ ╭────╯
1.05 │ ╭─────╯
1.00 │───────────────────────┼────────────────────────── Baseline (PF = 1.0)
0.95 │ ╭────────────╯
0.90 │ ╭──────╯ Severe degradation at tight Fibonacci tolerance (ε = 0.1)
└───┴──────────┴──────────┴──────────┴──────────► Error Tolerance (ε)
0.10 0.20 0.30 0.40 0.50
8.2 Why Do Looser Tolerances Perform Better? — 22:56
- Fibonacci Numerology is Arbitrary: Imposing strict ratios derived from Fibonacci sequences artificially filters out valid geometric swing reversals.
- Generic Price Reversals: The market does exhibit cyclical swing patterns, but the true underlying reversal dynamics do not conform strictly to ancient mathematical proportions.
- Data-Mining Over Sacred Numbers — 23:28: Rather than forcing dogmatic Fibonacci numbers, an institutional approach data-mines the optimal retracement ratios directly from empirical market distributions using walk-forward parameter estimation.