Learning Objectives:
-
Master Encoder-Decoder (Seq2Seq) LSTM architectures for multi-horizon forecasting
-
Understand Temporal Convolutional Networks (TCNs) and their advantages
-
Learn Temporal Fusion Transformers (TFTs) with attention mechanisms
-
Understand Patch Time-Series Transformers (PatchTST) for efficient long-sequence processing
-
Apply these architectures to financial time-series prediction problems
Part 1: The Temporal Complexity of Financial Data
1.1: Understanding Financial Time-Series Data
The Nature of Financial Data:
Financial markets generate enormous volumes of sequential data every second. Examples include tick-by-tick asset prices, Limit Order Book (LOB) states, trading volumes, macroeconomic indicators, volatility measures, and interest rate curves.
Unlike ordinary datasets, financial time series possess several challenging characteristics:
Characteristics of Financial Time Series: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Financial Time Series Characteristics β β β β Non-Stationarity: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Statistical properties (mean, variance) change over timeβ β β β β’ Market regimes shift (bull, bear, volatile, calm) β β β β β’ Structural breaks (policy changes, crises) β β β β β’ Challenge: Models must adapt continuously β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Noise: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Random market fluctuations obscure underlying patterns β β β β β’ Signal-to-noise ratio is extremely low β β β β β’ Overfitting risk is high β β β β β’ Challenge: Distinguish signal from noise β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Missing Data: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Data gaps due to holidays, outages, illiquid markets β β β β β’ Irregular sampling intervals β β β β β’ Asynchronous data streams β β β β β’ Challenge: Handle incomplete observations β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Multi-Horizon Dependencies: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Current behavior depends on events minutes, days, or β β β β months earlier β β β β β’ Short-term (momentum) and long-term (trend) effects β β β β β’ Multiple time scales interact β β β β β’ Challenge: Capture dependencies across scales β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Time Series Notation:
A financial time series is represented as:
X = [xβ, xβ, xβ, ..., x_T]
Where:
- xβ β βα΅ is the feature vector at time t
- d is the number of features (price, volume, volatility, etc.)
- T is the sequence length
Target: yβ β β (or βα΅ for multi-output)
- yβ = f(xβ, xβ, ..., xβ) + Ξ΅β
- Ξ΅β is random noise
Forecasting:
Given historical observations up to time T,
predict y_{T+1}, y_{T+2}, ..., y_{T+H}
where H is the forecast horizon.
1.2: The Need for Advanced Architectures
Why LSTMs Have Limitations:
Although Long Short-Term Memory (LSTM) networks significantly improved sequential learning by mitigating the vanishing gradient problem, institutional quantitative research has increasingly adopted more advanced architectures capable of modeling long-range dependencies more efficiently.
LSTM Limitations: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β LSTM Limitations β β β β Sequential Processing: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Cannot parallelize across time steps β β β β β’ Training is slow for long sequences β β β β β’ GPU utilization is inefficient β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Long-Range Dependencies: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Still struggles with very long sequences (>100 steps) β β β β β’ Information bottleneck in hidden state β β β β β’ Limited capacity to retain very old information β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Multi-Horizon Forecasting: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Standard LSTMs predict one step at a time β β β β β’ Error accumulation in autoregressive mode β β β β β’ Training and inference mismatch (teacher forcing) β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Interpretability: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Black-box model β β β β β’ Difficult to understand why predictions were made β β β β β’ Limited regulatory compliance β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The Advanced Architecture Landscape:
Institutional quantitative research has increasingly adopted:
-
Encoder-Decoder (Seq2Seq) LSTM architecturesΒ for multi-horizon forecasting
-
Temporal Convolutional Networks (TCNs)Β for parallel processing
-
Temporal Fusion Transformers (TFTs)Β for interpretability and attention
-
Patch Time-Series Transformers (PatchTST)Β for efficient long-sequence processing
Part 2: Encoder-Decoder Architectures for Multi-Horizon Forecasting
2.1: Sequence-to-Sequence (Seq2Seq) Architecture
Architecture Overview:
A Sequence-to-Sequence (Seq2Seq) model consists of two neural networks:
-
Encoder:Β Processes the historical sequence and compresses it into a latent representation
-
Decoder:Β Uses the latent representation to generate forecasts for future time periods
Encoder-Decoder (Seq2Seq) Architecture:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Encoder-Decoder Architecture β
β β
β Encoder: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β
β β xβ β [LSTM] β hβ ββ β β
β β xβ β [LSTM] β hβ ββ€ β β
β β xβ β [LSTM] β hβ ββ€ β h_T (Context Vector) β β
β β ... ββ€ β β
β β x_T β [LSTM] β h_T ββ β β
β β β β
β β h_T = Encoder(xβ, xβ, ..., x_T) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βΌ β
β Decoder: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β
β β h_T β [LSTM] β Ε·_{T+1} β β
β β β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β h_T, Ε·_{T+1} β [LSTM] β Ε·_{T+2} ββ β
β β β ββ β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β h_T, Ε·_{T+2} β [LSTM] β Ε·_{T+3} ββ β
β β β ββ β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β ... β β
β β h_T, Ε·_{T+H-1} β [LSTM] β Ε·_{T+H} β β
β β β β
β β Ε·_{T+i} = Decoder(h_T, Ε·_{T+i-1}) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The Encoder:
The encoder receives a historical sequence of observations:
xβ, xβ, xβ, ..., x_T Where: - xβ = input feature vector at time t - T = length of the historical sequence The encoder compresses the entire sequence into a latent representation called the context vector. Mathematically: h_T = Encoder(xβ, xβ, ..., x_T) Where: - h_T = latent context vector summarizing all historical information The encoder may consist of stacked LSTM or GRU layers.
The Decoder:
The decoder uses the context vector to generate forecasts for future time periods.
Forecast Horizon: H
Output sequence: Ε·_{T+1}, Ε·_{T+2}, ..., Ε·_{T+H}
Where:
- Ε· = predicted value
- H = forecast horizon
Mathematically:
Ε·_{T+i} = Decoder(h_T, Ε·_{T+i-1})
For i = 1, 2, ..., H
Financial Applications:
Seq2Seq architectures are particularly useful for:
-
Stock price forecasting
-
Volatility prediction
-
Energy demand forecasting
-
Exchange-rate prediction
-
Multi-asset portfolio forecasting
2.2: Teacher Forcing
The Training Challenge:
During training, the decoder needs to learn to generate accurate predictions. However, if the decoder uses its own previous predictions, errors can accumulate and training becomes unstable.
Teacher Forcing Solution:
During training, the decoder receives the true historical value instead of its own prediction.
Teacher Forcing:
Input_{t+1} = y_t
Where:
- y_t = actual observed value
Advantages:
- Faster convergence
- Stable gradient propagation
- Reduced training error
Mathematical Formulation:
Without Teacher Forcing (Autoregressive):
Ε·_{t+1} = Decoder(h_T, Ε·_t)
With Teacher Forcing:
Ε·_{t+1} = Decoder(h_T, y_t)
Where y_t is the actual value, not the predicted value.
2.3: Free Running (Autoregressive Inference)
The Deployment Challenge:
During deployment, future observations are unavailable. The decoder must therefore use its own previous prediction.
Free Running (Autoregressive Inference):
Input_{t+1} = Ε·_t
Where Ε·_t is the model's own prediction.
Issue:
- Small forecasting errors propagate through subsequent predictions
- Error accumulation over long horizons
Error Propagation:
Error Accumulation:
Step 1: Ε·_{T+1} = Decoder(h_T, y_T) + Ξ΅β
Step 2: Ε·_{T+2} = Decoder(h_T, Ε·_{T+1}) + Ξ΅β
Step 3: Ε·_{T+3} = Decoder(h_T, Ε·_{T+2}) + Ξ΅β
...
Each step incorporates the error from the previous step:
Ε·_{T+H} = f(y_T, Ξ΅β, Ξ΅β, ..., Ξ΅_H)
Errors accumulate over the forecast horizon.
2.4: Scheduled Sampling
The Solution:
Scheduled Sampling combines Teacher Forcing and Free Running.
Scheduled Sampling:
During training, the next decoder input is selected probabilistically.
Input_{t+1} = {
y_t with probability p (Teacher Forcing)
Ε·_t with probability (1-p) (Free Running)
}
Where:
- p = probability of using Teacher Forcing
- (1-p) = probability of using Free Running
Scheduling:
- Start with p = 1.0 (full Teacher Forcing)
- Gradually decrease p as training progresses
- End with p = 0.0 (full Free Running)
Mathematically:
p(epoch) = max(0, p_start - (p_start / total_epochs) Γ epoch)
Benefits:
-
Smooth transition from Teacher Forcing to Free Running
-
Reduces mismatch between training and inference
-
Better generalization on unseen data
-
More stable training
2.5: Attention in Encoder-Decoder
Attention Mechanism:
Instead of compressing the entire sequence into a single context vector, attention allows the decoder to focus on different parts of the encoder output at each step.
Attention in Encoder-Decoder:
For each decoding step i:
1. Compute attention scores: e_{ij} = score(s_i, h_j)
2. Softmax: Ξ±_{ij} = exp(e_{ij}) / Ξ£ exp(e_{ik})
3. Context vector: c_i = Ξ£ Ξ±_{ij} h_j
4. Update state: s_i = Decoder(s_{i-1}, c_i, y_{i-1})
Where:
- s_i = decoder state at step i
- h_j = encoder state at step j
- score = attention scoring function
- Ξ± = attention weights
- c_i = attention context vector
Attention Visualization: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Attention Visualization β β β β Decoder Steps β β β β β Step 1: ββββββββββββββββββββββββ β β (Focuses on recent history) β β β β Step 2: ββββββββββββββββββββββββ β β (Focuses on mid-range history) β β β β Step 3: βββββββββββββββββββββββββ β β (Focuses on distant past and recent) β β β β Step 4: ββββββββββββββββββββββββ β β (Focuses on future-relevant patterns) β β β β β = High attention weight β β β = Low attention weight β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Part 3: Temporal Convolutional Networks (TCNs)
3.1: Overview and Advantages
What are TCNs?
Unlike recurrent networks, Temporal Convolutional Networks process the entire sequence simultaneously, making them highly parallelizable.
TCNs combine:
-
Causal convolutions
-
Dilated convolutions
-
Residual connections
TCN Advantages: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β TCN Advantages β β β β Parallel Processing: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Process all time steps simultaneously β β β β β’ Efficient GPU utilization β β β β β’ Faster training and inference β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Long-Range Dependencies: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Dilated convolutions provide exponential receptive fieldβ β β β β’ Captures very long-term dependencies efficiently β β β β β’ No vanishing gradient problem β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Stable Gradients: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ No recurrent connections β β β β β’ Gradients flow directly through the network β β β β β’ No exploding/vanishing gradients β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Interpretability: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Residual connections show skip patterns β β β β β’ Easier to understand important time steps β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
3.2: Causal Convolutions
The Principle:
Financial forecasting must never use future information. For time t, the prediction depends only on xβ, xβββ, xβββ, …, never on xβββ.
Causal Convolution: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Causal Convolution β β β β t=1 t=2 t=3 t=4 t=5 t=6 t=7 β β β β β β β β β β β βΌ βΌ βΌ βΌ βΌ βΌ βΌ β β β β β β β β β β β β β β β β β β β β ββββββΌβββββΌβββββΌβββββΌβββββΌβββββ β β β β β β β β β ββββββΌβββββΌβββββΌβββββ β β β β β β β ββββββΌβββββ β β β β β βΌ β β Output β β β β Each output depends only on current and past inputs β β No future information used β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Mathematical Formulation:
Causal Convolution:
y(t) = Ξ£_{i=0}^{k-1} f(i) Β· x(t-i)
Where:
- y(t) = convolution output
- f(i) = filter coefficients
- x = input sequence
- k = filter size
Properties:
- y(t) depends only on x(t), x(t-1), ..., x(t-k+1)
- Preserves temporal causality
- Prevents look-ahead bias
3.3: Dilated Convolutions
The Concept:
Dilated convolutions expand the receptive field exponentially without increasing the number of parameters.
Dilated Convolution Visualization: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Dilated Convolution Visualization β β β β d=1 (Standard): β β xβ xβ xβ xβ xβ xβ xβ β β β β β β β βββββΌββββ β β β β β y(t) β β β β d=2 (Dilated): β β xβ xβ xβ xβ xβ xβ xβ β β β β β β βββββββββ β β β β β y(t) β β β β d=3 (Dilated): β β xβ xβ xβ xβ xβ xβ xβ β β β β β β βββββββββββββ β β β β β y(t) β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Mathematical Formulation:
Dilated Convolution:
y(t) = Ξ£_{i=0}^{k-1} f(i) Β· x(t - dΒ·i)
Where:
- y(t) = convolution output
- f(i) = filter coefficient
- x = input sequence
- k = filter size
- d = dilation factor
Special Cases:
- d = 1: Standard convolution
- d > 1: Dilated convolution (skips elements)
Receptive Field:
R = 1 + Ξ£_{l=1}^{L} (k_l - 1) Β· d_l
With exponential dilation (d = 2^l):
R = 1 + Ξ£_{l=1}^{L} (k_l - 1) Β· 2^l
Receptive Field Expansion:
Receptive Field Growth: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Receptive Field Growth β β β β Layer 1 (d=1, k=3): β β Receptive Field = 3 β β xβ xβ xβ xβ xβ xβ xβ β β β β β β β βββββΌββββ β β β β β yβ β β β β Layer 2 (d=2, k=3): β β Receptive Field = 7 β β xβ xβ xβ xβ xβ xβ xβ β β β β β β β β β β β βββββΌββββ βββββΌββββ βββββΌββββ β β β β β β β βββββββββββββΌββββββββββββ β β β β β yβ β β β β Layer 3 (d=4, k=3): β β Receptive Field = 15 β β (Exponential growth) β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
3.4: Residual Connections
The Principle:
Residual learning allows information to bypass intermediate layers, improving gradient flow and enabling very deep networks.
Residual Connection: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Residual Connection β β β β Input βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β β βΌ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Convolutional Layer (F) β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β β β β + β β β βββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββ β β β β β βΌ β β Output β β β β y = F(x) + x β β β β Where: β β - F(x) = learned transformation β β - x = original input β β β β Benefits: β β β’ Reduces vanishing gradients β β β’ Stabilizes optimization β β β’ Enables very deep TCNs β β β’ Allows gradients to bypass layers β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Residual TCN Block:
Residual TCN Block: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Residual TCN Block β β β β Input x β β β β β βΌ β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β Dilated Causal Convolution (d=1) β β β β Weight Normalization β β β β Activation (ReLU) β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βΌ β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β Dilated Causal Convolution (d=2) β β β β Weight Normalization β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β β β β β + β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βΌ β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β Activation (ReLU) β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βΌ β β Output y = F(x) + x β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
3.5: TCN for Financial Forecasting
TCN Architecture for Finance:
TCN Architecture:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TCN Architecture for Finance β
β β
β Input: Historical sequence (T steps, D features) β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β xβ, xβ, ..., x_T (prices, volume, volatility, macros) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β
β β Residual TCN Block 1 (d=1) β β
β β Receptive Field: 3 β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β
β β Residual TCN Block 2 (d=2) β β
β β Receptive Field: 7 β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β
β β Residual TCN Block 3 (d=4) β β
β β Receptive Field: 15 β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β
β β Residual TCN Block 4 (d=8) β β
β β Receptive Field: 31 β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β
β β Global Average Pooling β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β
β β Dense Layers for Prediction β β
β β β’ Hidden layer: 128 neurons (ReLU) β β
β β β’ Output layer: H neurons (forecast horizon) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β Output: Ε·_{T+1}, Ε·_{T+2}, ..., Ε·_{T+H} β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Part 4: Attention Mechanisms and Temporal Fusion Transformers (TFT)
4.1: Self-Attention Fundamentals
The Core Concept:
Attention mechanisms allow a model to learn which observations are most important rather than treating every historical observation equally.
Scaled Dot-Product Attention:
Scaled Dot-Product Attention: Attention(Q, K, V) = softmax(QKα΅ / βd_k) Β· V Where: - Q = Query matrix (what we're looking for) - K = Key matrix (what each element contains) - V = Value matrix (actual content) - d_k = dimension of key vectors Interpretation: - Each observation assigns importance weights to every other observation - Large attention scores indicate stronger influence on the prediction - Softmax ensures weights sum to 1 - Scaling by 1/βd_k prevents vanishing gradients
Attention Weights Visualization:
Attention Weights for Financial Time Series: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Attention Weights β β β β Target: Volatility Forecast β β β β Time Step | Attention Weight β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β t-1 (1 day ago) | βββββββββββββββ (0.15) β β t-2 | ββββββββββ (0.10) β β t-5 (1 week ago) | ββββββββββββββββ (0.16) β β t-10 | ββββββ (0.06) β β t-20 (1 month) | βββββββββββ (0.11) β β t-30 | ββββ (0.04) β β t-60 (2 months) | ββββββββββββββββββ (0.18) β β t-90 (3 months) | βββββ (0.05) β β t-180 (6 months) | βββββββββββββ (0.13) β β t-365 (1 year) | βββ (0.03) β β β β Interpretation: β β β’ Recent (1 day) and 1-week horizons are important β β β’ 2-month ago has high weight (regime change) β β β’ 1-year ago has low weight (outdated) β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
4.2: Multi-Head Attention
The Concept:
Instead of learning one attention pattern, multiple attention mechanisms operate simultaneously.
Multi-Head Attention: MultiHead(Q, K, V) = Concat(headβ, headβ, ..., headβ) Β· Wα΄Ό Where: headα΅’ = Attention(QWα΅’^Q, KWα΅’^K, VWα΅’^V) Benefits: - Learns multiple market relationships simultaneously - Captures both short-term and long-term dependencies - Improves forecasting robustness
Financial Heads Example:
Financial Multi-Head Attention: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Financial Multi-Head Attention β β β β Head 1: High-Frequency Order Flow β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Focuses on tick-by-tick price movements β β β β β’ Captures micro-structure patterns β β β β β’ Identifies order flow imbalances β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Head 2: Macroeconomic Yield Curves β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Focuses on interest rate movements β β β β β’ Captures yield curve shifts β β β β β’ Identifies monetary policy impacts β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Head 3: Cross-Asset Correlations β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Focuses on relationships between assets β β β β β’ Captures contagion and spillover effects β β β β β’ Identifies risk-off/risk-on regimes β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Head 4: Volatility Dynamics β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Focuses on volatility clustering β β β β β’ Captures leverage effects β β β β β’ Identifies regime changes in volatility β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Head 5: Sentiment and News β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β’ Focuses on text-based data β β β β β’ Captures sentiment shifts β β β β β’ Identifies event impacts β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
4.3: Variable Selection Networks
The Challenge:
Financial datasets often contain hundreds of variables, including interest rates, order book imbalance, trading volume, inflation, GDP growth, and treasury yields. Not all variables are equally important at all times.
Variable Selection Networks:
Variable Selection Networks learn dynamic feature importance, automatically assigning higher weights to the most informative predictors.
Variable Selection Network: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Variable Selection Network β β β β Input Variables: β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β vβ vβ vβ vβ vβ vβ ... vβ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β β β Variable Weights (Learned) β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β vβ: 0.02 vβ: 0.15 vβ: 0.01 vβ: 0.25 β β β β β β vβ : 0.01 vβ: 0.30 ... vβ: 0.05 β β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β β β Weighted Inputs β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β vβΓ0.02 vβΓ0.15 vβΓ0.01 vβΓ0.25 ... β β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β β β Selected Variables (Top K) β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β vβ (0.30), vβ (0.25), vβ (0.15), ... β β β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β β β Temporal Fusion Transformer β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
4.4: Temporal Fusion Transformer (TFT) Architecture
Complete TFT Architecture:
Temporal Fusion Transformer Architecture:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Temporal Fusion Transformer β
β β
β Static Variables (Time-Invariant): β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Company sector β β
β β β’ Geographic region β β
β β β’ Regulatory environment β β
β β β’ Business model β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β Static Encoder: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Encodes static features into context vectors β β
β β β’ Provides baseline information β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β Time-Varying Variables: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Prices, volumes, volatility β β
β β β’ Macro indicators β β
β β β’ Technical indicators β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β Variable Selection Networks: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Selects most relevant variables β β
β β β’ Learns dynamic feature importance β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β LSTM Encoder: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Processes historical sequence β β
β β β’ Captures sequential dependencies β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β Multi-Head Attention: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Learns long-range dependencies β β
β β β’ Captures cross-asset relationships β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β Decoder + LSTM: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β’ Generates forecasts for future horizons β β
β β β’ Uses attention context to inform predictions β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β Output: Ε·_{T+1}, Ε·_{T+2}, ..., Ε·_{T+H} β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
TFT Advantages:
-
Interpretability:Β Attention weights show which variables and time steps matter most
-
Multi-Horizon:Β Predicts multiple future time steps simultaneously
-
Static Variables:Β Incorporates time-invariant features (sector, region)
-
Variable Selection:Β Automatically selects most relevant features
-
Long-Range Dependencies:Β Captures both short and long-term patterns
Part 5: Patch Time-Series Transformer (PatchTST)
5.1: The Efficiency Problem
Traditional Transformer Limitations:
Traditional transformers process every time step individually. For long financial sequences, this becomes computationally expensive.
Computational Complexity: Standard Transformer: O(TΒ²) PatchTST: O(T/P Γ T/P) Where: - T = sequence length - P = patch size Example: T=512, P=32 Standard: O(512Β²) = 262,144 operations PatchTST: O(16Β²) = 256 operations Reduction: 1,000Γ
5.2: Patching
The Concept:
Instead of individual observations, the model groups consecutive observations into patches.
Patching Visualization: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Patching Visualization β β β β Sequence: β β xβ xβ xβ xβ xβ xβ xβ xβ xβ xββ xββ xββ β β β β Patch 1 (P=4): β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β xβ xβ xβ xβ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Patch 2 (P=4): β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β xβ xβ xβ xβ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Patch 3 (P=4): β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β xβ xββ xββ xββ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Number of Patches: 3 β β Instead of 12 tokens, only 3 patch tokens β β β β Patch Size P = 4 β β Sequence Length T = 12 β β Number of Patches N = T/P = 3 β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Mathematical Formulation:
Patching:
Given sequence xβ, xβ, ..., x_T
Choose patch size P
Number of patches: N = T/P (floor)
Patch i: p_i = [x_{(i-1)P+1}, x_{(i-1)P+2}, ..., x_{iP}]
Each patch is an embedding:
e_i = Linear(p_i) (projection to d_model dimensions)
Input to Transformer: [eβ, eβ, ..., e_N]
(N tokens instead of T tokens)
5.3: Channel Independence
The Concept:
Rather than mixing all variables, PatchTST processes each feature independently before combining the learned representations.
Channel Independence: βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β Channel Independence β β β β Traditional (Channel Mixing): β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β All variables processed together β β β β Variable interactions learned jointly β β β β Risk: Interference between unrelated variables β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β PatchTST (Channel Independence): β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β Each variable processed independently β β β β β β β β Price: [PatchTST for price] β β β β Volume: [PatchTST for volume] β β β β Volatility: [PatchTST for volatility] β β β β ... β β β β β β β β Learned representations combined at the end β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β β β Advantages: β β β’ Less feature interference β β β β’ Better scalability β β β β’ Improved generalization β β β β’ More interpretable β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
5.4: PatchTST Architecture
Complete PatchTST Architecture:
PatchTST Architecture:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PatchTST Architecture β
β β
β Input: Multi-variate time series β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Variable 1: [xβ, xβ, ..., x_T] β β
β β Variable 2: [xβ, xβ, ..., x_T] β β
β β Variable 3: [xβ, xβ, ..., x_T] β β
β β ... β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β For each variable independently: β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β β
β β Patching: β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β Group P consecutive values into patches β β β
β β β Patch size P, stride S β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β β
β β Patch Embedding: β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β Linear projection of each patch β β β
β β β Learnable positional encoding β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β β
β β Transformer Encoder: β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β Multi-Head Self-Attention β β β
β β β Feed-Forward Network β β β
β β β Layer Normalization β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β β
β β Output: Variable-specific representation β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β
β β Combine Variable Representations β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β β β Average pooling across variables β β β
β β β Or concatenation + linear projection β β β
β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββ β
β β Output: Ε·_{T+1}, Ε·_{T+2}, ..., Ε·_{T+H} β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
5.5: PatchTST Implementation
Python Implementation:
import torch import torch.nn as nn import torch.nn.functional as F class PatchTST(nn.Module): def __init__( self, n_variables, # Number of input variables seq_len, # Input sequence length patch_len, # Length of each patch stride, # Stride between patches d_model, # Model dimension n_heads, # Number of attention heads n_layers, # Number of transformer layers d_ff, # Feed-forward dimension output_len, # Forecast horizon dropout=0.1 ): super().__init__() self.n_variables = n_variables self.patch_len = patch_len self.stride = stride self.d_model = d_model # Number of patches self.n_patches = (seq_len - patch_len) // stride + 1 # Patch embedding for each variable self.patch_embed = nn.Linear(patch_len, d_model) # Positional encoding for patches self.pos_encoding = nn.Parameter( torch.randn(1, self.n_patches, d_model) * 0.01 ) # Transformer encoder layers self.encoder_layers = nn.ModuleList([ TransformerEncoderLayer(d_model, n_heads, d_ff, dropout) for _ in range(n_layers) ]) # Output projection self.output_projection = nn.Linear(d_model * n_variables, output_len) self.dropout = nn.Dropout(dropout) self.norm = nn.LayerNorm(d_model) def forward(self, x): # x: (batch, seq_len, n_variables) batch_size = x.shape[0] # Reshape for channel-independent processing # (batch, n_variables, seq_len) x = x.permute(0, 2, 1) # Patching for each variable patch_outputs = [] for var_idx in range(self.n_variables): # Extract variable var_data = x[:, var_idx, :] # (batch, seq_len) # Create patches patches = [] for i in range(self.n_patches): start = i * self.stride end = start + self.patch_len patch = var_data[:, start:end] # (batch, patch_len) patches.append(patch) # Stack patches patches = torch.stack(patches, dim=1) # (batch, n_patches, patch_len) # Embed patches patch_embeds = self.patch_embed(patches) # (batch, n_patches, d_model) # Add positional encoding patch_embeds = patch_embeds + self.pos_encoding # Pass through transformer for layer in self.encoder_layers: patch_embeds = layer(patch_embeds) # Pool over patches var_rep = patch_embeds.mean(dim=1) # (batch, d_model) patch_outputs.append(var_rep) # Combine variables combined = torch.cat(patch_outputs, dim=1) # (batch, d_model * n_variables) # Output projection output = self.output_projection(combined) # (batch, output_len) return output class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, n_heads, d_ff, dropout=0.1): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout) self.feed_forward = nn.Sequential( nn.Linear(d_model, d_ff), nn.ReLU(), nn.Dropout(dropout), nn.Linear(d_ff, d_model) ) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout = nn.Dropout(dropout) def forward(self, x): # Self-attention attn_output, _ = self.self_attn(x, x, x) x = self.norm1(x + self.dropout(attn_output)) # Feed-forward ff_output = self.feed_forward(x) x = self.norm2(x + self.dropout(ff_output)) return x
Summary
Modern deep learning architectures significantly outperform traditional recurrent neural networks for financial forecasting by capturing complex temporal dependencies more efficiently.
Key Concepts Covered:
Encoder-Decoder (Seq2Seq) Models:Β Encode historical observations into a latent context vector and decode future values over multiple forecast horizons, making them suitable for multi-step prediction.
Teacher Forcing and Scheduled Sampling:Β Improve training stability while reducing the mismatch between training and real-world inference.
Temporal Convolutional Networks (TCNs):Β Replace recurrent computations with causal and dilated convolutions, enabling parallel processing and efficient learning of long-term dependencies.
Residual Connections:Β Facilitate the training of deep networks by improving gradient flow and reducing optimization difficulties.
Self-Attention and Temporal Fusion Transformers (TFTs):Β Dynamically learn which historical observations and input variables are most relevant, providing both improved predictive accuracy and model interpretability.
Patch Time-Series Transformers (PatchTST):Β Partition long sequences into patches and process channels independently, reducing computational cost while preserving local temporal structure.
Together, these architectures represent the current state of the art in institutional financial forecasting, enabling quantitative trading systems, risk engines, and portfolio management platforms to model complex market dynamics with greater accuracy, scalability, and interpretability.
Key Terminology Glossary
| Term | Definition |
|---|---|
| Seq2Seq | Sequence-to-Sequence – encoder-decoder architecture |
| Teacher Forcing | Using ground truth as input during training |
| Free Running | Using predicted values as input during inference |
| Scheduled Sampling | Gradually transitioning from teacher forcing to free running |
| TCN | Temporal Convolutional Network – causal dilated convolutions |
| Causal Convolution | Convolution that uses only past information |
| Dilated Convolution | Convolution with gaps for larger receptive field |
| Residual Connection | Skip connection for improved gradient flow |
| Receptive Field | The range of input observations influencing a prediction |
| Self-Attention | Attention mechanism within the same sequence |
| Multi-Head Attention | Multiple parallel attention mechanisms |
| TFT | Temporal Fusion Transformer – interpretable forecasting |
| Variable Selection Network | Dynamic feature importance learning |
| PatchTST | Patch Time-Series Transformer – efficient patching |
| Channel Independence | Processing each variable separately |
| Patch Embedding | Projection of a patch to a vector |
Further Reading
-
Sutskever, I., et al. (2014).Β Sequence to Sequence Learning with Neural Networks.Β NeurIPS.
-
Bai, S., et al. (2018).Β An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling.Β arXiv.
-
Lim, B., et al. (2019).Β Temporal Fusion Transformers for Interpretable Multi-horizon Time Series Forecasting.Β arXiv.
-
Nie, Y., et al. (2023).Β A Time Series is Worth 64 Words: Long-term Forecasting with Transformers.Β ICLR.
-
Vaswani, A., et al. (2017).Β Attention Is All You Need.Β NeurIPS.