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

Preparing Crypto Data for Machine Learning

Turn raw crypto OHLCV candlesticks into 30+ clean, stationary machine learning features without leaking future prices into your model.

Bitfoster Team
December 3, 2026
10 Min Read
lesson-16-ml-feature-engineering/
Preparing Crypto Data for Machine Learning

Hands-On Deliverable

A data-prep pipeline that turns raw candlesticks into 30+ clean ML clues (features).

Preparing Crypto Data for Machine Learning

If you feed raw Bitcoin prices—like $28,400, $64,120, or $91,500—directly into a machine learning model, it will get confused almost immediately. Why? Because a raw price by itself doesn't tell a story. Is $64,000 expensive or cheap? That depends entirely on where the price was yesterday, how fast it moved this week, and whether volume exploded or dried up.

In machine learning, we don't hand the model raw prices and hope for magic. We hand it features—and the easiest way to think about features is that features are clues.

Just like a detective doesn't solve a mystery from a single timestamp, a trading model needs structured clues: How much did price change over the last 3 hours? Is the current candle unusually volatile? Are buyers stepping in with above-average volume?

In this lesson, you will build a clean, reusable Python pipeline that turns basic OHLCV (Open, High, Low, Close, Volume) candlesticks into 30+ machine-learning-ready clues while keeping your dataset free of NaNs, extreme outliers, and future data leaks.


Why Raw Prices Break Machine Learning Models

Imagine training a model on Bitcoin data from 2023 when BTC traded between $20,000 and $40,000. Then, you deploy that model in a year when BTC trades around $95,000. Every single input number is now outside anything the model ever saw during training!

Instead of raw prices, we convert candles into relative, scale-free measurements (often called stationary features):

  • Percentage returns instead of dollar changes (+1.2% means the same thing at $20,000 and $100,000).
  • Ratios to moving averages (e.g., "price is 1.8% above its 20-hour average").
  • Candle anatomy (how big the wicks and body are compared to the total candle range).
  • Relative volume (is this hour's volume 2.5x the 24-hour average?).
  • Time clues (what hour of the day or day of the week it is, since crypto liquidity shifts between Asian, European, and US sessions).

Prerequisites

Install the required libraries in your Python environment:

pip install pandas numpy scikit-learn

Building the 30+ Feature Data-Prep Pipeline

The script below works right out of the box. If you have your own CSV file (btc_1h.csv with timestamp,open,high,low,close,volume), it will load it automatically. If not, it generates 2,000 realistic hourly crypto candlesticks so you can run and inspect the entire pipeline immediately.

Save this as build_features.py:

import os
import numpy as np
import pandas as pd
from sklearn.preprocessing import RobustScaler


def load_or_generate_candles(csv_path: str = "btc_1h.csv", n_bars: int = 2000) -> pd.DataFrame:
    """Load OHLCV candles from CSV, or generate realistic synthetic hourly data."""
    if os.path.exists(csv_path):
        df = pd.read_csv(csv_path, parse_dates=["timestamp"])
        df = df.sort_values("timestamp").reset_index(drop=True)
        print(f"Loaded {len(df)} candles from {csv_path}")
        return df

    print(f"'{csv_path}' not found — generating {n_bars} synthetic 1h crypto candles...")
    rng = np.random.default_rng(42)
    timestamps = pd.date_range("2026-01-01", periods=n_bars, freq="1h")

    # Simulate realistic drifting log-returns with volatility clusters
    vol = np.where((np.arange(n_bars) // 168) % 3 == 0, 0.014, 0.006)
    returns = rng.normal(loc=0.00015, scale=vol)
    close = 65000 * np.exp(np.cumsum(returns))

    open_ = np.roll(close, 1)
    open_[0] = close[0]
    spread = np.abs(rng.normal(0.003, 0.002, n_bars))
    high = np.maximum(open_, close) * (1 + spread)
    low = np.minimum(open_, close) * (1 - spread)
    volume = rng.lognormal(mean=6.5, sigma=0.6, size=n_bars) * (1 + np.abs(returns) * 60)

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


def engineer_features(df: pd.DataFrame) -> pd.DataFrame:
    """Turn raw OHLCV candles into 30+ clean, scale-free ML clues."""
    feat = pd.DataFrame(index=df.index)
    c, o, h, l, v = df["close"], df["open"], df["high"], df["low"], df["volume"]
    eps = 1e-9  # Prevents division by zero

    # 1. Momentum & Return Clues (6 features)
    for window in [1, 3, 6, 12, 24, 72]:
        feat[f"ret_{window}h"] = c.pct_change(window)

    # 2. Moving Average Distance Clues (6 features)
    for window in [7, 14, 21, 50, 100]:
        sma = c.rolling(window).mean()
        feat[f"dist_sma_{window}"] = (c - sma) / (sma + eps)
    ema_12 = c.ewm(span=12, adjust=False).mean()
    ema_26 = c.ewm(span=26, adjust=False).mean()
    feat["macd_ratio"] = (ema_12 - ema_26) / (c + eps)

    # 3. Volatility & Range Clues (6 features)
    log_ret = np.log(c / c.shift(1))
    for window in [6, 12, 24, 72]:
        feat[f"vol_{window}h"] = log_ret.rolling(window).std()

    tr = pd.concat([
        h - l,
        (h - c.shift(1)).abs(),
        (l - c.shift(1)).abs(),
    ], axis=1).max(axis=1)
    feat["atr_14_pct"] = tr.rolling(14).mean() / (c + eps)
    feat["vol_regime_ratio"] = feat["vol_12h"] / (feat["vol_72h"] + eps)

    # 4. Candle Anatomy Clues (5 features)
    candle_range = (h - l) + eps
    feat["body_pct"] = (c - o) / (o + eps)
    feat["body_to_range"] = (c - o).abs() / candle_range
    feat["upper_wick_ratio"] = (h - np.maximum(o, c)) / candle_range
    feat["lower_wick_ratio"] = (np.minimum(o, c) - l) / candle_range
    feat["close_position"] = (c - l) / candle_range  # 0 = closed at low, 1 = closed at high

    # 5. Oscillator Clues: RSI & Bollinger Band Position (4 features)
    delta = c.diff()
    gain = delta.clip(lower=0).rolling(14).mean()
    loss = (-delta.clip(upper=0)).rolling(14).mean()
    rs = gain / (loss + eps)
    feat["rsi_14"] = 100 - (100 / (1 + rs))
    feat["rsi_slope_3h"] = feat["rsi_14"].diff(3)

    bb_mid = c.rolling(20).mean()
    bb_std = c.rolling(20).std()
    feat["bb_zscore_20"] = (c - bb_mid) / (bb_std + eps)
    feat["bb_width_20"] = (4 * bb_std) / (bb_mid + eps)

    # 6. Volume Clues (4 features)
    for window in [6, 24]:
        vol_ma = v.rolling(window).mean()
        feat[f"vol_ratio_{window}h"] = v / (vol_ma + eps)
    feat["vol_change_1h"] = v.pct_change(1).clip(-5, 5)
    feat["dollar_vol_zscore"] = (
        (c * v - (c * v).rolling(24).mean()) / ((c * v).rolling(24).std() + eps)
    )

    # 7. Cyclical Time Clues (4 features)
    hour = df["timestamp"].dt.hour
    dow = df["timestamp"].dt.dayofweek
    feat["hour_sin"] = np.sin(2 * np.pi * hour / 24)
    feat["hour_cos"] = np.cos(2 * np.pi * hour / 24)
    feat["dow_sin"] = np.sin(2 * np.pi * dow / 7)
    feat["dow_cos"] = np.cos(2 * np.pi * dow / 7)

    # Clean up infinities and warm-up NaN rows
    feat = feat.replace([np.inf, -np.inf], np.nan)
    combined = pd.concat([df[["timestamp", "close"]], feat], axis=1).dropna().reset_index(drop=True)
    return combined


def scale_features_safely(df: pd.DataFrame, feature_cols: list[str], split_ratio: float = 0.8):
    """Fit RobustScaler ONLY on the training slice to prevent future data leakage."""
    split_idx = int(len(df) * split_ratio)
    train_df = df.iloc[:split_idx].copy()
    test_df = df.iloc[split_idx:].copy()

    scaler = RobustScaler()
    train_df[feature_cols] = scaler.fit_transform(train_df[feature_cols])
    test_df[feature_cols] = scaler.transform(test_df[feature_cols])
    return train_df, test_df, scaler


if __name__ == "__main__":
    raw_df = load_or_generate_candles()
    dataset = engineer_features(raw_df)

    feature_cols = [c for c in dataset.columns if c not in ("timestamp", "close")]
    train_df, test_df, _ = scale_features_safely(dataset, feature_cols)

    print(f"\nTotal engineered features : {len(feature_cols)}")
    print(f"Clean rows after warm-up  : {len(dataset)} (dropped {len(raw_df) - len(dataset)} warm-up rows)")
    print(f"Train rows / Test rows    : {len(train_df)} / {len(test_df)}")
    print(f"Any NaN values remaining? : {dataset[feature_cols].isna().any().any()}")
    print("\nSample engineered clues (first 3 rows, first 5 features):")
    print(dataset[["timestamp"] + feature_cols[:5]].head(3).to_string(index=False))

    dataset.to_csv("btc_ml_features.csv", index=False)
    print("\nSaved clean dataset to btc_ml_features.csv")

Expected Terminal Output

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

'btc_1h.csv' not found — generating 2000 synthetic 1h crypto candles...

Total engineered features : 35
Clean rows after warm-up  : 1901 (dropped 99 warm-up rows)
Train rows / Test rows    : 1520 / 381
Any NaN values remaining? : False

Sample engineered clues (first 3 rows, first 5 features):
          timestamp    ret_1h    ret_3h    ret_6h   ret_12h   ret_24h
2026-01-05 03:00:00 -0.008614 -0.021409 -0.015923 -0.012441  0.031820
2026-01-05 04:00:00  0.004127 -0.011052 -0.014802 -0.009112  0.028945
2026-01-05 05:00:00 -0.002918 -0.007433 -0.020115 -0.016503  0.024011

Saved clean dataset to btc_ml_features.csv

Notice how we dropped the first 99 rows automatically. That happens because our longest rolling indicator (dist_sma_100) needs 100 candles to calculate its first valid number. Dropping those warm-up rows keeps your dataset spotless.

Common Beginner Mistake: Fitting your scaler (StandardScaler or RobustScaler) on the entire dataset before splitting into train and test sets. If you do that, the average and range of future prices sneak into your training data—a subtle bug called data leakage. Always fit your scaler on train_df only, then call .transform() on test_df.


Study & Practice Recap

  • Features are clues, not raw prices: Convert OHLCV data into relative returns, moving-average distances, candle ratios, volatility, and volume multiples so your model generalizes across different price eras.
  • Crypto has fat tails: Using RobustScaler (which uses medians and interquartile ranges instead of means) stops a single crazy flash-crash candle from squashing all your normal candles into tiny numbers.
  • Zero-leak hygiene starts early: Every feature must look strictly backward in time, and scalers must only learn statistics from the training slice.

Tiny Hands-On Exercise: Add 2 new features to engineer_features()—for example, ret_168h (7-day return) and is_weekend (1 if Saturday/Sunday, else 0)—re-run python build_features.py, and confirm your total engineered feature count jumps from 35 to 37.

Topics:#Machine Learning#Python#Feature Engineering#Pandas#Crypto Trading