Use when implementing X-Trend or attention-based trading models...
Complete guide to implementing the X-Trend (Cross Attentive Time-Series Trend Network) architecture, combining LSTMs, attention mechanisms, and few-shot learning for trend-following strategies.
Activate this skill when:
Input: Target sequence x[t] + Context set C
ā
[Encoder]
- LSTM for sequences
- Entity embeddings
- Variable Selection Network (VSN)
- Self-attention over context
- Cross-attention: target ā context
ā
[Decoder]
- LSTM with encoder output
- Dual heads: Forecast + Position
- PTP (Predictive distribution To Position)
ā
Output: Trading position z[t] ā [-1, 1]
+ Forecast distribution (μ, Ļ) or quantiles
The model takes 8-dimensional feature vectors combining:
Normalization formula for returns:
r_hat[t-t', t] = r[t-t',t] / (Ļ[t] * sqrt(t'))
IMPORTANT: Use EWMA (exponentially weighted moving average) for volatility calculation:
volatility = prices.pct_change().ewm(span=60).std()
See IMPLEMENTATION.md for full code.
Learns to weight different input features dynamically:
v[j,t] = FFN_j(x[j,t])w[t] = softmax(FFN_weight(x[t]))VSN(x[t]) = Σ w[j,t] * v[j,t]Purpose: Automatically determines which features (returns vs MACD, short-term vs long-term) are most relevant at each time step.
See IMPLEMENTATION.md for PyTorch implementation.
Learn asset-specific representations:
Important: Exclude entity embeddings for zero-shot learning (unseen assets).
See IMPLEMENTATION.md for code.
LSTM-based encoder with skip connections:
Architecture Pattern: x ā VSN ā LSTM ā (+skip) ā LayerNorm ā FFN(+entity) ā (+skip) ā LayerNorm
See IMPLEMENTATION.md for full implementation.
Target sequence attends to context sequences:
Attention(Q, K, V) = softmax(QK^T / ād) V
where:
- Q (queries): From target sequence
- K (keys): From context sequences
- V (values): From context sequences
Multi-head attention (4 heads recommended) allows model to focus on different aspects simultaneously.
See IMPLEMENTATION.md for code.
Context sequences attend to each other before cross-attention:
Flow: Context ā Self-Attention ā Cross-Attention with Target
See IMPLEMENTATION.md for implementation.
Combines all encoder components:
Output: Enriched target representation informed by context patterns.
See IMPLEMENTATION.md for complete code.
Produces trading signals and forecasts:
Inputs: Target features + Encoder output Outputs: Position z[t] ā [-1,1] + Forecast (μ, Ļ) or quantiles
Architecture:
Three Variants:
See IMPLEMENTATION.md for implementation details.
The full X-Trend model combines encoder and decoder:
class XTrendModel(nn.Module):
def __init__(self, input_dim=8, hidden_dim=64, num_assets=50,
forecast_type='gaussian', num_heads=4):
self.encoder = XTrendEncoder(...)
self.decoder = XTrendDecoder(...)
def forward(self, target_features, target_asset_id,
context_features, context_asset_ids, use_ptp=True):
# Encode with attention over context
encoder_output, attention_weights = self.encoder(...)
# Decode to position + forecast
position, forecast = self.decoder(...)
return position, forecast, attention_weights
See IMPLEMENTATION.md for full code.
Sharpe Loss:
L_Sharpe = -sqrt(252) * mean(returns) / std(returns)
Gaussian MLE Loss:
L_MLE = -log p(r | μ, Ļ)
Joint Loss:
L_joint = α * L_forecast + L_Sharpe
Where α = 1.0 for Gaussian, α = 5.0 for Quantile.
{
'input_dim': 8,
'hidden_dim': 64,
'num_assets': 50,
'num_heads': 4,
'context_size': 20,
'seq_len': 126, # 6 months
'learning_rate': 1e-3,
'alpha': 1.0, # Joint loss weight
'dropout': 0.3,
'target_vol': 0.15
}
See TRAINING.md for complete training guide including:
Visualize which context sequences the model attends to:
_, _, attention_weights = model(target, context)
# Shape: (batch, num_heads, seq_len, num_contexts)
# Average across heads and time
avg_attention = attention_weights.mean(dim=(0, 1, 2))
# Top 3 most important contexts
top_k = torch.topk(avg_attention, k=3)
Use for:
See IMPLEMENTATION.md for visualization code.
ā Use LayerNorm + skip connections for stable training ā Entity embeddings for few-shot but exclude for zero-shot ā Multi-head attention (4 heads is good default) ā Joint loss training balances forecasting and trading ā Episodic training mimics test-time usage ā Gradient clipping (max norm = 10.0) ā EWMA for volatility (span=60) not simple rolling std ā Monitor attention weights to ensure meaningful patterns
ā Don't skip warm-up - first 63 predictions are unstable ā Don't use entity embeddings in zero-shot - model hasn't seen asset ā Don't mix training data - use episodes, not mini-batches ā Don't ignore attention interpretation - helps debug ā Don't forget dropout (0.3-0.5) for regularization ā Don't use simple rolling std - use EWMA for volatility
Based on X-Trend paper results (2018-2023):
Few-Shot Learning:
Zero-Shot Learning:
COVID-19 Recovery:
When implementing X-Trend:
financial-time-series - Input features, returns, momentumfew-shot-learning-finance - Episodic training, context constructionchange-point-detection - CPD for context set improvementLast Updated: Based on X-Trend paper (March 2024) Skill Type: Architecture + Implementation Line Count: ~370 (under 500-line rule ā )