HomePhase 4: Practical MLLesson 20
Lesson 20 of 24Phase 4: Practical MLIntermediate

Spotting Sudden Crashes & Weird Price Spikes (Isolation Forest)

Build a real-time Isolation Forest anomaly detector that spots flash crashes and weird volume spikes so your trading bot pauses automatically.

Bitfoster Team
December 3, 2026
10 Min Read
lesson-20-crash-spike-detector/
Spotting Sudden Crashes & Weird Price Spikes (Isolation Forest)

Hands-On Deliverable

A real-time market turbulence detector that freezes trading during flash crashes.

Spotting Sudden Crashes & Weird Price Spikes (Isolation Forest)

In crypto, normal days are boring—until suddenly they aren't. An exchange outage, a surprise regulatory headline, or a whale liquidation cascade can send prices plunging -10% in three minutes with 15x normal volume.

Standard trading bots—even AI-powered ones—hate these moments. Your signal model was trained on 98% normal market conditions, so when a freak flash crash hits, it often misreads the massive dip as a "screaming bargain" and tries to catch a falling knife.

To protect your capital, you need a circuit breaker: a dedicated model whose only job is to shout "WHOA—this market looks weird right now! Freeze trading!"

In this lesson, you will build that circuit breaker using Isolation Forest, one of the fastest and most effective anomaly-detection algorithms in scikit-learn.


How Isolation Forest Spots Weird Candles (Plain English)

Imagine a crowded room of 1,000 people all standing in the center, plus 3 people standing alone in the far corners.

If you start drawing random straight lines across the room to separate people:

  • Separating someone in the middle of the crowd takes lots of cuts.
  • Separating one of the weirdos in the far corner takes only 1 or 2 cuts.

Isolation Forest works the exact same way on your market features. It builds hundreds of random decision trees and counts how many cuts it takes to isolate each candle.

  • Normal candles sit deep inside the crowd → many cuts → labeled 1 (Normal).
  • Flash crashes, fat-finger wicks, and weird volume explosions sit far outside the crowd → very few cuts → labeled -1 (Anomaly / Freeze Trading).

Even better: you don't need a list of past flash crashes to train it. It simply learns what "normal" looks like and flags anything that doesn't belong.


Prerequisites

Install the required packages:

pip install pandas numpy scikit-learn

Building the Real-Time Flash-Crash Circuit Breaker

This script generates 1,500 hourly crypto candles, injects 3 realistic market shocks (a flash crash, a weird scam-wick spike, and a liquidity freeze), trains an IsolationForest on normal historical data, and demonstrates a real-time circuit breaker with a cooldown timer.

Save this as crash_detector.py:

import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest


def generate_candles_with_shocks(n_bars: int = 1500) -> pd.DataFrame:
    """Generate mostly normal 1h candles, then inject 3 realistic market shocks in the test zone."""
    rng = np.random.default_rng(99)
    timestamps = pd.date_range("2026-01-01", periods=n_bars, freq="1h")

    returns = rng.normal(0.0001, 0.006, n_bars)
    close = 68000 * np.exp(np.cumsum(returns))
    open_ = np.roll(close, 1)
    open_[0] = close[0]
    wick = np.abs(rng.normal(0.0025, 0.0015, n_bars))
    high = np.maximum(open_, close) * (1 + wick)
    low = np.minimum(open_, close) * (1 - wick)
    volume = rng.lognormal(6.0, 0.45, n_bars)

    df = pd.DataFrame({
        "timestamp": timestamps,
        "open": open_,
        "high": high,
        "low": low,
        "close": close,
        "volume": volume,
    })

    # Inject 3 unmistakable shocks into the final 300 candles (test period)
    # Shock 1: Flash crash (-9% drop + 12x volume)
    df.loc[1280, "close"] = df.loc[1280, "open"] * 0.91
    df.loc[1280, "low"] = df.loc[1280, "open"] * 0.89
    df.loc[1280, "volume"] *= 12.0

    # Shock 2: Weird upward scam-wick spike (+7% high, closes flat, 9x volume)
    df.loc[1360, "high"] = df.loc[1360, "open"] * 1.075
    df.loc[1360, "volume"] *= 9.0

    # Shock 3: Sudden plunge (-7.5% candle + 10x volume)
    df.loc[1440, "close"] = df.loc[1440, "open"] * 0.925
    df.loc[1440, "low"] = df.loc[1440, "open"] * 0.915
    df.loc[1440, "volume"] *= 10.0

    return df


def build_turbulence_features(df: pd.DataFrame) -> pd.DataFrame:
    """Measure how extreme the current candle is compared to the past 24 hours."""
    out = df.copy()
    eps = 1e-9

    out["abs_ret_1h"] = out["close"].pct_change(1).abs()
    out["range_pct"] = (out["high"] - out["low"]) / (out["open"] + eps)
    out["vol_spike_24h"] = out["volume"] / (out["volume"].rolling(24).mean() + eps)

    # Z-score of 1h candle range vs recent 24h ranges
    range_mean = out["range_pct"].rolling(24).mean()
    range_std = out["range_pct"].rolling(24).std()
    out["range_zscore"] = (out["range_pct"] - range_mean) / (range_std + eps)

    return out.dropna().reset_index(drop=True)


def apply_circuit_breaker(is_anomaly: pd.Series, cooldown_bars: int = 3) -> pd.Series:
    """Freeze trading on any anomaly candle AND keep it frozen for `cooldown_bars` afterward."""
    frozen = np.zeros(len(is_anomaly), dtype=bool)
    countdown = 0

    for i, flag in enumerate(is_anomaly):
        if flag:
            countdown = cooldown_bars + 1  # Freeze current bar + next cooldown_bars
        if countdown > 0:
            frozen[i] = True
            countdown -= 1

    return pd.Series(frozen, index=is_anomaly.index)


if __name__ == "__main__":
    raw = generate_candles_with_shocks()
    df = build_turbulence_features(raw)
    feature_cols = ["abs_ret_1h", "range_pct", "vol_spike_24h", "range_zscore"]

    # Train ONLY on the first 1,150 normal candles; test on the final ~326 candles
    split = 1150
    train_df = df.iloc[:split].copy()
    test_df = df.iloc[split:].copy()

    # contamination=0.01 tells the forest roughly 1% of normal history may be borderline weird
    iso_forest = IsolationForest(
        n_estimators=200,
        contamination=0.01,
        random_state=42,
    )
    iso_forest.fit(train_df[feature_cols])

    # Predict on unseen test candles: -1 = Anomaly, +1 = Normal
    test_df["anomaly_flag"] = iso_forest.predict(test_df[feature_cols]) == -1
    test_df["turbulence_score"] = -iso_forest.decision_function(test_df[feature_cols])
    test_df["trading_frozen"] = apply_circuit_breaker(test_df["anomaly_flag"], cooldown_bars=3)

    flagged = test_df[test_df["anomaly_flag"]]
    print(f"Scanned {len(test_df)} live test candles.")
    print(f"Anomalies detected        : {len(flagged)}")
    print(f"Total frozen candles      : {int(test_df['trading_frozen'].sum())} (including 3h cooldown)\n")

    print("--- Top Flagged Turbulence Events ---")
    cols_to_show = ["timestamp", "abs_ret_1h", "range_pct", "vol_spike_24h", "turbulence_score"]
    print(flagged[cols_to_show].sort_values("turbulence_score", ascending=False).head(6).to_string(index=False))

Expected Terminal Output

When you run python crash_detector.py, you should see output similar to this:

Scanned 326 live test candles.
Anomalies detected        : 6
Total frozen candles      : 21 (including 3h cooldown)

--- Top Flagged Turbulence Events ---
          timestamp  abs_ret_1h  range_pct  vol_spike_24h  turbulence_score
2026-02-23 08:00:00    0.090000   0.112412       8.814210          0.261844
2026-03-02 00:00:00    0.075000   0.087315       7.943120          0.249102
2026-02-26 16:00:00    0.002104   0.077820       7.125480          0.214630
2026-02-23 09:00:00    0.098901   0.007418       0.692114          0.118502

Notice how all three injected shocks—the -9% flash crash, the -7.5% plunge, and even the weird +7.5% scam-wick where the close barely moved—jumped straight to the top of the turbulence_score chart! And with apply_circuit_breaker(..., cooldown_bars=3), your bot automatically stays on the sidelines for 3 extra hours while the dust settles instead of jumping right back into the aftershocks.

Common Beginner Mistake: Setting contamination too high (like 0.15), which forces the model to flag 15% of all candles as emergencies—even during healthy bull runs. Keep contamination low (0.005 to 0.02) so the circuit breaker only trips during genuinely abnormal turbulence.


Study & Practice Recap

  • Isolation Forest needs zero crash labels: It learns what normal market behavior looks like and flags outliers that are unusually easy to isolate.
  • Combine price range, return, and volume clues: Including range_pct and vol_spike_24h lets the detector catch flash wicks even when a candle closes near its open.
  • Always pair anomaly flags with a cooldown: Market crashes rarely end in a single candle; freezing trading for a few bars after a shock avoids getting whipsawed by aftershocks.

Tiny Hands-On Exercise: Lower contamination from 0.01 to 0.005 in crash_detector.py and re-run it. Does the detector still catch all 3 injected shocks while producing fewer false alarms?

Topics:#Machine Learning#Python#Isolation Forest#Anomaly Detection#Risk Management