Chapter 14: Data Mining Novel Chart Patterns with Python
- Source: Data Mining Novel Chart Patterns With Python | Algorithmic Trading Strategy
- Channel: NeuroTrader
- Duration: 20:52
- Language: English
Chapter Overview — 00:00
Classical technical analysis relies almost entirely on human-curated, subjective geometric shapes (e.g., Head & Shoulders, double tops, triangles) formulated decades ago in manual charting literature. However, modern financial time series contain thousands of recurring multi-bar microstructures that human perception overlooks.
Instead of hand-crafting rigid pattern definitions, this chapter establishes an end-to-end unsupervised machine learning pipeline to mine novel, high-performing chart patterns directly from historical price data.
UNSUPERVISED PATTERN MINING PIPELINE
Raw OHLCV Series PIP Compression & Filtering Z-Score Normalization
┌─────────────────┐ ┌───────────────────────────┐ ┌───────────────────────┐
│ Hourly Log │ ─────► │ Sliding Window (24 bars) │ ──────► │ Zero-Mean, Unit-Var │
│ Price Series │ │ Extract 5 PIP Vertices │ │ Scale-Invariant Shapes│
└─────────────────┘ │ Discard Trivial Overlaps │ └──────────┬────────────┘
└───────────────────────────┘ │
▼
Signal Generation Expectancy Evaluation K-Means Clustering
┌─────────────────┐ ┌───────────────────────────┐ ┌───────────────────────┐
│ Walk-Forward │ ◄───── │ Select Max & Min │ ◄────── │ Silhouette Scan │
│ Out-of-Sample │ │ Martin Ratio Clusters │ │ (k = 5..40) │
│ Execution │ │ (UI Drawdown Adjusted) │ │ Centroid Archetypes │
└─────────────────┘ └─────────────┬─────────────┘ └───────────────────────┘
│
▼
Monte Carlo Permutation Test
┌───────────────────────────┐
│ Shuffle Log Returns (100x)│
│ Validate Real vs. Noise │
└───────────────────────────┘
In this chapter, you will learn:
- The Subsequence Clustering Fallacy: Why naive sliding window clustering produces mathematically meaningless noise (the Keogh critique) and how state-filtered Perceptually Important Points (PIPs) solve it.
- Geometric Normalization: Transforming raw price segments into scale-invariant coordinate vectors using Z-score standardization.
- Unsupervised Archetype Discovery: Using K-Means clustering paired with Silhouette Score optimization to dynamically determine the optimal pattern count.
- Risk-Adjusted Expectancy via Martin Ratio: Evaluating cluster profitability using the Ulcer Index to penalize both the depth and duration of drawdowns.
- Combating Data Mining Bias: Implementing Monte Carlo return permutations to statistically prove edge over pure random chance.
- Walk-Forward Out-of-Sample Validation: Testing discovery stability and model decay on Bitcoin hourly data across multi-year walk-forward folds.
1. The Subsequence Clustering Problem & The Keogh Critique — 00:45
1.1 The Naive Sliding Window Trap
In 2001, early data mining literature proposed extracting consecutive sliding windows from financial time series and clustering them directly with algorithms like K-Means. However, in 2003, a landmark paper by Eamonn Keogh et al. demonstrated that clustering time series subsequences extracted by sliding windows is completely meaningless.
When a window of size slides bar-by-bar across smooth time series:
- Consecutive windows share points (massive mutual information overlap).
- Adjacent subsequences create "trivial matches" where points cluster together simply due to temporal continuity.
- The resulting centroids converge to sine waves or smooth averages regardless of the underlying data distribution, rendering the discovered patterns essentially random.
1.2 The 2005 Resolution: State-Filtered PIPs
To prevent meaningless pattern discovery, we apply the 2005 resolution to subsequence clustering:
- Dimensionality Reduction: Compress a 24-candle window into 5 Perceptually Important Points (PIPs).
- Point 1: Window start .
- Point 2: Window end .
- Points 3, 4, 5: Internal extrema having the maximum perpendicular distance from adjacent line segments.
- State Filtering: Slide the 24-candle window forward bar-by-bar, but only append the pattern to the dataset if the internal PIP coordinates change. If the internal extrema indices match the previous window, the subsequence is discarded.
This state filter eliminates trivial overlaps, drastically compresses sample size, speeds up clustering algorithms, and ensures that every recorded pattern represents a distinct structural swing.
2. Feature Representation & Z-Score Normalization — 02:48
2.1 Logarithmic Pricing
Financial assets exhibit non-stationary variance and exponential price growth over multi-year periods. Raw price differences at $60,000 Bitcoin are not directly comparable to movements at $6,000 Bitcoin. Therefore, prices are first transformed into logarithmic space:
2.2 Z-Score Coordinate Scaling
To compare a 5-point price shape formed during low volatility with one formed during high volatility, each candidate pattern must be scale-invariant. Given the price levels of the 5 PIPs , we normalize them via Z-score standardization:
Where:
- is the mean price level across the 5 points.
- is the standard deviation across the 5 points.
Raw Price Pattern ($) Z-Score Normalized Vector ($z$)
42,800 ───● (P1) +1.42 ───● (P1)
\ \
42,400 ─── \ ● (P3) +0.21 ─── \ ● (P3)
\ / \ \ / \
42,000 ─── \ / \ ● (P4) -0.54 ─── \ / \ ● (P4)
\ / \ / \ / \ /
41,600 ─── ● ● -1.09 ─── ● ●
(P2) (End) (P2) (End)
[!NOTE] In this implementation, the algorithm clusters solely on the normalized vertical price coordinates (), ignoring the horizontal time intervals between points. This focuses the clustering engine purely on geometric price formations.
3. Clustering Engine: K-Means & Silhouette Optimization — 05:03
3.1 Why Centroid-Based K-Means?
To deploy discovered patterns into live or out-of-sample trading, the model must instantaneously classify newly streaming market bars. K-Means clustering models each pattern family as an explicit centroid vector . Out-of-sample classification requires only calculating the Euclidean distance between the live normalized PIP vector and all cluster centers:
3.2 The Optimal Cluster Count Dilemma
Selecting the number of clusters involves a critical trade-off:
- Small (e.g., ): Large sample size per cluster increases statistical confidence, but averages together dissimilar shapes into loose, blurry centroids.
- Large (e.g., ): Centroids capture sharp, distinct geometric patterns, but sample size drops severely, risking small-sample overfitting.
3.3 Silhouette Score Scanning
To resolve this trade-off objectively, the pipeline utilizes Silhouette Analysis (via pyclustering.cluster.silhouette), testing candidate cluster sizes from to .
For each sample , the silhouette coefficient balances intra-cluster cohesion with nearest-cluster separation :
The algorithm averages across the entire dataset for each and selects the parameter that maximizes the mean Silhouette Score. The centroids are initialized using KMeans++ to prevent convergence to suboptimal local minima.
4. Performance Expectancy: Ulcer Index & Martin Ratio — 07:50
4.1 Fixed Horizon Forward Holding Period
When a pattern matching cluster terminates at candle index , a trade enters on the close and holds for a fixed holding period . With a pattern lookback of 24 candles, the holding horizon is set to 6 candles (one-fourth of the pattern formation length).
4.2 The Martin Ratio vs. Sharpe Ratio
Standard metrics like the Sharpe or Sortino ratio penalize volatility or downside variation on a bar-by-bar basis, ignoring the psychological and structural pain of prolonged drawdown periods. To evaluate cluster quality, the system employs the Martin Ratio, which replaces standard deviation with the Ulcer Index (UI).
The percentage drawdown at any bar during the cumulative equity curve is:
The Ulcer Index sums the squared percentage drawdowns across all bars:
| Metric Component | Mathematical Impact | Practical Trading Meaning |
|---|---|---|
| Squared Drawdown | Quadratic scaling of drawdowns | A 20% drawdown hurts 4x more than a 10% drawdown. |
| Summation over Horizon | Duration accumulation | Deep drawdowns that linger for weeks accumulate massive penalties. |
| Martin Ratio Score | High return + shallow, fast recoveries | Rewards patterns that trend immediately without prolonged adverse excursion. |
4.3 Pattern Selection Logic
- For every cluster , create a binary signal vector (equal to 1 for bars following every instance of cluster ).
- Calculate the Martin Ratio for all clusters.
- Best Long Pattern: The cluster index achieving the maximum positive Martin Ratio.
- Best Short Pattern: The cluster index yielding the lowest (most negative) return / Martin Ratio, flipped symmetrically ().
- The combined strategy concurrently trades both the top long and top short archetypes.
5. Combating Selection Bias: Monte Carlo Permutation Testing — 13:23
5.1 The Data Mining Fallacy
When an algorithm scans dozens of clusters across thousands of bars, it will inevitably find patterns that produced outstanding in-sample returns purely by random chance (data snooping / selection bias). Presenting in-sample backtest curves without statistical validation is misleading.
5.2 The Permutation Protocol
To verify whether the discovered patterns reflect true structural market inefficiency or random variance, we construct a Monte Carlo Permutation Test:
- Take the original hourly log return series .
- Randomly shuffle (permute) the return array . Shuffling completely destroys all temporal autocorrelation, sequential structure, and chart geometry while preserving the exact marginal return distribution, mean, variance, and kurtosis.
- Reconstruct a synthetic permuted price series via cumulative summation: .
- Run the complete data mining pipeline from scratch on the permuted series: PIP extraction Silhouette K-Means clustering Best cluster selection Final combined Martin Ratio.
- Repeat this process for independent random permutations to build an empirical null distribution .
MONTE CARLO PERMUTATION HISTOGRAM
Frequency
│ ┌───┐
│ ┌───┤ ├───┐
│ │ │ │ │
│ ┌───┤ │ │ ├───┐
│ ┌───┤ │ │ │ │ ├───┐ Actual Market Data
│ │ │ │ │ │ │ │ │ Martin Ratio
└─┴───┴───┴───┴───┴───┴───┴───┴───────────────▼──────────────►
-1.0 -0.5 0.0 0.5 1.0 ... 3.85 (Martin Ratio)
[ ─── Shuffled Synthetic Noise Paths ─── ]
5.3 Empirical Results
On hourly Bitcoin data (2018–2019):
- The Silhouette method identified as the optimal cluster count.
- In 100 random noise permutations, data mining on random paths generated maximum Martin ratios clustering between 0.2 and 1.4 due to selection bias.
- The Martin ratio discovered on actual Bitcoin price data was substantially higher than all 100 permutations.
- This quasi-p-value () proves that the real price series possesses persistent structural dependencies that do not exist in random walks.
6. Walk-Forward Out-of-Sample Testing — 16:14
6.1 Walk-Forward Architecture
To evaluate true out-of-sample robustness, the system implements a rolling walk-forward test across hourly Bitcoin data from 2018 through 2022:
- In-Sample Training Window: 2 years (17,520 hourly bars).
- Out-of-Sample Test Window: 1 year (8,760 hourly bars).
- Step Size: 1 year.
Fold 1: [ Train: 2018 - 2019 ] ──► [ Test: 2020 ]
Fold 2: [ Train: 2019 - 2020 ] ──► [ Test: 2021 ]
Fold 3: [ Train: 2020 - 2021 ] ──► [ Test: 2022 ]
6.2 Out-of-Sample Execution Mechanics
At each live hourly bar :
- Check if has reached the next training boundary; if so, re-run full PIP extraction, Silhouette search, and K-Means training on the trailing 2-year history.
- Extract the current 5 PIPs on the most recent 24 bars and normalize them via Z-score.
- Compute the Euclidean distance between the live vector and all active cluster centroids.
- If the nearest centroid matches the active long pattern archetype, emit
Signal = +1; if it matches the active short archetype, emitSignal = -1; otherwise emitSignal = 0. - Maintain the position for the 6-hour holding duration.
6.3 Empirical Performance & Alpha Decay
- 2020 Performance: Strong out-of-sample gains. The patterns mined from 2018–2019 continued to exploit market structural tendencies throughout 2020.
- 2021–2022 Performance: Performance plateaued and decayed into flat, choppy equity.
- Diagnosis: Crypto market microstructures evolved drastically between 2020 and 2022 (institutional inflows, explosive perpetual swap derivatives volume, algorithmic liquidity shifts). Static geometric clusters mined over historical multi-year windows suffer from regime obsolescence unless re-trained at higher frequencies or paired with macro volatility filters.
7. Critical Limitations & Practical Research Extensions — 19:35
- K-Means Initialization & Local Optima: Solving optimal K-Means clustering is NP-hard. Even with K-Means++, different random seeds yield slightly different cluster centers and selected patterns. In production systems, ensemble clustering (averaging multiple runs) or deterministic hierarchical clustering should be explored.
- Fixed Time vs. Volatility Exits: Holding a trade for a rigid 6-hour window ignores whether volatility is expanding or contracting. Incorporating Average True Range (ATR) based trailing stops or profit targets scaled to the PIP height would improve risk management.
- Nearest-Neighbor (k-NN) Direct Retrieval: Rather than clustering into discrete static centroids, one could store all historical normalized PIP vectors in a database and perform real-time k-Nearest-Neighbors (or Dynamic Time Warping) searches against current market structure.
- Machine Learning Meta-Classification: Instead of taking every trade where Euclidean distance is minimal, train a secondary gradient boosting model (XGBoost/LightGBM) using volume profile, funding rates, and pattern aspect ratios to filter out low-probability cluster activations.
Key Takeaways
- Subsequence clustering requires state filtering: Naive sliding windows produce trivial, meaningless clusters. Compressing price action with Perceptually Important Points and discarding consecutive duplicate internal extrema restores statistical validity.
- Normalize before clustering: Always convert prices to log space and standardize candidate shapes using Z-scores () to cluster geometric price action independent of absolute dollar levels.
- The Ulcer Index detects real risk: Evaluating trading patterns with the Martin Ratio penalizes drawdowns by both depth and duration, eliminating patterns that produce volatile, unviable equity curves.
- Permutation testing is mandatory: Never trust in-sample data mining results without running identical mining routines on 100+ return-shuffled noise series to quantify selection bias.
- Expect alpha decay across regimes: Visual patterns mined in one regime will decay as market participants adapt. Production models require rolling walk-forward adaptations and regime filters.