""" PatchTST Implementation for Financial Time Series Prediction. Based on: "A Time Series is Worth 64 Words: Long-term Forecasting with Transformers" (ICLR 2023) Paper: https://arxiv.org/abs/2211.14730 Key innovations of PatchTST: 1. Patching: Split time series into patches (like ViT for images) 2. Channel Independence: Each feature processed independently 3. Efficiency: Much faster than vanilla Transformer """ import torch import torch.nn as nn import math class PatchEmbedding(nn.Module): """Convert time series to patches and embed them.""" def __init__(self, patch_len=16, stride=8, d_model=128, in_channels=5): super().__init__() self.patch_len = patch_len self.stride = stride # Linear projection for each patch self.proj = nn.Linear(patch_len * in_channels, d_model) def forward(self, x): """ Args: x: [B, seq_len, in_channels] Returns: patches: [B, num_patches, d_model] """ B, L, C = x.shape # Extract patches with stride num_patches = (L - self.patch_len) // self.stride + 1 patches = [] for i in range(num_patches): start = i * self.stride end = start + self.patch_len patch = x[:, start:end, :] # [B, patch_len, C] patch = patch.reshape(B, -1) # [B, patch_len*C] patches.append(patch) patches = torch.stack(patches, dim=1) # [B, num_patches, patch_len*C] patches = self.proj(patches) # [B, num_patches, d_model] return patches class PatchTST(nn.Module): """ PatchTST model for time series forecasting. Architecture: 1. Patch Embedding: Split series into patches 2. Positional Encoding 3. Transformer Encoder 4. Flatten and Project to output """ def __init__( self, seq_len=96, pred_len=20, in_channels=5, d_model=128, nhead=8, num_layers=3, dim_feedforward=256, dropout=0.1, patch_len=16, stride=8 ): super().__init__() self.seq_len = seq_len self.pred_len = pred_len self.in_channels = in_channels self.d_model = d_model # Patch embedding self.patch_embed = PatchEmbedding(patch_len, stride, d_model, in_channels) # Calculate number of patches self.num_patches = (seq_len - patch_len) // stride + 1 # Positional encoding (learnable) self.pos_embed = nn.Parameter(torch.randn(1, self.num_patches, d_model) * 0.02) # Transformer encoder encoder_layer = nn.TransformerEncoderLayer( d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, dropout=dropout, batch_first=True ) self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers) # Output projection self.head = nn.Sequential( nn.Flatten(), nn.Linear(self.num_patches * d_model, 256), nn.ReLU(), nn.Dropout(dropout), nn.Linear(256, pred_len * in_channels) ) def forward(self, x): """ Args: x: [B, seq_len, in_channels] Returns: pred: [B, pred_len, in_channels] """ B = x.size(0) # Patch embedding x = self.patch_embed(x) # [B, num_patches, d_model] # Add positional encoding x = x + self.pos_embed # Transformer encoding x = self.transformer(x) # [B, num_patches, d_model] # Project to output out = self.head(x) # [B, pred_len * in_channels] out = out.reshape(B, self.pred_len, self.in_channels) return out if __name__ == "__main__": # Test model = PatchTST(seq_len=96, pred_len=20, in_channels=5) x = torch.randn(4, 96, 5) out = model(x) print(f"Input: {x.shape}") print(f"Output: {out.shape}") print(f"Parameters: {sum(p.numel() for p in model.parameters()) / 1e6:.2f}M")