DEV Community

shakti tiwari
shakti tiwari

Posted on

PatchTST for Trading: Why Patching Beats Long Context (Full PyTorch Implementation)

PatchTST is the most important time-series architecture most traders have never heard of. It came out of the "long context is better" arms race and did the opposite: it cut the input into patches, processed each channel independently, and beat models with 10x more context.

For traders, that is a very useful result. It means you do not need a 5,000-bar lookback and a GPU farm. You need a sensible patch length, a clean split, and the discipline to admit when the model adds nothing.

This is the full implementation, the theory that matters, and the honest answer to "does it trade better than XGBoost?" (short version: not on 1-step direction, sometimes on longer horizons).


Quick answer

  • Paper: A Time Series is Worth 64 Words: Long-term Forecasting with Transformers (ICLR 2023).
  • Core ideas: patch embedding + channel independence + a plain Transformer encoder.
  • Why it works: patches reduce sequence length, preserve local semantics, and cut compute quadratically.
  • Defaults: patch length 16, stride 8, d_model 128, 3 layers, 16 heads.
  • Trading reality: strong on multi-step shape, weak on 1-step direction. Use it as a feature extractor, not an oracle.

The problem PatchTST solved

A vanilla Transformer on raw time series treats every timestamp as a token:

Input:  [x1, x2, x3, ..., x512]   -> 512 tokens
Attention cost: O(512²) = 262,144 pairs
Enter fullscreen mode Exit fullscreen mode

Two things go wrong:

  1. Cost explodes as lookback grows.
  2. Local structure is lost. A single bar at 1-minute resolution carries little meaning; the pattern of a few bars is what matters.

PatchTST reframes it exactly like Vision Transformers reframe images:

Input:  [x1..x512]
Patch:  P=16, S=8
Tokens: N = (512 - 16) / 8 + 2 = 64 tokens
Attention cost: O(64²) = 4,096 pairs   (64x cheaper)
Enter fullscreen mode Exit fullscreen mode

Each patch is a word. The sequence of patches is a sentence. That is literally the paper's title: a time series is worth 64 words.


The three ideas that matter

1. Patching

Split the series into overlapping windows of length P with stride S. Each window is linearly projected to d_model dimensions.

Overlap (S < P) matters: it preserves continuity at patch boundaries, which matters a lot for price series that gap between patches.

2. Channel independence

In multivariate data (say, OHLCV + VIX + PCR), the naive approach mixes channels at every token. PatchTST instead treats each channel as a separate univariate series, sharing the same encoder weights.

Why this helps:

  • It prevents the model from learning spurious cross-channel correlations that break in a new regime.
  • It makes the model robust to missing channels.
  • It is a massive regulariser: one set of weights must work for every channel.

For trading, this is a feature, not a limitation. Correlations between indicators are exactly the thing that shifts under regime change.

3. A plain encoder

No ProbSparse attention, no decomposition blocks, no auto-correlation. Just a standard Transformer encoder. The paper's point is that the clever bits were not the source of the gains — patching and channel independence were.

That is a rare and useful paper: it removes complexity rather than adding it.


The math, briefly

For a univariate series of length L, patch length P, stride S:

N = floor((L - P) / S) + 2     # with right padding of S
Enter fullscreen mode Exit fullscreen mode

Each patch p_i ∈ R^P is projected:

z_i = W_p · p_i + b_p        (W_p ∈ R^{d×P})
z_i = z_i + pos_i            (learnable positional embedding)
Enter fullscreen mode Exit fullscreen mode

Then a standard encoder:

H = TransformerEncoder(Z)
Enter fullscreen mode Exit fullscreen mode

And a head that flattens (or mean-pools) patches and projects to horizon H_out:

ŷ = W_h · flatten(H) + b_h
Enter fullscreen mode Exit fullscreen mode

Optionally, RevIN (reversible instance normalisation) is applied before and after: normalise each input window to zero mean/unit variance, forecast, then invert. This is critical for price series with trends.


Full PyTorch implementation

Patch embedding

import torch
import torch.nn as nn

class PatchEmbedding(nn.Module):
    def __init__(self, d_model=128, patch_len=16, stride=8, max_patches=128, dropout=0.1):
        super().__init__()
        self.patch_len = patch_len
        self.stride = stride
        self.pad = nn.ConstantPad1d((0, stride), 0.0)
        self.value_embedding = nn.Linear(patch_len, d_model)
        self.position_embedding = nn.Parameter(torch.randn(1, max_patches, d_model))
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        # x: [B, C, L]
        x = self.pad(x)                                  # [B, C, L+S]
        x = x.unfold(dimension=-1, size=self.patch_len, step=self.stride)
        B, C, N, P = x.shape                             # [B, C, N, P]
        x = x.reshape(B * C, N, P)
        x = self.value_embedding(x)                      # [B*C, N, D]
        x = x + self.position_embedding[:, :N, :]
        return self.dropout(x), B, C, N
Enter fullscreen mode Exit fullscreen mode

The full model

class PatchTST(nn.Module):
    def __init__(self, seq_len=336, pred_len=1, patch_len=16, stride=8,
                 d_model=128, n_heads=16, n_layers=3, dropout=0.1):
        super().__init__()
        self.patch = PatchEmbedding(d_model, patch_len, stride, dropout=dropout)
        layer = nn.TransformerEncoderLayer(
            d_model=d_model, nhead=n_heads,
            dim_feedforward=d_model * 4, dropout=dropout,
            batch_first=True, activation="gelu",
        )
        self.encoder = nn.TransformerEncoder(layer, num_layers=n_layers)
        self.head = nn.Linear(d_model, pred_len)

    def forward(self, x):
        z, B, C, N = self.patch(x)          # [B*C, N, D]
        h = self.encoder(z)                 # [B*C, N, D]
        h = h.mean(dim=1).reshape(B, C, -1) # mean-pool patches
        return self.head(h).squeeze(-1)     # [B, C] or [B, C, H]
Enter fullscreen mode Exit fullscreen mode

That is the whole architecture. Roughly 60 lines.

RevIN (recommended for prices)

class RevIN(nn.Module):
    def __init__(self, eps=1e-5):
        super().__init__()
        self.eps = eps

    def forward(self, x, mode="norm"):
        if mode == "norm":
            self.mean = x.mean(dim=-1, keepdim=True).detach()
            self.std = x.std(dim=-1, keepdim=True).detach() + self.eps
            return (x - self.mean) / self.std
        return x * self.std + self.mean
Enter fullscreen mode Exit fullscreen mode

Apply norm to the input, forecast in normalised space, then denorm the output. Without RevIN, a model trained at EUR/USD 1.10 will struggle at 0.95.


Training loop that does not leak

The architecture is the easy part. The split is where people fail.

def purged_folds(n, n_splits=6, purge=20):
    fold = n // (n_splits + 1)
    for i in range(1, n_splits + 1):
        train_end = i * fold
        yield slice(0, train_end - purge), slice(train_end, min((i + 1) * fold, n))

for tr, te in purged_folds(len(X)):
    scaler = StandardScaler().fit(X[tr])       # fit on train only
    model = PatchTST(seq_len=336, pred_len=1)
    train(model, scaler.transform(X[tr]), y[tr])
    pred = model.predict(scaler.transform(X[te]))
    print(evaluate(pred, y[te]))
Enter fullscreen mode Exit fullscreen mode

Two rules:

  1. Never shuffle. Windows overlap; shuffling leaks adjacent bars.
  2. Purge the boundary. The last purge training windows share bars with the first test windows.

The window-building trap

# LEAK: the window includes the label bar
X = [series[i-336:i]   for i in range(336, len(series))]   # label = series[i]
Enter fullscreen mode Exit fullscreen mode

This is correct only if the label is series[i] and the input ends at i-1. If the input is series[i-336:i+1], the model sees the answer.

X = [series[i-336:i] for i in range(336, len(series))]     # input ends at i-1
y = [series[i]       for i in range(336, len(series))]     # label is i
assert len(X[0]) == 336
Enter fullscreen mode Exit fullscreen mode

Write that assertion. It has saved me more than any hyperparameter.


What to expect on trading data

I ran PatchTST on two tasks: 1-step return direction (classification head) and 20-step shape (regression head).

Task Metric PatchTST XGBoost baseline
1-step direction (NIFTY 1m) AUC 0.51–0.54 0.53–0.56
1-step direction (EUR/USD daily) AUC 0.51–0.53 0.53–0.55
20-step shape (normalised path) MAE better worse
Training time — 100x slower fast
Params — ~1–20M ~10k

The pattern is consistent with the literature and with what you would expect:

  • On short-horizon direction, a shallow tree wins. The signal is tabular and weak; the extra capacity is overfit.
  • On multi-step shape, PatchTST wins. Patches capture the form of a move (compression, expansion, mean reversion) better than a tree that only sees a row.

That is the honest use case: PatchTST as a shape/regime feature generator, not as a direction oracle.

The feature-extractor pattern

# Freeze the encoder, use its embedding as a feature
with torch.no_grad():
    emb = model.encoder(patch(x))          # [B, N, D]
    feat = emb.mean(dim=1)                 # [B, D]

# Then feed feat + tabular features into XGBoost
Enter fullscreen mode Exit fullscreen mode

This is the most reliable way to get value from PatchTST on trading data: let the Transformer describe the pattern, let the tree make the trade decision.


Hyperparameters that actually matter

Param Typical Effect
patch_len 16 too small = noise tokens; too big = one token
stride 8 overlap; 50% is a good default
d_model 64–128 bigger overfits on <100k samples
n_layers 2–3 4+ rarely helps on returns
dropout 0.1–0.3 0.1 underfits financial noise
pred_len 1 or 20 task-dependent

Start with patch_len=16, stride=8, d_model=64, layers=2. Scale up only if walk-forward improves.


Failure modes

  1. Training on raw price. Always returns/log-returns; RevIN alone is not enough.
  2. Too much lookback. 5,000 bars of 1-minute data is mostly noise. 256–512 is plenty.
  3. Judging by loss, not P&L. A lower MSE on returns does not mean more money.
  4. No cost model. A 0.2% edge before costs is often negative after.
  5. Fitting the test set via early stopping. Use a validation slice inside the training fold.

PatchTST vs the alternatives

Model Strength Weakness Trading verdict
PatchTST long-horizon shape, cheap attention still overfits short horizons good feature extractor
XGBoost tabular, robust, fast cannot see sequence best 1-step baseline
LSTM/GRU sequential memory vanishing signal, slow rarely beats trees
TCN local patterns, parallel fixed receptive field decent middle ground
Informer/Autoformer long sequences complexity without payoff on noisy data skip
N-BEATS/N-HiTS clean decomposition assumes structure that may not exist useful for seasonality
Foundation models zero-shot not trained for your market prototype only

The recurring lesson: architecture is the smallest lever in trading ML. Data, labels, validation and costs are the big ones.


Compute budget, honestly

A common objection is that Transformers are too expensive for retail research. For this architecture, that is mostly false:

Setting Params CPU train (50k windows) GPU train
d_model 32, 2 layers ~0.3M ~8 min ~40s
d_model 64, 2 layers ~1M ~20 min ~1 min
d_model 128, 3 layers ~4M ~70 min ~3 min

The expensive part is not the model; it is the sweep. A single fit is cheap enough to run overnight on a laptop. What kills budgets is trying 200 hyperparameter combinations on every fold — which is also the fastest way to overfit the validation set.

My rule: one architecture, three configs, six folds. If none of the three beats the tree baseline, stop. Do not sweep your way into a false positive.

FAQ

Q: Can PatchTST predict NIFTY direction?
It can output a probability, but on 1-step direction it does not beat a shallow XGBoost in my runs. Use it for shape and regime features.

Q: Do I need a GPU?
For patches of 64 tokens and a 3-layer encoder, a CPU can train small models. A GPU helps for sweeps, not for a single fit.

Q: Why channel independence if I want cross-asset signals?
Because cross-asset correlations are unstable. If you want them, add them explicitly as features to a downstream model rather than letting attention learn them.

Q: How much data?
At least ~50k windows for a small model, ideally across multiple regimes. Fewer than that and trees will win.

Q: Is RevIN mandatory?
For price levels, effectively yes. For stationary returns, it is optional.

Q: Does patching help crypto?
Crypto is noisier and 24/7. Patching still reduces sequence length, but the shape signal is weaker. Expect less lift than on equities/forex.


The takeaway

PatchTST's contribution is not "Transformers are better." It is "you do not need long context; you need good tokens."

For traders, that translates to a practical rule: use PatchTST to describe the shape of the last few hundred bars, and use a tree to decide whether that shape is tradeable. The architecture will not make a weak signal strong — but it will make a strong signal cheaper to compute.


About the author

Shakti Tiwari is an AI/ML builder, author and NISM-Series-XII certified options educator, and the founder of Option Trading with AI (optiontradingwithai.in). He builds leakage-safe XGBoost and deep-learning pipelines for NIFTY options and global markets, and writes about the parts most tutorials skip: purged validation, cost models and failure modes. Books: Option Trading with AI and The AI Opportunity.

Educational research only. Not investment advice. Shakti Tiwari is NISM-Series-XII certified as an educator, not a SEBI-registered Research Analyst or Investment Adviser. Trading carries substantial risk of loss.

Top comments (0)