Time-Series & Market Prediction Models

📈 Time-Series, Market AI & Financial Prediction Models

Predicting financial asset prices (stocks, crypto, commodities, or game auction-house economies) requires specialized Sequential Machine Learning Architectures that model temporal dependencies without falling victim to the Non-Stationarity and Lookahead Bias of market data.

This guide outlines the complete pipeline: from feature engineering and normalization to deep sequence architectures (LSTM / GRU / Temporal Fusion Transformers) in PyTorch.


🏛️ The Financial ML Pipeline

+-------------------------------------------------------------+
| 1. Raw Market Data (OHLCV Candles / Order Book Ticks)       |
|    - [Timestamp, Open, High, Low, Close, Volume]            |
+-------------------------------------------------------------+
                              │
                     (Stationary Feature Engineering)
                              ▼
+-------------------------------------------------------------+
| 2. Feature Engineering & Technical Indicators               |
|    - Fractional differentiation, Log Returns, RSI, MACD, ATR|
+-------------------------------------------------------------+
                              │
                     (Sliding Window [Batch, Seq_Len, Dim])
                              ▼
+-------------------------------------------------------------+
| 3. Sequence Model Architecture (PyTorch)                    |
|    - LSTM / GRU / 1D Dilated Conv / Temporal Attention      |
+-------------------------------------------------------------+
                              │
                     (Classification / Regression Output)
                              ▼
+-------------------------------------------------------------+
| 4. Trading Signal / Target Evaluation                       |
|    - Direction classification (Up/Down) or Triple-Barrier   |
+-------------------------------------------------------------+

⚠️ 1. The Cardinal Sins of Financial Machine Learning

Unlike image classification where a cat remains a cat, financial data is notoriously hostile to naive ML:

  1. Non-Stationarity (Raw Prices are Dangerous): Never train a model directly on raw stock prices (e.g. Apple at $150). If the stock later hits $250, the network enters an out-of-distribution regime. Instead, train on Log Returns or Percentage Change:
rt=ln⁡(PtPt−1)
  1. Lookahead Bias (Data Leakage): If you normalize data with standard MinMaxScaler fitted over the entire dataset, future maximums and minimums leak into past training samples. Always use Rolling / Expanding Window Scaling fit only on prior historical timesteps.
  2. Overfitting to Noise: Financial time-series have a very low Signal-to-Noise Ratio (SNR). Deep 50-layer models will memorize noise. Keep architectures small, use heavy dropout (0.2–0.5), and enforce L2 weight decay.

🧱 2. Feature Engineering & Feature Vector Design

A robust feature tensor at time t combines price kinematics with volume dynamics:

Feature Formula / Meaning Purpose
Log Returns (rt) ln⁡(Closet/Closet−1) Stationarized price movement
Log Volume (vt) ln⁡(Volumet+1) Volume magnitude compression
Normalized Range (True Range) (Hight−Lowt)/Closet Intra-bar volatility
Relative Strength Index (RSI) Momentum oscillator [0.0,1.0] Overbought / oversold pressure
MACD Histogram EMA12(P)−EMA26(P)−Signal Trend velocity change

💻 3. Building an LSTM Market Prediction Model in PyTorch

Long Short-Term Memory (LSTM) networks maintain a hidden state vector (ht) and a cell state vector (ct), allowing the network to retain long-range context while filtering out short-term fluctuations.

import torch
import torch.nn as nn

class MarketLSTM(nn.Module):
    def __init__(self, feature_dim: int, hidden_dim: int, num_layers: int, num_classes: int = 3):
        super().__init__()
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers

        # 1. Recurrent LSTM backbone
        self.lstm = nn.LSTM(
            input_size=feature_dim,
            hidden_size=hidden_dim,
            num_layers=num_layers,
            batch_first=True,    # Expected tensor shape: [batch_size, sequence_length, feature_dim]
            dropout=0.3 if num_layers > 1 else 0.0
        )

        # 2. Fully-connected classification head (3 classes: 0=Sell/Down, 1=Hold, 2=Buy/Up)
        self.fc = nn.Sequential(
            nn.Linear(hidden_dim, 64),
            nn.LayerNorm(64),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(64, num_classes)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x shape: [batch_size, sequence_length, feature_dim]
        # lstm_out shape: [batch_size, sequence_length, hidden_dim]
        lstm_out, (hn, cn) = self.lstm(x)
        
        # Take the output of the VERY LAST timestep in the sequence
        last_timestep_output = lstm_out[:, -1, :]
        
        # Output raw logits
        logits = self.fc(last_timestep_output)
        return logits

🎯 4. Labeling Strategies: The Triple-Barrier Method

Naive labeling assigns 1 if price increases tomorrow and 0 if price drops. This ignores real trading mechanics (stop losses and holding durations).

The industry-standard Triple-Barrier Method sets three boundaries around the entry price:

  1. Upper Horizontal Barrier: Profit target (e.g. +2%).
  2. Lower Horizontal Barrier: Stop-loss limit (e.g. −1%).
  3. Vertical Barrier: Maximum holding time limit (e.g. 5 hours or 50 bars).

The label (Y) is determined by which barrier is touched first: