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

Intro to Neural Networks for Price Sequences (LSTM & Transformers)

Build a PyTorch LSTM sequence model for crypto candles, learn how Transformers compare, and benchmark neural networks head-to-head vs LightGBM.

Bitfoster Team
December 3, 2026
10 Min Read
lesson-21-sequence-neural-networks/
Intro to Neural Networks for Price Sequences (LSTM & Transformers)

Hands-On Deliverable

A sequence-based neural network model benchmarked head-to-head against LightGBM.

Intro to Neural Networks for Price Sequences (LSTM & Transformers)

So far in Phase 4, our models looked at one row at a time—a single snapshot of today's clues. Even when we added moving averages, XGBoost and LightGBM still read each candle like a flat spreadsheet row.

Human chart traders don't look at markets like a spreadsheet. You look at a movie strip of the last 24 candles in order: "First price drifted down, then volume dried up, then three higher lows formed in a row..."

That is what sequence neural networks—specifically LSTMs and Transformers—were built to read:

  • LSTM (Long Short-Term Memory): Imagine reading a book one sentence at a time while keeping a small sticky note of the plot in your head. At each new candle, the LSTM decides what to keep on its sticky note and what old noise to erase.
  • Transformer: Imagine spreading all 24 candles out on a desk at once and drawing highlighter lines between the moments that matter most (this is called self-attention). Transformers shine on massive datasets (millions of candles), while compact LSTMs are often easier to train on smaller crypto datasets without overfitting.

But here is the million-dollar question every beginner asks: Are neural networks actually better than LightGBM for crypto candles? Let's stop guessing and run a fair, head-to-head benchmark!


Prerequisites

Install PyTorch alongside our standard ML tools:

pip install torch pandas numpy scikit-learn lightgbm

(This script runs comfortably on any normal laptop CPU in under 15 seconds—no expensive GPU required.)


Building the PyTorch LSTM vs. LightGBM Benchmark

To feed a neural network a sequence, we reshape our data from a 2D table (rows, features) into a 3D stack of sliding windows: (samples, sequence_length, features). For example, each training sample is a mini-chart of the last 24 candles × 5 features.

Save this complete benchmark as benchmark_lstm_vs_lgbm.py:

import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score, precision_score
from lightgbm import LGBMClassifier


def set_seeds(seed: int = 42):
    np.random.seed(seed)
    torch.manual_seed(seed)


def generate_sequence_dataset(n_bars: int = 2500) -> tuple[pd.DataFrame, list[str]]:
    """Generate synthetic 1h crypto candles with mild sequential momentum."""
    rng = np.random.default_rng(42)
    returns = rng.normal(0.0001, 0.008, n_bars)
    for i in range(12, n_bars):
        # Subtle multi-bar pattern so both models have real signal to discover
        returns[i] += 0.16 * returns[i - 4 : i].mean()

    close = 65000 * np.exp(np.cumsum(returns))
    volume = rng.lognormal(6.2, 0.5, n_bars) * (1 + np.abs(returns) * 40)

    df = pd.DataFrame({"close": close, "volume": volume})
    df["ret_1h"] = df["close"].pct_change(1)
    df["ret_6h"] = df["close"].pct_change(6)
    df["vol_12h"] = df["ret_1h"].rolling(12).std()
    df["vol_ratio"] = df["volume"] / df["volume"].rolling(24).mean()
    sma_20 = df["close"].rolling(20).mean()
    df["dist_sma_20"] = (df["close"] - sma_20) / sma_20

    # Target: 1 if 6-hour forward return > +0.5%, else 0
    df["target"] = (df["close"].shift(-6) / df["close"] - 1.0 > 0.005).astype(int)
    df = df.dropna().reset_index(drop=True)

    feature_cols = ["ret_1h", "ret_6h", "vol_12h", "vol_ratio", "dist_sma_20"]
    return df, feature_cols


def make_sliding_windows(X: np.ndarray, y: np.ndarray, seq_len: int = 24):
    """Turn 2D rows into 3D overlapping windows of shape (samples, seq_len, features)."""
    X_seq, y_seq = [], []
    for i in range(seq_len, len(X)):
        X_seq.append(X[i - seq_len : i])
        y_seq.append(y[i])
    return np.array(X_seq, dtype=np.float32), np.array(y_seq, dtype=np.float32)


class CandleLSTM(nn.Module):
    """Compact PyTorch LSTM that reads a 24-candle sequence and outputs a win probability."""

    def __init__(self, n_features: int, hidden_size: int = 32):
        super().__init__()
        self.lstm = nn.LSTM(
            input_size=n_features,
            hidden_size=hidden_size,
            num_layers=1,
            batch_first=True,
        )
        self.dropout = nn.Dropout(0.2)
        self.head = nn.Linear(hidden_size, 1)

    def forward(self, x):
        # lstm_out shape: (batch, seq_len, hidden_size)
        lstm_out, _ = self.lstm(x)
        last_step = lstm_out[:, -1, :]  # Take the summary after reading the final candle
        logits = self.head(self.dropout(last_step)).squeeze(-1)
        return logits


def train_lstm(X_train_seq, y_train_seq, X_test_seq, epochs: int = 12, batch_size: int = 64):
    """Train the PyTorch LSTM and return predicted test probabilities."""
    loader = DataLoader(
        TensorDataset(torch.tensor(X_train_seq), torch.tensor(y_train_seq)),
        batch_size=batch_size,
        shuffle=True,
    )
    model = CandleLSTM(n_features=X_train_seq.shape[2], hidden_size=32)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
    criterion = nn.BCEWithLogitsLoss()

    model.train()
    for _ in range(epochs):
        for xb, yb in loader:
            optimizer.zero_grad()
            loss = criterion(model(xb), yb)
            loss.backward()
            optimizer.step()

    model.eval()
    with torch.no_grad():
        logits = model(torch.tensor(X_test_seq))
        probs = torch.sigmoid(logits).numpy()
    return probs


if __name__ == "__main__":
    set_seeds(42)
    df, feature_cols = generate_sequence_dataset()

    # Chronological 80/20 split with a 6-bar purge gap
    split = int(len(df) * 0.80)
    purge = 6
    seq_len = 24

    train_df = df.iloc[:split]
    test_df = df.iloc[split + purge :]

    # Fit scaler strictly on training data (essential for neural networks!)
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(train_df[feature_cols])
    X_test_scaled = scaler.transform(test_df[feature_cols])
    y_train = train_df["target"].to_numpy()
    y_test = test_df["target"].to_numpy()

    # Align tabular LightGBM targets with the exact same test rows as the LSTM
    X_train_seq, y_train_seq = make_sliding_windows(X_train_scaled, y_train, seq_len=seq_len)
    X_test_seq, y_test_seq = make_sliding_windows(X_test_scaled, y_test, seq_len=seq_len)

    # 1. Benchmark LightGBM (tabular snapshot)
    t0 = time.perf_counter()
    lgbm = LGBMClassifier(
        n_estimators=120, max_depth=3, num_leaves=7, learning_rate=0.05, random_state=42, verbose=-1
    )
    lgbm.fit(X_train_scaled[seq_len:], y_train[seq_len:])
    lgbm_probs = lgbm.predict_proba(X_test_scaled[seq_len:])[:, 1]
    lgbm_time = time.perf_counter() - t0

    # 2. Benchmark PyTorch LSTM (24-candle sequence)
    t1 = time.perf_counter()
    lstm_probs = train_lstm(X_train_seq, y_train_seq, X_test_seq, epochs=12)
    lstm_time = time.perf_counter() - t1

    print("--- Head-to-Head Benchmark (Identical Out-of-Sample Test Set) ---")
    for name, probs, elapsed in [
        ("LightGBM (Tabular)", lgbm_probs, lgbm_time),
        ("PyTorch LSTM (24h)", lstm_probs, lstm_time),
    ]:
        auc = roc_auc_score(y_test_seq, probs)
        preds = (probs >= 0.55).astype(int)
        prec = precision_score(y_test_seq, preds, zero_division=0) * 100
        print(
            f"{name:20s} | ROC-AUC: {auc:.3f} | [email protected]: {prec:5.1f}% "
            f"| Trades: {int(preds.sum()):3d} | Train Time: {elapsed:4.2f}s"
        )

Expected Terminal Output

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

--- Head-to-Head Benchmark (Identical Out-of-Sample Test Set) ---
LightGBM (Tabular)   | ROC-AUC: 0.608 | [email protected]:  54.2% | Trades:  83 | Train Time: 0.14s
PyTorch LSTM (24h)   | ROC-AUC: 0.596 | [email protected]:  52.6% | Trades:  76 | Train Time: 3.42s

Look closely at that result—it is one of the most valuable lessons in practical quantitative trading:

  1. LightGBM often matches or beats deep learning on a few thousand daily/hourly candles, while training 20x faster and requiring far less tuning.
  2. Where do LSTMs and Transformers pull ahead? When you feed them high-frequency order-book sequences, multi-asset streams, or hundreds of thousands of candles where exact step-by-step timing matters more than summary indicators.
  3. Pro tip: You don't even have to pick one! Many real trading desks average the probabilities from LightGBM and a sequence neural network together (an ensemble) to get smoother, more reliable predictions.

Common Beginner Mistake: Feeding unscaled features (like raw prices or volume in millions) into a PyTorch neural network. Unlike tree models, neural networks multiply inputs by weights and push them through smooth curves—huge unscaled numbers cause exploding gradients and flat, useless predictions. Always scale sequence inputs with StandardScaler or RobustScaler fit strictly on the training set.


Study & Practice Recap

  • Sequence models read mini-movies, not single snapshots: LSTMs and Transformers take 3D input windows shaped (samples, sequence_length, features) so they can see how a pattern unfolds bar by bar.
  • Simple beats fancy unless data proves otherwise: Always benchmark any neural network head-to-head against a fast LightGBM baseline on the exact same out-of-sample test slice.
  • Keep neural networks compact for crypto: A 1-layer LSTM with hidden_size=32 and Dropout(0.2) generalizes far better on noisy financial data than a giant 10-layer network.

Tiny Hands-On Exercise: Create a 50/50 ensemble at the bottom of benchmark_lstm_vs_lgbm.py by computing ensemble_probs = 0.5 * lgbm_probs + 0.5 * lstm_probs, print its ROC-AUC and [email protected], and check whether combining both models beats each one individually!

Topics:#Machine Learning#Python#PyTorch#LSTM#Transformers#Deep Learning