Chapter 16: Flag and Pennant Pattern Recognition in Python
- Source: Flag and Pennant Pattern Recognition in Python | Algorithmic Trading Strategy
- Channel: NeuroTrader
- Duration: 13:58
- Language: English
Chapter Overview — 00:00
While reversal patterns (like the Head and Shoulders) seek to pick tops and bottoms against prevailing momentum, flags and pennants are trend continuation patterns. They capture a fundamental market dynamic: a brief pause, consolidation, or interruption within a strong prevailing trend before momentum resumes.
BULL FLAG & PENNANT ANATOMY
Bull Flag (Parallel Channel) Bull Pennant (Converging Wedge)
Tip Tip
▲ /── Upper Line ▲ \
/ \ / / \ \
/ ● / ● \
/ / \ / / \ ● Breakout!
Pole / ● \ / ● \ /
Impulse / \ ▼ Breakout! / \ ▼
/ ● / / ●
/ \ /
Base ● Base ●
In textbook technical analysis:
- A Flag features roughly parallel bounding trend lines sloping in the opposite direction of the trend.
- A Pennant features converging bounding trend lines resembling a symmetrical triangle or pointed wedge.
Rather than obsessing over rigid chartist dogma, this chapter strips the pattern down to its quantitative essence: an impulsive pole followed by a compact consolidation.
In this chapter, you will learn:
- Geometric Formalization & Terminology: Defining Pole Base, Tip, Height, Width, Flag Height, Flag Width, and Confirmation Points.
- Method 1 (PIP Shape Recognition): Enforcing internal (bullish) and (bearish) multi-wave swing structures using Perceptually Important Points.
- Method 2 (Trendline Channel Recognition): Replacing rigid interior zig-zag requirements with linear regression trend lines and relaxed geometric bounds.
- Adaptive Time-Horizon Backtesting: Holding positions proportionally to consolidation duration () on hourly Bitcoin data (2018–2022).
- The Symmetry Breakthrough: How Method 2 unlocks rare bilateral profitability (both Bull and Bear Flags exhibiting consistent edge across multi-scale parameter sweeps).
- Machine Learning Feature Engineering: Formulating geometric pattern ratios to train meta-classifiers for breakout probability.
1. Pattern Anatomy & Mathematical Definitions — 00:55
To construct algorithmic scanners, visual charting terms must be converted into rigorous geometric metrics:
QUANTITATIVE PATTERN METRICS
Price
▲ Tip (x_tip, y_tip)
│ ●
│ / \ Upper Flag Line
│ / ●───────●
│ / / \ / \ Breakout Candle
│ / ● \ / ▲ (Confirmation)
│ / \ ●───────●
│ / \ Lower Flag Line
│ / ●
│ Base (x_base, y_base) ●
│ ◄─── Pole ──►◄─── Flag ──►
│ Width Width
└────────────────────────────────────────────────────────► Time
| Component | Formal Metric | Definition & Formula |
|---|---|---|
| Pole Base | Origin of the directional impulse (confirmed rolling window extremum). | |
| Pole Tip | Termination vertex of the impulse before consolidation begins. | |
| Pole Height | Vertical price change: . | |
| Pole Width | Number of elapsed bars: . | |
| Flag Width | Number of bars spent consolidating: . | |
| Flag Height | Vertical price span between highest and lowest points inside the flag. | |
| Confirmation | The bar where price closes outside the bounding channel in the trend direction. |
2. Method 1: PIP-Based Shape Recognition (M & W Structures) — 01:50
2.1 The Idealized Zig-Zag Model
The first identification method models the consolidation phase as an explicit 5-point alternating wave:
- Bull Flag: Forms a distinct -shape (Tip low high low breakout).
- Bear Flag: Forms a distinct -shape (Tip high low high breakout).
2.2 Algorithm Pipeline
- Identify the Pole Base: A confirmed local peak (Bear Flag) or local trough (Bull Flag) identified via the Rolling Window algorithm of parameter
order. - Identify the Pole Tip: The extreme price (maximum for bull, minimum for bear) achieved since the base.
- Extract 5 PIPs on Consolidation: From the Pole Tip up to the current candidate bar, extract 5 Perceptually Important Points (PIPs).
- Construct Bounding Lines:
- Upper Channel Line: Connects PIP 1 (Tip) and PIP 3.
- Lower Channel Line: Connects PIP 2 and PIP 4.
# Slope and intercept for upper line (PIPs 0 and 2) and lower line (PIPs 1 and 3)
m_upper, b_upper = fit_line(pip_x[0], pip_y[0], pip_x[2], pip_y[2])
m_lower, b_lower = fit_line(pip_x[1], pip_y[1], pip_x[3], pip_y[3])
2.3 Strict Geometric Filters
To eliminate distorted or degenerate formations, candidates must pass four qualification rules:
- Minimum Consolidation Time: .
- Width Ratio: Flag Width must be less than 50% of Pole Width (). Consolidations lasting longer than the initial impulse cease to be flags.
- Height Ratio: Flag Height must retrace less than 50% of the Pole Height ().
- Interior Alternation (-Shape Check): For a Bull Flag, the central internal vertex (PIP index 2) must be strictly higher than its neighboring points ( and ).
- Divergence Constraint: The intersection point of the two channel lines must not fall inside the flag body or diverge excessively backward ().
- Breakout Confirmation: The current candle's closing price must break above the upper bounding line for a Bull Flag ().
3. Method 1 Backtest Performance (Hourly BTC 2018–2022) — 06:53
3.1 Adaptive Time-Horizon Exit Rule
Rather than using arbitrary fixed-tick take profits or stops, the backtest evaluates structural forward expectancy:
- Holding Period = Flag Width ().
- Rationale: A larger consolidation (e.g., 20 candles) warrants a longer continuation move than a brief 4-candle micro-flag.
3.2 Empirical Results
Across rolling window order parameters on hourly Bitcoin (BTC/USDT):
- Bull Flags:
- Low order parameters () produced consistently positive average log returns and win rates exceeding 60%.
- Performance decayed significantly at larger orders (), indicating that larger macro consolidations do not reliably follow the rigid 5-point PIP structure.
- Bear Flags:
- Robust across both small and medium order parameters. Negative returns on short positions were rare, producing dependable trend continuation.
- Pennants (Both Bull and Bear):
- Failed completely. Formations occurred far less frequently and showed wildly inconsistent, negative returns.
- Bear Pennants performed so abysmally that trading them as continuation patterns consistently destroyed capital (suggesting they function better as counter-trend bear traps).
4. Method 2: Trendline Channel Recognition (Relaxed Consolidation) — 09:11
4.1 Shortcomings of the PIP Method
Method 1 possessed two key limitations:
- Over-Specification: Forcing price to conform to a strict 5-point or shape disqualified many legitimate, high-probability consolidations (e.g., tight multi-candle horizontal ranges or 3-touch channels).
- Non-Monotonic Scaling: The number of patterns discovered fluctuated erraticly across the order parameter sweep rather than scaling smoothly with lookback size.
4.2 Architecture of Method 2
Method 2 replaces PIP extraction with direct Trendline Fitting (fit_trendline_single) and anchors the pole between consecutive rolling window extrema:
METHOD 2 PIPELINE
Consecutive Extrema Linear Trendlines Relaxed Constraints
┌───────────────────────┐ ┌───────────────────────┐ ┌───────────────────────┐
│ Pole Base: RW Bottom │ ─────► │ Fit Upper & Lower │ ─────► │ Width < 50% Pole │
│ Pole Tip: RW Top │ │ Trendlines on Bars │ │ Height < 75% Pole │
└───────────────────────┘ │ (Tip to Current - 1) │ └───────────┬───────────┘
└───────────────────────┘ │
▼
Breakout Evaluation
┌───────────────────────┐
│ Current Bar Closes │
│ Beyond Upper/Lower Line│
└───────────────────────┘
- Pole Anchoring: The base is a confirmed rolling window bottom, and the tip is the adjacent rolling window top.
- Channel Regression: Fit upper and lower resistance/support trend lines using linear regression across all bars from up to (excluding the current candle).
- Relaxed Bounds:
- Flag Width remains .
- Flag Height threshold is relaxed from 50% to 75% of Pole Height ().
- Current Bar Breakout: The current bar triggers confirmation if its close penetrates the fitted channel line.
5. Method 2 Performance: Rare Bilateral Symmetry — 11:29
When backtested across the identical 5-year hourly Bitcoin dataset, Method 2 produced an exceptional quantitative breakthrough:
METHOD 2 PATTERN ROBUSTNESS SWEEP
Average Return
│
+3% ─┼───/───\───/───\──────/───\───/─── Bull Flags (Method 2)
+2% ─┼──/─────\─/─────\────/─────\─/──── Bear Flags (Method 2)
+1% ─┼─/───────▼───────\──/───────▼───── (Consistently Positive across all N!)
0 ─┼──────────────────────────────────
-1% ─┼───▲───────▲───────▲───────▲────── Pennants (Method 2)
-2% ─┼────\─────/─\─────/─\─────/─────── (Inconsistent / Negative)
└────┴──────┴───────┴───────┴──────► Order Parameter N (3..48)
5.1 Results Analysis
- Monotonic Discovery: The number of detected patterns scaled smoothly and monotonically as increased from 3 to 48.
- Bilateral Symmetry (Long & Short):
- Bull Flags: Generated positive average returns on almost every parameter value, with edge strengthening at larger orders () and win rates consistently .
- Bear Flags: Delivered equally powerful performance across the entire parameter spectrum.
- In quantitative finance, finding a technical pattern that demonstrates positive expectancy with near-perfect symmetry on both long and short sides is extraordinarily rare.
- Pennants Still Fail: Even under relaxed trendline fitting, converging pennants failed to produce reliable continuation returns.
6. Machine Learning Feature Engineering for Pattern Scoring — 12:56
6.1 "Legitimate" vs. "Textbook" Patterns
Traditional retail education teaches traders to evaluate patterns by whether they "look like pictures in a book." In quantitative algorithmic trading:
6.2 Feature Vector for Meta-Classifiers
Rather than applying hard binary thresholds (), the quantitative properties of discovered flag candidates should be converted into a continuous feature vector to train a machine learning model (e.g., LightGBM or Random Forest):
| Feature Name | Mathematical Formulation | Predictive Hypothesis |
|---|---|---|
| Aspect Ratio | Compact, narrow consolidations indicate aggressive institutional accumulation. | |
| Retracement Ratio | Shallow pullbacks () imply stronger trend continuation. | |
| Duration Ratio | Fast pauses retain higher momentum than prolonged grinds. | |
| Channel Divergence | Parallel channels () vs. converging pennants (). | |
| Volume Compression | Volume dry-up during consolidation precedes high-velocity breakouts. |
By training a binary classifier on these features, algorithmic execution can dynamically size positions or filter out low-expectancy flag breakouts.
Key Takeaways
- Trend interruptions provide superior edge: Unlike reversal formations (which fight prevailing momentum), flags exploit brief pauses in strong trends, capturing high-velocity continuation moves.
- Flags work; Pennants do not: Across multiple algorithm implementations and parameter sweeps, parallel flags consistently generated positive edge, whereas converging pennants produced inconsistent, net-negative returns.
- Trendline channel fitting outperforms rigid PIP shapes: Relaxing internal geometry and fitting linear trend lines (
fit_trendline_single) yielded far superior parameter stability and monotonic scaling. - Rare bilateral symmetry on Bitcoin: Method 2 flags proved profitable on both the long (Bull Flag) and short (Bear Flag) side across almost the entire spectrum of order lookbacks ().
- Adaptive holding horizons prevent premature exits: Scaling the holding period directly to the consolidation duration () effectively captures continuation momentum without relying on arbitrary fixed targets.