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

Chapter 16: Flag and Pennant Pattern Recognition in Python


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:

  1. Geometric Formalization & Terminology: Defining Pole Base, Tip, Height, Width, Flag Height, Flag Width, and Confirmation Points.
  2. Method 1 (PIP Shape Recognition): Enforcing internal WW (bullish) and MM (bearish) multi-wave swing structures using Perceptually Important Points.
  3. Method 2 (Trendline Channel Recognition): Replacing rigid interior zig-zag requirements with linear regression trend lines and relaxed geometric bounds.
  4. Adaptive Time-Horizon Backtesting: Holding positions proportionally to consolidation duration (Hold Period=Flag Width\text{Hold Period} = \text{Flag Width}) on hourly Bitcoin data (2018–2022).
  5. The Symmetry Breakthrough: How Method 2 unlocks rare bilateral profitability (both Bull and Bear Flags exhibiting consistent edge across multi-scale parameter sweeps).
  6. 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
ComponentFormal MetricDefinition & Formula
Pole Base(xbase,ybase)(x_{\text{base}}, y_{\text{base}})Origin of the directional impulse (confirmed rolling window extremum).
Pole Tip(xtip,ytip)(x_{\text{tip}}, y_{\text{tip}})Termination vertex of the impulse before consolidation begins.
Pole HeightHpoleH_{\text{pole}}Vertical price change: ∥ytip−ybase∥\|y_{\text{tip}} - y_{\text{base}}\|.
Pole WidthWpoleW_{\text{pole}}Number of elapsed bars: xtip−xbasex_{\text{tip}} - x_{\text{base}}.
Flag WidthWflagW_{\text{flag}}Number of bars spent consolidating: xcurrent−xtipx_{\text{current}} - x_{\text{tip}}.
Flag HeightHflagH_{\text{flag}}Vertical price span between highest and lowest points inside the flag.
Confirmation(xconfirm,yconfirm)(x_{\text{confirm}}, y_{\text{confirm}})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 WW-shape (Tip →\rightarrow low →\rightarrow high →\rightarrow low →\rightarrow breakout).
  • Bear Flag: Forms a distinct MM-shape (Tip →\rightarrow high →\rightarrow low →\rightarrow high →\rightarrow breakout).

2.2 Algorithm Pipeline

  1. Identify the Pole Base: A confirmed local peak (Bear Flag) or local trough (Bull Flag) identified via the Rolling Window algorithm of parameter order.
  2. Identify the Pole Tip: The extreme price (maximum for bull, minimum for bear) achieved since the base.
  3. Extract 5 PIPs on Consolidation: From the Pole Tip up to the current candidate bar, extract 5 Perceptually Important Points (PIPs).
  4. 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:

  1. Minimum Consolidation Time: Wflag≥max⁡(5,⌊order/2⌋)W_{\text{flag}} \ge \max(5, \lfloor \text{order} / 2 \rfloor).
  2. Width Ratio: Flag Width must be less than 50% of Pole Width (Wflag≤0.50×WpoleW_{\text{flag}} \le 0.50 \times W_{\text{pole}}). Consolidations lasting longer than the initial impulse cease to be flags.
  3. Height Ratio: Flag Height must retrace less than 50% of the Pole Height (Hflag≤0.50×HpoleH_{\text{flag}} \le 0.50 \times H_{\text{pole}}).
  4. Interior Alternation (WW-Shape Check): For a Bull Flag, the central internal vertex (PIP index 2) must be strictly higher than its neighboring points (ypip,2>ypip,1y_{\text{pip}, 2} > y_{\text{pip}, 1} and ypip,2>ypip,3y_{\text{pip}, 2} > y_{\text{pip}, 3}).
  5. Divergence Constraint: The intersection point of the two channel lines must not fall inside the flag body or diverge excessively backward (xintersect<xtip−1.0×Wflagx_{\text{intersect}} < x_{\text{tip}} - 1.0 \times W_{\text{flag}}).
  6. Breakout Confirmation: The current candle's closing price must break above the upper bounding line for a Bull Flag (pt>mupper⋅t+bupperp_t > m_{\text{upper}} \cdot t + b_{\text{upper}}).

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 (WflagW_{\text{flag}}).
  • 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 N∈[3,48]N \in [3, 48] on hourly Bitcoin (BTC/USDT):

  • Bull Flags:
    • Low order parameters (N≤12N \le 12) produced consistently positive average log returns and win rates exceeding 60%.
    • Performance decayed significantly at larger orders (N>24N > 24), 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:

  1. Over-Specification: Forcing price to conform to a strict 5-point WW or MM shape disqualified many legitimate, high-probability consolidations (e.g., tight multi-candle horizontal ranges or 3-touch channels).
  2. 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│
                                                                   └───────────────────────┘
  1. Pole Anchoring: The base is a confirmed rolling window bottom, and the tip is the adjacent rolling window top.
  2. Channel Regression: Fit upper and lower resistance/support trend lines using linear regression across all bars from xtipx_{\text{tip}} up to xcurrent−1x_{\text{current}} - 1 (excluding the current candle).
  3. Relaxed Bounds:
    • Flag Width remains ≤0.50×Wpole\le 0.50 \times W_{\text{pole}}.
    • Flag Height threshold is relaxed from 50% to 75% of Pole Height (Hflag≤0.75×HpoleH_{\text{flag}} \le 0.75 \times H_{\text{pole}}).
  4. 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

  1. Monotonic Discovery: The number of detected patterns scaled smoothly and monotonically as NN increased from 3 to 48.
  2. Bilateral Symmetry (Long & Short):
    • Bull Flags: Generated positive average returns on almost every parameter value, with edge strengthening at larger orders (N≥20N \ge 20) and win rates consistently >50%> 50\%.
    • 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.
  3. 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:

A legitimate pattern is simply one that produces statistically significant positive forward expectancy.\text{A legitimate pattern is simply one that produces statistically significant positive forward expectancy.}

6.2 Feature Vector for Meta-Classifiers

Rather than applying hard binary thresholds (Hflag≤0.75H_{\text{flag}} \le 0.75), the quantitative properties of discovered flag candidates should be converted into a continuous feature vector x∈Rd\mathbf{x} \in \mathbb{R}^d to train a machine learning model (e.g., LightGBM or Random Forest):

Feature NameMathematical FormulationPredictive Hypothesis
Aspect RatioWflagHflag\frac{W_{\text{flag}}}{H_{\text{flag}}}Compact, narrow consolidations indicate aggressive institutional accumulation.
Retracement RatioHflagHpole\frac{H_{\text{flag}}}{H_{\text{pole}}}Shallow pullbacks (<0.382< 0.382) imply stronger trend continuation.
Duration RatioWflagWpole\frac{W_{\text{flag}}}{W_{\text{pole}}}Fast pauses retain higher momentum than prolonged grinds.
Channel Divergenceθupper−θlower\theta_{\text{upper}} - \theta_{\text{lower}}Parallel channels (Δθ≈0\Delta \theta \approx 0) vs. converging pennants (Δθ<0\Delta \theta < 0).
Volume CompressionVˉflagVˉpole\frac{\bar{V}_{\text{flag}}}{\bar{V}_{\text{pole}}}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 (N∈[3,48]N \in [3, 48]).
  • Adaptive holding horizons prevent premature exits: Scaling the holding period directly to the consolidation duration (Hold=Wflag\text{Hold} = W_{\text{flag}}) effectively captures continuation momentum without relying on arbitrary fixed targets.

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