Chapter 15: Automated Head and Shoulders Pattern Recognition in Python
- Source: Automated Head and Shoulders Chart Pattern in Python | Algorithmic Trading Strategy
- Channel: NeuroTrader
- Duration: 11:01
- Language: English
Chapter Overview — 00:00
The Head and Shoulders (H&S) formation—along with its bullish counterpart, the Inverted Head and Shoulders (IHS)—is widely considered the crown jewel of classical technical analysis. Traditional charting literature claims that these 5-point reversal structures reliably signal exhaustion and trend reversal.
However, manual discretionary trading of H&S patterns is plagued by subjective bias, cherry-picked hindsight, and significant execution slippage. By the time a human trader visually confirms that price has breached the neckline, the breakout candle has often already completed the majority of the move.
STANDARD HEAD AND SHOULDERS ANATOMY
● Head (H)
/ \
/ \
Left Shoulder (LS)● ● Right Shoulder (RS)
/ \ / \
/ \ / \
/ ● \
/ Left ● Neckline Break (Late Entry!)
/ Armpit (LA) \
● ● Right Armpit (RA)
In this chapter, you will learn:
- Mathematical Formalization of the 5 Turning Points: Detecting Left Shoulder, Left Armpit, Head, Right Armpit, and Right Shoulder using rolling window extrema.
- Geometric Validation Rules: Implementing formal Balance and Symmetry ratio constraints from academic algorithmic pattern recognition literature.
- The Early Identification Breakthrough: Solving the neckline breakout lag problem by confirming entries at the Right Shoulder-to-Armpit midpoint.
- Exit Strategy Comparison: Benchmarking fixed-horizon time exits (scaled to Head Span) against classical textbook price-target projections (Head Height).
- Empirical Parameter Sensitivity Analysis: Backtesting multi-scale order parameters () on 5 years of hourly Bitcoin data (2018–2022) to reveal where classical TA dogma holds and where it completely collapses.
1. Geometric Definition & Algorithmic Rules — 00:27
1.1 The Five Key Extremum Vertices
A standard Head and Shoulders pattern consists of three consecutive peaks separated by two intermediate troughs:
- Left Shoulder (): First local peak.
- Left Armpit (): First intervening local trough.
- Head (): Highest peak, strictly exceeding both shoulders.
- Right Armpit (): Second intervening local trough.
- Right Shoulder (): Final local peak, lower than the Head.
- Neckline: The linear trend line connecting the two armpits ().
For the Inverted Head and Shoulders (IHS), the geometry is symmetrically inverted (three troughs separated by two intermediate reaction peaks).
1.2 Extrema Detection via Rolling Window
To identify turning points dynamically without lookahead bias, we apply the Rolling Window Algorithm parameterized by order :
- A bar at index is confirmed as a local maximum if for all .
- A bar is confirmed as a local minimum if for all .
- Extrema indices are appended to a double-ended queue (
collections.deque(maxlen=5)). - Because market data can produce consecutive peaks without an intervening trough, the algorithm enforces a strict alternating verification check (
PeakTroughPeakTroughPeak).
1.3 Geometric Qualification Constraints
To prevent false-positive identifications of arbitrary noise as H&S patterns, we enforce three strict geometric rules adapted from Technical Analysis for Algorithmic Pattern Recognition:
GEOMETRIC VERIFICATION RULES
Rule 1: Head Prominence Rule 2: Balance Constraint
Head > LS, RS Midpoint Checks
▲ ▲
/ \ / \
▲ / \ ▲ ▲ / \ ▲
/ \ / \ / \ / \ / * \ / \
● ● ● ● ●---●-------●---● <-- Midpoints
LA RA LA RA
Shoulders must stay ABOVE midpoints!
Rule 1: Head Prominence
The central peak must be strictly higher than both surrounding shoulders:
Rule 2: Balance Rule
Calculate the vertical midpoint between each shoulder and its corresponding armpit:
To ensure balance, each shoulder must not be disproportionately deflated relative to the opposite armpit: the Left Shoulder must remain above , and the Right Shoulder must remain above .
Rule 3: Temporal Symmetry Rule
The time elapsed between the Left Shoulder and Head must be comparable to the time elapsed between the Head and Right Shoulder:
If one half of the pattern takes more than 2.5 times longer to form than the other, the pattern is disqualified due to temporal asymmetry.
2. The Execution Dilemma & Early Identification — 01:50
2.1 The Late Breakout Problem
Standard textbook convention dictates entering a trade on the close of the candle that penetrates the neckline. However, empirical market inspection reveals a severe flaw:
- Because the neckline is universally watched, once the price reaches it, aggressive market orders trigger simultaneously (breakout traders + stop runs).
- The candle breaking the neckline is frequently an extended, high-range bar.
- Entering on the close of this candle incurs extreme adverse slippage and forfeits the majority of the risk-reward ratio.
CONVENTIONAL VS. EARLY ENTRY
● Head
/ \
Left Shoulder / \ Right Shoulder
● / \ ●
/ \ / \ / \
/ \ / \ / ▼ [EARLY ENTRY]
/ \ / \ / Crosses RS-RA Midpoint!
/ \ / \ /
● ● ●
Start LA RA
\ /
\ /
─────────────────────────► ✘ [CONVENTIONAL ENTRY]
Neckline Breaks Neckline (Late, exhausted move)
2.2 The Early Identification Mechanism
Instead of waiting for full neckline penetration, we define an Early Identification trigger:
- Monitor price immediately after the Right Shoulder is formed.
- Confirm the pattern the moment price crosses below the midpoint between the Right Shoulder and the Right Armpit:
[!TIP] Trade-Off Analysis: Early identification sacrifices win rate on patterns that fail to break the neckline, but captures significantly better entry prices on patterns that successfully complete. As backtesting demonstrates, this trade-off is massively asymmetric in favor of early entry.
3. Python Implementation Architecture — 02:44
3.1 Data Structures & Dynamic Shoulder Detection
Waiting for the rolling window algorithm to confirm the Right Shoulder introduces an unacceptable lag of candles. To eliminate this delay, find_hs_patterns detects the Right Shoulder dynamically:
- Once the Right Armpit is confirmed by the rolling window, the algorithm scans every subsequent candle.
- The Right Shoulder is dynamically assigned as the maximum price recorded since the Right Armpit.
- Pattern validation checks execute on every incoming bar.
@dataclass
class HSDataClass:
inverted: bool
indices: list[int] # [start, ls, la, head, ra, rs, break]
prices: list[float] # Corresponding prices
start_idx: int
end_idx: int
neckline_slope: float
neckline_intercept: float
3.2 Backward Pattern Start Tracing
To calculate exact pattern dimensions, the algorithm traces backwards in time before the Left Shoulder () to find the true origin of the move:
- Extrapolate the neckline backwards: .
- Step backwards candle-by-candle from until finding the first bar that crossed below the neckline.
- This historical cross point represents the formal beginning of the pattern.
4. Exit Mechanisms: Time Horizon vs. Classical TA Stops — 05:30
Two distinct exit models are benchmarked:
Exit Model 1: Head Span Holding Period (Dynamic Time Horizon)
The trade is held for a duration equal to the Head Span (the number of candles between the Left Armpit and Right Armpit):
- Larger, wider patterns automatically yield longer holding periods.
- Eliminates stop-hunting noise and captures average momentum drift.
Exit Model 2: Classical TA Stop-Loss & Take-Profit
Following traditional technical analysis textbooks:
- Take-Profit (Target): Projected by taking the vertical distance from the Head to the Neckline at the Head's index (Head Height) and projecting it from the Neckline breakout point:
- Stop-Loss: Anchored at the peak of the Right Shoulder ().
- Time Limit: If neither the Take-Profit nor Stop-Loss is triggered within a duration equal to the Head Span, the trade is liquidated at market close.
5. Empirical Performance on Bitcoin (2018–2022) — 07:20
Testing was conducted on hourly Bitcoin (BTC/USDT) from January 2018 through December 2022 across 48 rolling window order parameters ().
| Pattern Type | Detection Mode | Exit Strategy | Performance & Consistency | Win Rate |
|---|---|---|---|---|
| Bearish H&S | Standard (Neckline) | Time Hold (Head Span) | Inconsistent. Small worked; medium lost heavily; large mediocre. | 42–48% |
| Bearish H&S | Standard (Neckline) | Classical TP / SL | Severely degraded. Premature stops ruined profitability. | 35–42% |
| Bearish H&S | Early Identification | Time Hold / Stop | Failed. Substantial false-positive breakdowns; negative total return. | 38–44% |
| Inverted H&S | Standard (Neckline) | Time Hold (Head Span) | Inconsistent. Narrow profitable parameter bands; unstable edge. | 45–50% |
| Inverted H&S | Standard (Neckline) | Classical TP / SL | Minor improvement on large patterns, but overall poor consistency. | 42–47% |
| Inverted H&S | Early Identification | Time Hold (Head Span) | Outstanding. Consistently profitable across nearly all . | 54–63% |
INVERTED H&S PERFORMANCE COMPARISON
Cumulative Return
│
│ /--- Early Identification
│ / (Robust across all N)
│ /---/
│ /---/
│ /---/
│ ───────────────────────────────── Standard Neckline Break
│ \ / \ (Inconsistent, choppy)
│ \----/ \----
└──────────────────────────────────────────────► Order Parameter N (1..48)
5.1 Why Early Inverted H&S Works While Bearish H&S Fails
- Structural Market Asymmetry in Crypto:
Bitcoin during 2018–2022 exhibited strong macro upward drift interspersed with violent flash crashes and liquidations.
- Bearish topping structures often experience sudden vicious short squeezes before rolling over, stopping out short positions.
- Bullish rounding accumulations (Inverted H&S) allow smart-money positioning. Entering early as price breaks the right shoulder midpoint front-runs the inevitable breakout run.
- Textbook Profit Targets Are Illusions: The traditional Head Height target () proved almost entirely unhelpful. Markets rarely move in exact textbook geometric projections. Time-based exits or trailing momentum indicators drastically outperform arbitrary price targets.
6. Algorithmic Reality: What Makes Patterns Work — 10:04
The empirical failure of most standard Head & Shoulders configurations highlights crucial tenets of quantitative research:
- Dogma Alpha: Chart patterns taught in popular retail trading books fail when subjected to unbiased algorithmic backtesting across parameter spaces.
- Execution Timing Dominates Geometry: The exact same geometric formation (Inverted H&S) was completely unviable under textbook neckline confirmation, but became highly profitable when modified with Early Identification.
- Parameter Stability is the Ultimate Test: An algorithmic edge is only legitimate if it remains profitable across a continuous spectrum of order parameters (). If a pattern only "works" at and loses at and , it is pure curve-fitting.
Key Takeaways
- Rolling window lag kills shoulder detection: Never wait for a rolling window to confirm the Right Shoulder. Anchor the Right Armpit, then dynamically identify the Right Shoulder on incoming bars.
- Enforce formal Balance and Symmetry: Using mathematical constraints (shoulder heights relative to armpit midpoints; left vs. right duration ratio ) eliminates over 70% of false-positive noise.
- Neckline breakouts are a retail trap: Entering on the close of neckline breakout candles forfeits the favorable risk-reward zone.
- Early Inverted H&S is a legitimate crypto edge: Front-running the neckline by entering at the Right Shoulder-to-Armpit midpoint creates a robust, multi-year statistical advantage on hourly Bitcoin.
- Discard textbook Take-Profit targets: Head Height projections rarely hit before adverse pullbacks. Dynamic time horizons based on pattern span provide far superior risk-adjusted returns.