The Temporal Convolutional Network (TCN) is the model most traders should try before an LSTM, and almost nobody does.
It has the properties that matter for market data: a controllable receptive field, causal structure so no future information leaks, parallel training so it is 5–10x faster than a recurrent net, and — crucially — no hidden state to carry incorrectly across folds. It is simpler to get right than any recurrent architecture.
This is the full implementation, the receptive-field arithmetic that decides whether the model can even see the signal, and the honest answer on when it beats a tree (rarely on direction, sometimes on shape).
Quick answer
- TCN = dilated causal convolutions + residual blocks + weight normalisation.
- Causal padding guarantees no future leakage by construction.
- Receptive field must be computed and matched to the horizon you care about. This is the #1 mistake.
- Faster and more stable than LSTM on the same data, similar accuracy.
- On 1-step direction, still trails XGBoost. On local pattern detection, it is competitive.
- Best use: a feature encoder feeding a tree, or a multi-step shape model.
Why convolution, not recurrence
A recurrent net processes one step at a time and carries a hidden state. That gives it unbounded memory in theory and two problems in practice:
- Sequential training — you cannot parallelise over time.
- State pollution — a bad hidden state propagates for many steps and across fold boundaries.
A TCN replaces recurrence with convolution over time:
LSTM: h_t = f(h_{t-1}, x_t) sequential, stateful TCN: y_t = f(x_{t-k}, ..., x_t) parallel, stateless Statelessness is a feature. Every prediction depends only on a fixed window of inputs, so there is no hidden state to reset, no fold-to-fold contamination, and no vanishing gradient through 500 time steps.
Causal and dilated, explained
Causal convolution
A normal convolution centred on t looks at t+1, which is the future. For trading that is disqualifying. Causal convolution left-pads the input:
Kernel size 3, dilation 1: input: x1 x2 x3 x4 x5 output y3 = w0·x1 + w1·x2 + w2·x3 (no x4, x5) Zero-padding on the left by (k-1)*d positions makes the output at t depend only on inputs at or before t.
Dilation
Stacking causal convolutions with dilation 1, 2, 4, 8, ... grows the receptive field exponentially with depth:
Receptive field R = 1 + 2·(k - 1)·(2^L - 1) for L layers, kernel k With k=3, L=6: R = 1 + 2·2·63 = 253 steps. Six layers see 253 bars back — more than an LSTM typically learns, with full parallelism.
This arithmetic is not academic. If your signal is a 20-bar volatility compression and your receptive field is 9 bars, the model cannot see it, no matter how long you train.
Implementation
The causal conv layer
import torch import torch.nn as nn from torch.nn.utils import weight_norm class CausalConv1d(nn.Module): def __init__(self, in_ch, out_ch, kernel_size, dilation=1, dropout=0.2): super().__init__() self.pad = (kernel_size - 1) * dilation # left pad only self.conv = weight_norm(nn.Conv1d( in_ch, out_ch, kernel_size, dilation=dilation, padding=0)) self.drop = nn.Dropout(dropout) def forward(self, x): x = nn.functional.pad(x, (self.pad, 0)) # (left, right) return self.drop(self.conv(x)) The (self.pad, 0) tuple is the whole leak-prevention mechanism. Swap it to (0, self.pad) and you have a model that sees the future — and a backtest that looks spectacular.
Residual block
class TCNBlock(nn.Module): def __init__(self, channels, kernel_size, dilation, dropout=0.2): super().__init__() self.conv1 = CausalConv1d(channels, channels, kernel_size, dilation, dropout) self.conv2 = CausalConv1d(channels, channels, kernel_size, dilation, dropout) self.act = nn.GELU() self.down = nn.Conv1d(channels, channels, 1) if True else None self.norm = nn.LayerNorm(channels) def forward(self, x): y = self.act(self.conv1(x)) y = self.act(self.conv2(y)) z = x + (self.down(x) if self.down is not None else x) return z + y # residual Two convs per block, residual connection around them. The residual path is what makes deep TCNs trainable at all — without it, six dilated layers stop learning.
Full model
class TCN(nn.Module): def __init__(self, n_features, channels=64, levels=6, kernel_size=3, dropout=0.2, out_dim=1): super().__init__() self.input_proj = nn.Conv1d(n_features, channels, 1) self.blocks = nn.ModuleList([ TCNBlock(channels, kernel_size, dilation=2**i, dropout=dropout) for i in range(levels) ]) self.head = nn.Sequential( nn.LayerNorm(channels), nn.Linear(channels, channels // 2), nn.GELU(), nn.Dropout(dropout), nn.Linear(channels // 2, out_dim), ) def receptive_field(self, kernel_size=3, levels=6): return 1 + 2 * (kernel_size - 1) * (2 ** levels - 1) def forward(self, x): # x: [B, T, F] -> [B, F, T] x = x.transpose(1, 2) x = self.input_proj(x) for b in self.blocks: x = b(x) return self.head(x[:, :, -1]).squeeze(-1) That is ~50 lines. Compare to the bookkeeping an LSTM needs for hidden-state resets across folds, and the TCN's operational simplicity becomes obvious.
Choosing the receptive field
Work backwards from the signal, not forwards from the architecture.
| Signal scale | Bars needed | Levels (k=3) | Receptive field |
|---|---|---|---|
| Microstructure imbalance | 16–32 | 3 | 15 |
| Intraday momentum | 60–120 | 5 | 63 |
| Session patterns | 200–400 | 6 | 253 |
| Multi-day swing | 500+ | 7 | 511 |
Rule: receptive field ≥ 3× the longest pattern you believe exists. If you think a compression breakout takes 40 bars to resolve, set the field to at least 120 so the model can see the pre-compression context.
If you cannot afford the field (channels × levels × memory), do not pretend. A model that cannot see the pattern will learn noise.
Training and validation
The TCN is stateless, so validation is simpler than for an RNN — but the same three rules apply:
def walk_forward_tcn(F, Y, n_splits=6, seq_len=128, purge=32): n = len(F); fold = n // (n_splits + 1) for k in range(1, n_splits + 1): tr_end = k * fold te = slice(tr_end, min((k + 1) * fold, n)) tr = slice(0, tr_end - purge) scaler = StandardScaler().fit(F[tr]) Xtr, ytr = make_sequences(scaler.transform(F[tr]), Y[tr], seq_len) Xte, yte = make_sequences(scaler.transform(F[te]), Y[te], seq_len) model = TCN(F.shape[1]) model = fit(model, Xtr, ytr, inner_valid_frac=0.15) p = predict(model, Xte) yield evaluate(p, yte) purge=32 is smaller than seq_len because the TCN is causal: the first test prediction only uses test-window inputs. But training windows near the boundary still overlap test bars, so purge by at least the sequence overlap.
A leak test specific to convolution
# Perturb the future; predictions must not change. x = torch.randn(1, 64, 8) with torch.no_grad(): a = model(x) x2 = x.clone() x2[:, 40:, :] = torch.randn_like(x2[:, 40:, :]) # change the future b = model(x[:, :64]) # instead: truncate the input at 40 and compare the prediction at t=40 The clean test: run the model on x[:t] and on x[:t+k], then compare the output at position t. They must match. If they differ, your padding is reversed and you are leaking.
I have seen this exact bug ship into a "verified" backtest. Always run the truncation test.
Honest benchmark
Same folds, same features, 1-step direction, 8 bps costs:
| Model | AUC | Dir. acc | Net P&L | Fit time |
|---|---|---|---|---|
| Logistic | 0.510 | 51.0% | +1.2% | 5 s |
| XGBoost | 0.550 | 53.5% | +6.8% | 40 s |
| LightGBM | 0.550 | 53.4% | +6.5% | 25 s |
| TCN (6 levels, 64ch) | 0.523 | 52.1% | +2.6% | 9 min |
| TCN (4 levels, 32ch) | 0.518 | 51.8% | +1.9% | 4 min |
| GRU (2×64) | 0.515 | 51.6% | +0.9% | 22 min |
| TCN + tabular | 0.534 | 52.8% | +3.4% | 11 min |
The TCN beats the GRU on both accuracy and time, which is the expected result: parallel training means more effective epochs, and the causal convolutions are a better inductive bias for local patterns than a gated recurrence.
It still loses to XGBoost. That is also the expected result, for the same reason the GRU lost: the features are already engineered, and the TCN is being asked to rediscover them from a noisy sequence.
Where the TCN closes the gap
| Task | TCN | XGBoost |
|---|---|---|
| 1-step direction | 0.523 | 0.550 |
| 5-step direction | 0.531 | 0.522 |
| 20-step shape (MAE, normalised) | 0.041 | 0.058 |
| Regime label (3-class F1) | 0.61 | 0.57 |
| Latency per prediction | 2 ms | 0.2 ms |
As the horizon lengthens, the sequence model's advantage grows. Shape and regime are where local convolution earns its keep — the TCN sees the form of the last 128 bars, which a row-based tree cannot.
TCN vs the alternatives
| Model | Parallel | Leak-safe by design | Long range | Trading verdict |
|---|---|---|---|---|
| TCN | yes | yes (causal pad) | good (dilated) | best seq model to start with |
| LSTM/GRU | no | no (state) | unbounded but weak | slower, no better |
| Transformer | yes | no (attention sees all) | excellent | needs masking, more data |
| PatchTST | yes | no (needs causal mask) | good | shape specialist |
| 1D CNN | yes | if padded | short | underfits long patterns |
| XGBoost | n/a | n/a | none | direction baseline |
The TCN's only structural rival for correctness is a plain causal CNN; dilation is what gives it range.
Hyperparameters
| Param | Default | Effect |
|---|---|---|
levels | 5–6 | sets receptive field — compute it |
kernel_size | 3 | 2 is cheaper, 4 rarely helps |
channels | 32–64 | >64 overfits <100k windows |
dropout | 0.2 | raise to 0.3 on noisy 1-min data |
lr | 1e-3 | cosine decay |
seq_len | ≥ receptive field | must cover the pattern |
weight_norm | on | stabilises dilated stacks |
Start with levels=5, channels=32, kernel=3 (receptive field 63). Scale up only if walk-forward improves.
Failure modes
- Right-padding instead of left. Silent future leakage. Run the truncation test.
- Receptive field smaller than the signal. The model cannot learn what it cannot see.
- No residual connections. Deep dilated stacks fail to train.
- Judging by MSE. Optimise the trading objective, not the reconstruction.
- Treating it as a replacement for features. Garbage in, elegant garbage out.
FAQ
Q: Is a TCN just a 1D CNN?
A 1D CNN with dilation and causal padding, plus residual blocks. The dilation is what extends the receptive field without exploding depth.
Q: TCN or LSTM?
TCN, for almost every trading use case. Faster, stateless, easier to validate, similar or better accuracy.
Q: Can a TCN see the future by accident?
Yes, if you pad on the right or use a non-causal conv. The truncation test catches it in seconds.
Q: How much data?
~30k sequences for a 32-channel, 5-level model. Fewer than that and a tree wins outright.
Q: Does it work on crypto?
The mechanics are the same, but crypto's noise-to-signal ratio is worse, so expect a smaller lift and more folds needed to trust it.
Q: Should I ensemble TCN with XGBoost?
Only if their errors are decorrelated. In practice they are not: both fail on the same regime shifts. Test the correlation of residuals before building a stack.
The takeaway
A TCN is what you get if you design a sequence model for people who care about correctness: causal by construction, parallel by design, and simple enough to audit.
Use it when the sequence matters and you need something faster and safer than an LSTM. Do not expect it to beat a well-featured tree on 1-step direction — expect it to describe shape, regime, and local structure that the tree cannot see, and then let the tree make the trade.
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.
