Two people can look at the same price chart and name different candlestick patterns. Before testing whether a shape relates to later returns, it helps to have a consistent way to describe and group it. K-Means finds five groups in 2,506 SPY days without labels. The rarest covers 2% of days, while quiet candles make up 54%. The Dilbert strip captures the difficulty of naming shapes by eye.

Dilbert by Scott Adams, February 23, 2015.
The joke rests on subjective visual pattern matching. A hammer has a small body and long lower wick, but those descriptions leave the thresholds unspecified. Two analysts can disagree over the same formation. We use K-Means to assign groups from measured shapes, then test whether the groups predict future returns.
Discovering Patterns with K-Means
Watch K-Means iteratively assign 2,506 daily SPY candlesticks to five clusters. Each frame is one assignment-update cycle; the large crosses are cluster centroids moving toward their final positions:

Let's Build It
Click the badge to run this yourself:
import numpy as np
import yfinance as yf
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
np.random.seed(42)
# Fetch 10 years of daily SPY data (~2,500 bars)
df = yf.Ticker("SPY").history(period="10y", interval="1d")
df = df[['Open', 'High', 'Low', 'Close']].dropna()
# Feature engineering (faithful to the original R code)
df['body'] = df['Close'] - df['Open']
df['upper'] = df['High'] - df['Open']
df['lower'] = df['Low'] - df['Open']
df['ma_10'] = df['Close'].rolling(10).mean()
df['ma_5'] = df['Close'].rolling(5).mean()
df['trend'] = df['ma_10'] - df['ma_5']
df['vol'] = df['Close'].rolling(10).std()
df = df.dropna()
# Standardise and cluster
features = ['body', 'upper', 'lower', 'trend', 'vol']
X = StandardScaler().fit_transform(df[features])
km = KMeans(n_clusters=5, n_init=10, random_state=42)
df['cluster'] = km.fit_predict(X)
Cluster 0 (Quiet Day): n=1354 (54%), body=$-0.13, vol=$2.21
Cluster 1 (Volatile Drift): n= 374 (15%), body=$+0.11, vol=$7.06
Cluster 2 (Surge Rally): n= 55 ( 2%), body=$+7.29, vol=$12.46
Cluster 3 (Sharp Selloff): n= 278 (11%), body=$-5.42, vol=$6.64
Cluster 4 (Steady Bull): n= 445 (18%), body=$+3.16, vol=$4.84

K-Means finds five distinct candle types without any human labelling. Over half the days are "quiet" (small body, low volatility). The rarest cluster, "surge rally" (2%), captures the handful of extraordinary up-days that drive long-term equity returns.
What Just Happened?
Feature Engineering: Making Candles Comparable
The original R code used three price-relative features: Close minus Open, High minus Open, and Low minus Open. These capture the candle's body direction and wick lengths. We add two context features: the 10-day vs 5-day moving average crossover (trend) and the 10-day rolling standard deviation (volatility).
Without the trend and volatility features, a $3 bullish candle during a calm uptrend looks identical to a $3 bullish candle during a crisis recovery. They have the same body, but very different meanings. The five-feature representation captures both the candle's shape and its market context.
Standardisation with StandardScaler is critical. The body is measured in dollars (range: roughly -15 to +15), while volatility is measured in dollar standard deviations (range: 1 to 20). Without scaling, higher-variance features dominate the Euclidean distance and K-Means effectively clusters on volatility alone.
Choosing k: The Elbow Method

The elbow method plots within-cluster sum of squares (WCSS) against k. We look for the "bend" where adding another cluster yields diminishing returns. Here the curve flattens around k=5. For a deeper treatment of K-Means and cluster selection, see our post on K-Means to GMM.
Colour-Coded Chart: Seeing Clusters in Context

Overlaying cluster assignments on the actual price chart reveals structure. Notice how selloffs (red) and surge rallies (green) tend to cluster together during volatile periods, while quiet days (grey) dominate the calm stretches. This is not a coincidence; it reflects the well-known volatility clustering phenomenon in financial markets.
Transition Probabilities: The Next State
The transition matrix shows the probability of moving from one cluster state to another on the next trading day:

Three patterns stand out:
- Persistence. Quiet days are followed by another quiet day 84% of the time. Volatile drift persists at 71%. Markets spend most of their time in a single regime.
- Mean reversion after extremes. After a surge rally, there is a 40% chance of a sharp selloff the next day. After a selloff, there is a 38% chance of a steady bull recovery. Large moves tend to reverse.
- Regime transitions. Surge rallies almost never follow quiet days directly (0%). The market typically passes through volatile drift first, suggesting that volatility expands before directional moves. This echoes the Hidden Markov Model view of markets as switching between regimes.
Going Deeper: Multi-Candle Patterns
Single-candle clustering is useful, but the most famous patterns in technical analysis involve sequences of two, three, or four candles. A "morning star" is a three-candle reversal: small body, then a large bullish candle, then a small body. Can K-Means discover these multi-candle formations automatically?
Building Triplet and Quadruplet Features
We create sliding windows of consecutive candles and engineer features for each window:
def build_window_features(df, window_size):
"""Build feature vectors from sliding windows of candles."""
feats, indices = [], []
for i in range(window_size - 1, len(df)):
window = df.iloc[i - window_size + 1 : i + 1]
row = []
for j, (_, candle) in enumerate(window.iterrows()):
# Per-candle shape (proportional, scale-invariant)
row.extend([candle['body_pct'], candle['upper_pct'],
candle['lower_pct']])
# Inter-candle relationships
if j > 0:
prev = window.iloc[j - 1]
avg_range = (candle['range'] + prev['range']) / 2
gap = (candle['Open'] - prev['Close']) / avg_range
range_ratio = candle['range'] / prev['range']
row.extend([gap, range_ratio])
feats.append(row)
indices.append(df.index[i])
return np.array(feats), indices
For each candle, we use three proportional features: body as a fraction of the range (-1 = full bearish, +1 = full bullish), upper shadow ratio, and lower shadow ratio. Between consecutive candles, we add the gap (overnight jump) and the range ratio (is the next candle larger or smaller?).
A triplet has 3 * 3 + 2 * 2 = 13 features. A quadruplet has 4 * 3 + 3 * 2 = 18 features.
Discovered Triplet Patterns (k=6)

K-Means rediscovers several textbook patterns without ever being taught their names:
- Morning Star (19%): Two small candles bracketing a large bullish candle. Traditional TA teaches this as a bullish reversal signal.
- Evening Star (13%): The mirror image, a large bearish candle between two dojis. Taught as a bearish reversal.
- Three White Soldiers (15%): Three consecutive mildly bullish candles. A continuation pattern.
- Consolidation variants (53%): The majority of triplets are unremarkable, three small candles with no strong directional signal.
The fact that an unsupervised algorithm independently discovers formations that Japanese rice traders named centuries ago is striking. The patterns are real geometric structures in the data. The question is whether they have any predictive power.
Discovered Quadruplet Patterns (k=8)

With four-candle windows, K-Means discovers more nuanced formations:
- Selloff Bounce (9%): A sharp bearish candle on day 2 followed by recovery. This is the "V-reversal" that bottom-pickers look for.
- Accelerating Bull (11%): Increasingly bullish candles culminating in a large green candle on day 4. A "climax buy" pattern.
- Steady Uptrend and Persistent Bull (25%): Multi-day bullish runs differing mainly in wick proportions and pace.
- Consolidation variants (55%): Again, the majority of four-day windows are directionless.
The quadruplet analysis also reveals SPY's well-known bullish bias over the last decade. Almost every cluster has a positive average body, because SPY has been in a structural uptrend. A more neutral instrument like an FX pair would produce a more symmetric set of patterns.
Patterns and Future Returns
This is the question that matters. For each triplet pattern, we compute the mean next-day return:

Two patterns show nominally significant t-statistics: "Three White Soldiers" (t=2.2, +0.135%/day) and a consolidation variant (t=2.4, +0.148%/day). But we tested 14 patterns across triplets and quadruplets. Applying a Bonferroni correction for multiple comparisons, the significance threshold rises to |t| > 2.94. No pattern survives.
The evening star, supposedly a bearish reversal signal, has a positive mean next-day return (+0.044%). The morning star, a bullish signal, underperforms the unconditional baseline. As Dilbert's colleague warned: "Good, because it doesn't work if everyone does it."
The patterns are geometrically real but predictively empty. K-Means discovers genuine structural regularities in how candles form, but those regularities do not contain usable information about future returns that is not already priced in. This is consistent with the weak form of the efficient market hypothesis: past price patterns alone cannot generate excess returns.
Where This Comes From
K-Means clustering and candlestick charting come from entirely separate traditions that we combine here.
K-Means was independently discovered by several researchers. Stuart Lloyd developed the algorithm at Bell Labs in 1957 for pulse-code modulation, though it was not published until 1982. Hugo Steinhaus proposed a similar approach in 1957, and James MacQueen gave the algorithm its name in 1967. The algorithm's simplicity, cluster by nearest centroid, iterate until convergence, makes it one of the most widely used algorithms in data science.
"The main purpose of the present paper is to describe a process for partitioning an N-dimensional population into k sets on the basis of a sample."
MacQueen, J. (1967). Some methods for classification and analysis of multivariate observations. Proceedings of the 5th Berkeley Symposium, 1, 281-297.
Candlestick charting was developed by Japanese rice trader Munehisa Homma in the 18th century. Steve Nison introduced it to Western audiences in his 1991 book Japanese Candlestick Charting Techniques. The traditional named patterns (hammer, doji, morning star, engulfing) were identified by human traders through centuries of visual observation; the manual labelling criteria vary by practitioner, which is exactly the subjectivity problem our K-Means approach addresses.
The combination of unsupervised learning with financial time series is an active research area. Liao (2005) surveyed clustering approaches for time series, noting that feature-based methods (like our candlestick features) tend to outperform raw subsequence matching. More recent work by Tsai & Hsiao (2010) applied K-Means specifically to candlestick patterns for stock prediction, finding modest short-term effects that diminished when transaction costs were included.
Further Reading
- K-Means: Lloyd, S. (1982). Least squares quantization in PCM. IEEE Trans. Information Theory, 28(2), 129-137. The original (belated) publication.
- Candlestick patterns: Nison, S. (1991). Japanese Candlestick Charting Techniques. New York Institute of Finance. The book that popularised candlesticks in Western markets.
- Time series clustering survey: Liao, T.W. (2005). Clustering of time series data: a survey. Pattern Recognition, 38(11), 1857-1874.
- Next algorithm to learn: For a probabilistic take on the same problem, see our post on Hidden Markov Models, which models the unobservable market regime as a latent variable.
Try It Yourself
- Try a different asset. Replace SPY with a cryptocurrency (e.g., BTC-USD) or an FX pair (e.g., GBPUSD=X). Do you discover different archetypes?
- Use hourly data. Fetch
interval="1h"to get intraday candles. Do patterns discovered on hourly bars differ from daily ones? - Add volume. Include trading volume as a sixth feature. Does it split any existing clusters into meaningful sub-groups?
- Compare with manual labels. Implement the traditional "hammer" and "doji" definitions (e.g., body < 20% of range) and cross-tabulate with K-Means clusters. How much do they agree?
Interactive Tools
- Kelly Criterion Calculator: size positions for the patterns you trade
- Drawdown Calculator: analyse drawdowns of a pattern-based strategy
Related Posts
- From K-Means to GMM: Hard vs Soft Clustering: K-Means assigns each candle to exactly one cluster; GMM gives probabilistic memberships.
- Hidden Markov Models: When Clusters Have Memory: HMMs model regime transitions with an explicit temporal structure that K-Means ignores.
- Modern Portfolio Theory from Scratch: Another quantitative finance application: optimising portfolios on the efficient frontier.
- Cointegration and Pairs Trading: A statistical approach to trading that, unlike candlestick patterns, has theoretical justification.
- Changepoint Detection: Finding Regime Shifts: Formal methods for detecting the regime changes that our transition matrix hints at.
- Fourier Transform for Time Series Forecasting: Decomposing the same price series into cyclical components.






