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:
- Non-Stationarity (Raw Prices are Dangerous): Never train a model directly on raw stock prices (e.g. Apple at
). If the stock later hits , the network enters an out-of-distribution regime. Instead, train on Log Returns or Percentage Change:
- Lookahead Bias (Data Leakage): If you normalize data with standard
MinMaxScalerfitted 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. - 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 (
), and enforce weight decay.
🧱 2. Feature Engineering & Feature Vector Design
A robust feature tensor at time
| Feature | Formula / Meaning | Purpose |
|---|---|---|
| Log Returns ( | Stationarized price movement | |
| Log Volume ( | Volume magnitude compression | |
| Normalized Range (True Range) | Intra-bar volatility | |
| Relative Strength Index (RSI) | Momentum oscillator | Overbought / oversold pressure |
| MACD Histogram | Trend velocity change |
💻 3. Building an LSTM Market Prediction Model in PyTorch
Long Short-Term Memory (LSTM) networks maintain a hidden state vector (
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:
- Upper Horizontal Barrier: Profit target (e.g.
). - Lower Horizontal Barrier: Stop-loss limit (e.g.
). - Vertical Barrier: Maximum holding time limit (e.g. 5 hours or 50 bars).
The label (
+1 (Buy): Touched profit target first.-1 (Sell): Touched stop-loss first.0 (Hold / Neutral): Touched vertical time barrier without hitting stops or targets.
🔗 Related Notes
- Machine Learning Fundamentals — Tensors, autograd, and PyTorch training mechanics.
- Reinforcement Learning & Game AI — Training trading agents via RL policy optimization.
- ONNX & Engine Inference (Unreal & Godot) — Running real-time inference in C++ / game engines.
- Machine Learning Hub — Master directory for ML and AI architectures.
- Game Development Hub — Central game development index.