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

Chapter 19: Data Mining Candlestick Patterns with a Genetic Algorithm


Chapter Overview — 00:00

Retail trading literature is saturated with celebrated Japanese candlestick patterns—the Hammer, Shooting Star, Bullish Engulfing, Morning Star, and Doji. Yet empirical quantitative backtests consistently demonstrate that classical chartist patterns rarely provide a statistically robust edge on modern electronic markets.

Instead of accepting subjective historical folklore, this chapter explores an automated genetic algorithm (GA) framework to mine, evolve, and validate novel multi-bar candlestick patterns directly from raw price data.

                  GENETIC PATTERN EVOLUTION PIPELINE
                  
  [ Candlestick Data: O, H, L, C ]
                │
                ▼
  ┌─────────────────────────────────────────────────────────────┐
  │ 1. Initialization: Population of random relational rules    │
  │    e.g., (Open[0] > Low[1]) AND (Close[0] < High[1])        │
  └──────────────────────────────┬──────────────────────────────┘
                                 ▼
  ┌─────────────────────────────────────────────────────────────┐
  │ 2. Evaluation: Forward Return Series & Fitness Calculation  │
  │    Total Return | Profit Factor | Martin Ratio (Ulcer Index)│
  └──────────────────────────────┬──────────────────────────────┘
                                 ▼
  ┌─────────────────────────────────────────────────────────────┐
  │ 3. Genetic Operations:                                      │
  │    Elitism ──► Roulette Selection ──► Crossover ──► Mutation│
  └──────────────────────────────┬──────────────────────────────┘
                                 │ Next Gen
                                 ▼
  ┌─────────────────────────────────────────────────────────────┐
  │ 4. Diversity Enforcement: Pearson Correlation Penalty       │
  └──────────────────────────────┬──────────────────────────────┘
                                 ▼
  ┌─────────────────────────────────────────────────────────────┐
  │ 5. Rigorous Verification:                                   │
  │    Monte Carlo Permutations & Multi-Year Walk-Forward Tests │
  └─────────────────────────────────────────────────────────────┘

In this chapter, you will learn:

  1. How to formalize candlestick patterns as modular algebraic rule sets.
  2. The complete 6-stage lifecycle of an evolutionary trading algorithm.
  3. Why the Martin Ratio (Ulcer Performance Index) dramatically outperforms Total Return and Profit Factor as an optimization objective.
  4. How to evolve orthogonal, diversified pattern ensembles using correlation penalties.
  5. How to distinguish authentic market edge from data mining bias using Monte Carlo permutation tests and walk-forward validation.

1. Defining the Pattern Grammar & Schema — 00:15

A candlestick pattern is represented as a conjunction of logical relational rules comparing OHLC values across recent bars:

Pattern=R1∧R2∧⋯∧Rk\text{Pattern} = R_1 \land R_2 \land \dots \land R_k

Rule Anatomy

Each individual comparison rule consists of:

  • Left Variable: Series identifier (O,H,L,CO, H, L, C) at lag t1t_1.
  • Operator: Greater than (>>) or Less than (<<).
  • Right Variable: Series identifier (O,H,L,CO, H, L, C) at lag t2t_2.

For example: Rule 1:O0>L1(Current Open is greater than Previous Low)\text{Rule 1}: \quad O_0 > L_1 \quad (\text{Current Open is greater than Previous Low}) Rule 2:C0<H1(Current Close is less than Previous High)\text{Rule 2}: \quad C_0 < H_1 \quad (\text{Current Close is less than Previous High})

Hyperparameters & Semantic Hygiene

The pattern space is governed by two constraints:

  1. Pattern Size (kk): The number of comparison rules combined to form a single pattern (e.g., k=3k=3).
  2. Number of Candles (Lmax⁡L_{\max}): The maximum lookback horizon (lag values ∈[0,Lmax⁡−1]\in [0, L_{\max}-1], e.g., 3 candles).
# Conceptual representation of a 3-rule chromosome
chromosome = [
    {"left": ("open", 0),  "op": ">", "right": ("low", 1)},
    {"left": ("close", 0), "op": "<", "right": ("high", 1)},
    {"left": ("high", 1),  "op": ">", "right": ("high", 2)}
]

[!IMPORTANT] Rule Filtering When generating or mutating rules, the algorithm filters out:

  • Illogical Comparisons: Redundant or contradictory rules (e.g., H0<L0H_0 < L_0 or C0>H0C_0 > H_0).
  • Duplicate Rules: Replaced immediately with valid random comparisons.

2. The 6-Stage Genetic Algorithm Architecture — 01:31

A single generation cycles through six deterministic steps:

Stage 1: Initialization

Generate an initial population of MM randomized valid patterns conforming to the grammar.

Stage 2: Evaluation & Fitness Functions — 02:03

For each pattern, scan the dataset bar-by-bar. When all kk rules evaluate to True, record the 1-bar forward log return: rt+1=ln⁡(Ct+1Ct)r_{t+1} = \ln\left(\frac{C_{t+1}}{C_t}\right) For short-seeking patterns, flip the sign (−rt+1-r_{t+1}). Bars where the pattern does not trigger are assigned a return of 00.

All fitness functions must yield non-negative values (Fitness≥0\text{Fitness} \ge 0), with unprofitable patterns floored strictly at 00:

Fitness FunctionMathematical FormulationCharacteristics & Vulnerabilities
Total Return — 02:33max⁡(0,∑rt)\max\left(0, \sum r_t\right)Worst metric. Ignores risk and variance; prioritizes hyper-frequent patterns with massive market exposure.
Profit Factor — 03:05max⁡(0,ln⁡(∑Gains∑Losses))\max\left(0, \ln\left(\frac{\sum \text{Gains}}{\sum \text{Losses}}\right)\right)Biased toward rare outlier trades with high payoff ratios. Requires an artificial trade frequency constraint (≥2.5%\ge 2.5\% of bars) to prevent extreme overfitting.
Martin Ratio — 03:52Total ReturnUlcer Index\frac{\text{Total Return}}{\text{Ulcer Index}}Best metric. Penalizes both drawdown depth and duration. Generates smooth equity curves that generalize best out-of-sample.

Ulcer Index=1N∑i=1NDi2,Di=Pi−max⁡j≤i(Pj)max⁡j≤i(Pj)×100\text{Ulcer Index} = \sqrt{\frac{1}{N} \sum_{i=1}^N D_i^2}, \quad D_i = \frac{P_i - \max_{j \le i}(P_j)}{\max_{j \le i}(P_j)} \times 100

Stage 3: Elitism — 05:10

Copy the single best (or top 1–2%) individual directly into the next generation. This preserves peak fitness while avoiding premature genetic monoculture.

Stage 4: Parent Selection (Roulette Wheel) — 05:42

Selection probability is proportional to fitness: P(Parenti)=Fitnessi∑j=1MFitnessjP(\text{Parent}_i) = \frac{\text{Fitness}_i}{\sum_{j=1}^M \text{Fitness}_j} Patterns with zero fitness have a 0%0\% chance of reproduction ("survival of the fittest").

Stage 5: Reproduction & Crossover — 06:12

Given two selected parents, choose a random crossover point across the kk comparison rules. Swap genetic segments to produce two distinct children:

 Parent 1: [ Rule A1 | Rule A2   Rule A3 ]
 Parent 2: [ Rule B1 | Rule B2   Rule B3 ]
                       ▼ Crossover at split point 1
 Child 1:  [ Rule A1 | Rule B2   Rule B3 ]
 Child 2:  [ Rule B1 | Rule A2   Rule A3 ]

Stage 6: Mutation — 07:00

  1. Point Mutation (5%5\% probability): Mutates a single property of one rule (e.g., switches lag from 1 to 2, or changes Low to Close).
  2. Replacement Mutation (2%2\% probability): Replaces the entire pattern with a newly initialized random pattern to introduce fresh genetic material.
  3. Elite individuals are exempt from mutation.

3. Evolving Uncorrelated Pattern Ensembles — 09:23

A single candlestick pattern provides too few trades to build a diversified strategy. However, simply running the GA multiple times often yields identical or collinear patterns.

To discover distinct patterns, the algorithm penalizes fitness based on Pearson correlation with previously accepted patterns:

def penalize_fitness(new_pattern_returns, existing_patterns_returns, raw_fitness):
    """
    Penalizes fitness by the maximum correlation to any previously accepted pattern.
    """
    max_corr = 0.0
    for prev_returns in existing_patterns_returns:
        corr = np.corrcoef(new_pattern_returns, prev_returns)[0, 1]
        if corr > max_corr:
            max_corr = corr
            
    # If perfectly correlated (corr = 1), fitness becomes 0
    diversity_multiplier = max(0.0, 1.0 - max_corr)
    return raw_fitness * diversity_multiplier

Ensemble Execution

By chaining this process, an ensemble of 5 mutually uncorrelated patterns is mined. The trading rule is simple: take a 1-bar position whenever ANY of the 5 patterns triggers.

 Pattern 1: ───●───────────────●─────────
 Pattern 2: ────────●───────────────●────
 Pattern 3: ────────────●────────────────
 Combined:  ───▲────▲───▲──────▲────▲──── (Ensemble signals)

4. Verification & Overfitting Audits — 10:26

Because genetic algorithms search vast combinatorial spaces, in-sample performance is inherently inflated by data mining bias. Two statistical hurdles are required to test validity:

Test 1: Monte Carlo Permutation Test — 10:41

  • Methodology: Generate 100 permuted versions of the 2018 Bitcoin hourly dataset. Permuting price changes destroys the temporal ordering and geometric relationships while keeping the return distribution intact.
  • Run the identical GA to find 5-pattern ensembles on each permuted series.
  • Results:
    • Real Total Return exceeded 100% of the permuted distributions.
    • Real Martin Ratio ranked in the upper tail of the permuted distribution (ahead of nearly all permutations).
    • Conclusion: The GA is capturing authentic structural signal beyond pure random noise, but the signal margin is modest.

Test 2: Walk-Forward Out-of-Sample Validation — 11:42

The ensemble was trained on year TT and deployed strictly out-of-sample on year T+1T+1 across 2018–2022 on Bitcoin (BTC/USDT) and Ethereum (ETH/USDT) hourly candles:

  Train 2018 ──► Test 2019 (Profitable)
  Train 2019 ──► Test 2020 (Profitable)
  Train 2020 ──► Test 2021 (Profitable)
  Train 2021 ──► Test 2022 (Profitable, except Long BTC in bear market)

Empirical Observations

  1. Persistent Modest Profitability: Both long and short pattern ensembles remained net profitable across out-of-sample years.
  2. Performance Degradation: Out-of-sample Martin ratios were significantly lower than in-sample figures.
  3. Decaying Edge (Alpha Decay): Both in-sample and out-of-sample performance exhibited a gradual downward trend from 2018 to 2022, suggesting that market participants and algorithmic arbitrage are steadily compressing raw candlestick inefficiencies.
  4. Cross-Asset Portability: Applying the exact pipeline to Ethereum produced comparable profitable out-of-sample results.

5. Critical Assessment & Production Realities — 13:15

ConsiderationQuantitative FindingProduction Reality
Trading FrictionBacktests assumed 0% trading fee (reflecting Binance's zero-fee promo).With standard taker fees (e.g., 0.04%–0.075%) and slippage, the modest 1-bar edge is largely consumed.
Grammar ExpressivenessCurrent schema only evaluates boolean relative order (A>BA > B).Lacks price magnitude thresholds (e.g., $
Live ViabilityInsufficient standalone alpha for single-strategy execution.Highly effective as an orthogonal feature generator for downstream gradient-boosted trees (XGBoost/LightGBM) or neural networks.

Key Takeaways

  1. Rule Discretization Eliminates Subjectivity: Converting visual candlestick concepts into explicit relational rule sets enables algorithmic optimization and removes chartist ambiguity.
  2. Martin Ratio Penalizes Equity Pain: Optimizing for total return or profit factor invites overfitting and high-risk equity draws; optimizing for the Martin Ratio aligns the GA with institutional drawdown tolerances.
  3. Correlation Penalties Unlock Ensembles: Multiplying raw fitness by (1−rmax⁡)(1 - r_{\max}) forces genetic searches to discover structurally distinct market behaviors.
  4. Permutation Testing is Mandatory: Never trust in-sample machine-mined patterns without benchmarking against randomized noise distributions.

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