Teaching Your Bot to Recognize Market Moods (K-Means Clustering)
Every trend-following bot has the exact same kryptonite: sideways chop.
When Bitcoin is trending cleanly upward or downward, a simple moving-average crossover prints money. Then the market goes flat for three weeks—bouncing up and down inside a tight box—and that same bot gets chopped to pieces by fakeout after fakeout.
What if your bot could step back, look at the weather outside, and say: "Today is sideways chop—I'm keeping my hands in my pockets"?
In machine learning, this is called market regime detection, and one of the simplest ways to build it is K-Means Clustering. Unlike XGBoost (which needed labeled answers from Lesson 17), K-Means is unsupervised. You don't tell it what "calm" or "stormy" means. Think of K-Means like dumping a basket of mixed fruit onto a table and asking it to sort them into 3 piles by size and color—it automatically sorts market days into calm/choppy, trending, or stormy buckets based on volatility and trend strength.
How K-Means Sorts Market Moods
We give K-Means just three intuitive "weather readings" for every candle:
- Trend Strength (
abs_trend_24h): How far price moved over the last 24 hours (regardless of up or down). - Volatility (
vol_24h): How violently hourly candles are swinging. - Efficiency Ratio (
trend_efficiency): Total 24-hour move divided by the sum of all 1-hour wiggles. A straight-line trend scores near1.0; messy sideways chop scores near0.0.
K-Means groups every historical candle into K = 3 clusters. Because K-Means just names the clusters 0, 1, and 2 randomly, our code automatically inspects each cluster's average volatility and trend strength and gives them human-friendly names:
SIDEWAYS_CHOP→ Pause trend-following entries!CLEAN_TREND→ Green light for trend-following!STORMY_VOLATILE→ Cut position size or switch to defensive mode.
Prerequisites
Install the required packages:
pip install pandas numpy scikit-learn
Building the Market-Mood Detector
Save this complete, copy-and-paste runnable script as market_mood_detector.py:
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
def generate_multi_regime_candles(n_bars: int = 1800) -> pd.DataFrame:
"""Create synthetic 1h crypto candles that cycle through chop, trend, and storm phases."""
rng = np.random.default_rng(2026)
returns = np.zeros(n_bars)
for i in range(n_bars):
phase = (i // 200) % 3
if phase == 0:
# Sideways chop: tiny drift, low-to-medium noisy wiggles
returns[i] = rng.normal(0.0, 0.004)
elif phase == 1:
# Clean trend: steady directional drift with controlled noise
returns[i] = rng.normal(0.0022, 0.0045)
else:
# Stormy volatile: huge whipsaws in both directions
returns[i] = rng.normal(-0.0005, 0.018)
close = 62000 * np.exp(np.cumsum(returns))
timestamps = pd.date_range("2026-01-01", periods=n_bars, freq="1h")
return pd.DataFrame({"timestamp": timestamps, "close": close})
def build_mood_features(df: pd.DataFrame) -> pd.DataFrame:
"""Compute trend strength, volatility, and path efficiency over a 24h window."""
out = df.copy()
ret_1h = out["close"].pct_change(1)
out["abs_trend_24h"] = out["close"].pct_change(24).abs()
out["vol_24h"] = ret_1h.rolling(24).std()
# Efficiency = net distance traveled / total bumpy distance walked
net_move = (out["close"] - out["close"].shift(24)).abs()
total_path = out["close"].diff().abs().rolling(24).sum()
out["trend_efficiency"] = net_move / (total_path + 1e-9)
return out.dropna().reset_index(drop=True)
def label_clusters_by_personality(df: pd.DataFrame, cluster_col: str = "cluster") -> dict[int, str]:
"""Map raw cluster IDs (0, 1, 2) to human-readable market moods."""
summary = df.groupby(cluster_col)[["vol_24h", "trend_efficiency"]].mean()
stormy_id = int(summary["vol_24h"].idxmax())
remaining = summary.drop(index=stormy_id)
trending_id = int(remaining["trend_efficiency"].idxmax())
chop_id = int(remaining.drop(index=trending_id).index[0])
return {
stormy_id: "STORMY_VOLATILE",
trending_id: "CLEAN_TREND",
chop_id: "SIDEWAYS_CHOP",
}
def backtest_trend_bot(df: pd.DataFrame, pause_on_chop: bool = False) -> float:
"""Simple EMA 12/26 crossover bot to test whether pausing during chop helps."""
ema_fast = df["close"].ewm(span=12, adjust=False).mean()
ema_slow = df["close"].ewm(span=26, adjust=False).mean()
signal = (ema_fast > ema_slow).astype(int) # 1 = Long, 0 = Flat
if pause_on_chop:
signal = signal.where(df["mood"] != "SIDEWAYS_CHOP", 0)
# Shift signal by 1 bar so we trade on the NEXT candle (no lookahead!)
position = signal.shift(1).fillna(0)
next_ret = df["close"].pct_change().fillna(0)
# Subtract a realistic 0.05% fee whenever the bot changes position
trades = position.diff().abs().fillna(0)
strat_ret = position * next_ret - trades * 0.0005
total_return = (1 + strat_ret).prod() - 1
return total_return * 100
if __name__ == "__main__":
raw = generate_multi_regime_candles()
df = build_mood_features(raw)
mood_cols = ["abs_trend_24h", "vol_24h", "trend_efficiency"]
# Fit scaler and K-Means ONLY on the first 70% of history to avoid lookahead
split = int(len(df) * 0.70)
train_df = df.iloc[:split].copy()
test_df = df.iloc[split:].copy()
scaler = StandardScaler()
X_train = scaler.fit_transform(train_df[mood_cols])
X_test = scaler.transform(test_df[mood_cols])
kmeans = KMeans(n_clusters=3, n_init=20, random_state=42)
train_df["cluster"] = kmeans.fit_predict(X_train)
test_df["cluster"] = kmeans.predict(X_test)
mood_map = label_clusters_by_personality(train_df)
train_df["mood"] = train_df["cluster"].map(mood_map)
test_df["mood"] = test_df["cluster"].map(mood_map)
print("--- Learned Market Mood Buckets (Training Set Averages) ---")
print(train_df.groupby("mood")[mood_cols].mean().round(4).to_string())
print("\n--- Test Set Mood Distribution ---")
print(test_df["mood"].value_counts().to_string())
ret_always_on = backtest_trend_bot(test_df, pause_on_chop=False)
ret_mood_filtered = backtest_trend_bot(test_df, pause_on_chop=True)
print("\n--- Out-of-Sample Trend Bot Comparison ---")
print(f"Always-On Trend Bot : {ret_always_on:+.2f}%")
print(f"Mood-Filtered (No Chop) : {ret_mood_filtered:+.2f}%")
Expected Terminal Output
When you run python market_mood_detector.py, you should see output similar to this:
--- Learned Market Mood Buckets (Training Set Averages) ---
abs_trend_24h vol_24h trend_efficiency
mood
CLEAN_TREND 0.0564 0.0047 0.4712
SIDEWAYS_CHOP 0.0158 0.0044 0.1325
STORMY_VOLATILE 0.0681 0.0176 0.1840
--- Test Set Mood Distribution ---
mood
STORMY_VOLATILE 194
SIDEWAYS_CHOP 178
CLEAN_TREND 161
--- Out-of-Sample Trend Bot Comparison ---
Always-On Trend Bot : +11.42%
Mood-Filtered (No Chop) : +18.95%
Look at the table of learned averages:
CLEAN_TRENDhas low volatility (0.0047) and a high efficiency ratio (0.4712)—smooth, steady movement.SIDEWAYS_CHOPhas low volatility (0.0044) and a low efficiency ratio (0.1325)—going nowhere fast.STORMY_VOLATILEhas nearly4xthe volatility (0.0176).
By simply pausing the trend-following bot during SIDEWAYS_CHOP, you avoid paying fees on fakeouts and let your strategy focus on real moves.
Common Beginner Mistake: Forgetting to scale features with
StandardScalerbefore running K-Means. K-Means measures straight-line distance between points. If one feature ranges from0to100(like RSI) and another ranges from0.001to0.02(like volatility), K-Means will completely ignore volatility and cluster almost exclusively on RSI! Always scale your inputs first.
Study & Practice Recap
- Unsupervised learning finds hidden structure: K-Means groups candles into natural market moods without needing any hand-labeled training targets.
- Map cluster numbers to real names: Because cluster IDs (
0,1,2) are arbitrary, write a small helper function that inspects each cluster's average volatility and efficiency to label them reliably. - Fit on past data, predict on future data: Fit both
StandardScalerandKMeanson the training window only, then.predict()live candles as they arrive.
Tiny Hands-On Exercise: Modify backtest_trend_bot() so the bot pauses during both SIDEWAYS_CHOP and STORMY_VOLATILE (trading only during CLEAN_TREND), re-run the script, and compare the new out-of-sample return.