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

Chapter 10: Harmonic Pattern Recognition with Python


Chapter Overview — 00:00

Harmonic pattern trading is widely practiced in discretionary retail circles, where five-point price formations (XABCDXABCD) are identified using strict Fibonacci retracement and projection ratios (e.g., 0.6180.618, 0.7860.786, 1.2721.272, 1.6181.618). 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:

  1. The Golden Ratio Hypothesis: Testing whether price swing retracements cluster around Fibonacci levels using Kernel Density Estimation (KDE).
  2. Deterministic Segmentation: Employing the Directional Change (zigzag) algorithm across multiple scale parameters (σ\sigma).
  3. The 7 Canonical XABCD Geometries: Algorithmic definitions for the Gartley, Bat, Butterfly, Crab, Deep Crab, Cypher, and Shark patterns.
  4. Causal Pattern Detection Without Look-Ahead Bias: Formalizing the transition from confirmed swing CC to floating candidate DD.
  5. Logarithmic Ratio Error Metrics: Constructing distance functions for point ratios and bounded intervals.
  6. Multi-Scale Ensemble Strategy: Combining pattern signals across multiple scales into a continuous position-sizing engine [−1,1][-1, 1].
  7. 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 Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2} with seeds F0=0,F1=1F_0 = 0, F_1 = 1. The ratio of successive numbers converges asymptotically to the Golden Ratio:

lim⁡n→∞FnFn−1=ϕ≈1.6180339887...\lim_{n \to \infty} \frac{F_n}{F_{n-1}} = \phi \approx 1.6180339887...

The reciprocal is:

1ϕ=ϕ−1≈0.6180339887...\frac{1}{\phi} = \phi - 1 \approx 0.6180339887...

In trading lore, retracements of 0.6180.618 and extensions of 1.6181.618 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 σ\sigma from its running extreme.
  • σ=1%\sigma = 1\%: Captures high-frequency micro-swings.
  • σ=3%\sigma = 3\% or 4%4\%: 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 P0,P1,P2,…,PkP_0, P_1, P_2, \dots, P_k. The vertical segment height of the kk-th price leg is:

Hk=∣Pk−Pk−1∣H_k = |P_k - P_{k-1}|

The retracement ratio comparing the current segment to the preceding segment is:

Ratiok=HkHk−1\text{Ratio}_k = \frac{H_k}{H_{k-1}}

Because ratios are strictly positive and multiplicative, we transform them into log-space:

ln⁡(Ratiok)=ln⁡(Hk)−ln⁡(Hk−1)\ln(\text{Ratio}_k) = \ln(H_k) - \ln(H_{k-1})

A histogram of ln⁡(Ratio)\ln(\text{Ratio}) 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 (ln⁡(Ratio)=0\ln(\text{Ratio}) = 0).


3. Empirical Test: Does the Golden Ratio Naturally Emerge? — 04:43

To evaluate whether retracement ratios cluster at 0.6180.618 and 1.6181.618, we fit a Kernel Density Estimation (KDE) using SciPy's gaussian_kde on hourly Bitcoin data across varying σ\sigma 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

  • σ=1%\sigma = 1\%: A mild, negligible local bump around 1.6181.618.
  • σ=2%\sigma = 2\%: No distinct clustering at either 0.6180.618 or 1.6181.618.
  • σ=3%\sigma = 3\%: A notable, sharp spike occurs near the 1.6181.618 extension level.
  • σ=4%\sigma = 4\%: A weak peak appears at 1.6181.618, but 0.6180.618 remains statistically insignificant.

3.2 Interpretation

While there is mild empirical evidence for clustering at the 1.6181.618 extension during specific macro-scales (σ=3%\sigma = 3\%), the 0.6180.618 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 1.6181.618 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 (X,A,B,C,DX, A, B, C, D) 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:

  1. AB/XAAB / XA: Retracement of leg XAXA by leg ABAB.
  2. BC/ABBC / AB: Retracement of leg ABAB by leg BCBC.
  3. CD/BCCD / BC: Retracement or extension of leg BCBC by leg CDCD.
  4. AD/XAAD / XA: Overall retracement of the net move from XX to AA by point DD.

4.1 Canonical Ratios for 7 Major Harmonic Patterns — 07:08

PatternAB/XAAB / XA RatioBC/ABBC / AB RangeCD/BCCD / BC RangeAD/XAAD / XA Ratio
Gartley0.6180.618[0.382,0.886][0.382, 0.886][1.130,1.618][1.130, 1.618]0.7860.786
Bat[0.382,0.500][0.382, 0.500][0.382,0.886][0.382, 0.886][1.618,2.618][1.618, 2.618]0.8860.886
Butterfly0.7860.786[0.382,0.886][0.382, 0.886][1.618,2.618][1.618, 2.618][1.270,1.618][1.270, 1.618]
Crab[0.382,0.618][0.382, 0.618][0.382,0.886][0.382, 0.886][2.618,3.618][2.618, 3.618]1.6181.618
Deep Crab0.8860.886[0.382,0.886][0.382, 0.886][2.240,3.618][2.240, 3.618]1.6181.618
Cypher[0.382,0.618][0.382, 0.618][1.130,1.414][1.130, 1.414][1.270,2.000][1.270, 2.000]0.7860.786
SharkIgnored (None\text{None})[1.130,1.618][1.130, 1.618][1.618,2.240][1.618, 2.240][0.886,1.130][0.886, 1.130]

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:

  1. Confirming Point CC: We must wait for the Directional Change algorithm to confirm the extreme top or bottom that forms point CC (requiring a σ\sigma retrace).
  2. Updating Floating Point DD — 09:44:
    • For a Bullish Pattern: Once CC (a confirmed top) is established, each new bar's lowest low is evaluated as a potential candidate for point DD.
    • For a Bearish Pattern: Once CC (a confirmed bottom) is established, each new bar's highest high is evaluated as potential point DD.
  3. Execution at Candle Close — 10:15: As soon as candidate point DD aligns with all pattern ratios within tolerance ϵ\epsilon, a trade is entered immediately at that candle's close.
  4. 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 [L,U][L, U], or unconstrained (None\text{None}), 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:

Total Error=∑r∈{XA-AB,AB-BC,BC-CD,XA-AD}Error(r)\text{Total Error} = \sum_{r \in \{\text{XA-AB}, \text{AB-BC}, \text{BC-CD}, \text{XA-AD}\}} \text{Error}(r)

If the candidate's total error is below the defined tolerance threshold (Total Error≤ϵ\text{Total Error} \le \epsilon), 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 (σ=2%,ϵ=0.2\sigma = 2\%, \epsilon = 0.2)

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 σ\sigma:

  • The Shark Pattern: The only pattern that maintained a Profit Factor >1.0> 1.0 across every single tested σ\sigma 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" σ\sigma introduces severe curve-fitting. Instead, we ensemble the signals across an array of KK distinct scale thresholds (σ∈{1%,1.5%,2%,2.5%,3%}\sigma \in \{1\%, 1.5\%, 2\%, 2.5\%, 3\%\}):

Ensemble Signalt=1K∑k=1KSignalk,t\text{Ensemble Signal}_t = \frac{1}{K} \sum_{k=1}^K \text{Signal}_{k, t}

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 +0.67+0.67 or +1.0+1.0.
  • Isolated, single-scale signals execute at fractional risk (e.g., +0.2+0.2 or +0.33+0.33).

On Bitcoin, this multi-scale baseline with ϵ=0.2\epsilon = 0.2 produced a modest Profit Factor of 1.0261.026.


8. The Error Tolerance Paradox & Final Verdict — 21:07

With the multi-scale ensemble holding σ\sigma constant across all scales, only one free hyperparameter remains: the error threshold ϵ\epsilon.

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 (ϵ→0\epsilon \to 0) should isolate higher-quality reversals and increase the strategy's Profit Factor.
  • The Empirical Finding: The exact opposite occurs.
    • Tight error tolerances (ϵ≤0.1\epsilon \le 0.1) performed the worst.
    • As error tolerance was relaxed (ϵ→0.4−0.5\epsilon \to 0.4 - 0.5), 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

  1. Fibonacci Numerology is Arbitrary: Imposing strict ratios derived from Fibonacci sequences artificially filters out valid geometric swing reversals.
  2. Generic Price Reversals: The market does exhibit cyclical swing patterns, but the true underlying reversal dynamics do not conform strictly to ancient mathematical proportions.
  3. 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.

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