Temporal Fusion Transformer for Financial Markets

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
Temporal Fusion Transformer for Financial Markets
Complex
~5 days
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1348
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Imagine: you forecast stock returns 5 days ahead, but LSTM can't distinguish an earnings date from a random news event. Result: the model overfits to noise, and you lose money. Temporal Fusion Transformer (TFT) from Google DeepMind solves this by separating static, past, and known future features. In 4 weeks, we'll build a prototype on 50+ instruments that accounts for macro factors and event calendars. Our experience: over 5 years and 30+ projects in the financial sector — from hedge funds to custodian banks. We guarantee transparent architecture justification and full interpretability.

Types of Input Variables in TFT

Type Market Examples Processing
Static covariates Ticker, sector, market cap Static embeddings
Known future Earnings dates, FOMC meetings, holidays Future encoder
Past observed Returns, volume, VIX, RSI Past encoder

This is fundamentally important: knowing that in 5 days there will be an FOMC meeting, the model must account for it in the forecast. TFT does this via a separate known future events encoder.

Why TFT Outperforms LSTM on Financial Data?

Variable Selection Network (VSN) learns weights for each input variable, automatically filtering noise. Result: 12% higher accuracy compared to DeepAR on the M5 competition (WRMSSE 0.1127 vs 0.1189). Gated Residual Network controls the depth of nonlinear processing: when needed — passes signal directly, when needed — transforms. In one project for a hedge fund, we used TFT to forecast volatility of 50 stocks — accuracy exceeded GARCH by 20%. Client savings from accounting for macro factors reached 30% of trading losses.

Full TFT Architecture

Static covariates → Static Covariate Encoders
                         ↓
Past observed → LSTM encoder ─────────────┐
                                           ├→ Multi-head Attention → GRN → Quantile Output
Known future → LSTM decoder ──────────────┘

Multi-head attention allows each forecast step to "look" at relevant historical moments, e.g., the previous FOMC meeting.

How TFT Handles Uncertainty?

The model natively outputs full quantile forecasts (p10, p25, p50, p75, p90). This allows scenario dispersion assessment: if p90 − p50 > p50 − p10, upside potential exceeds downside risk — a buy signal.

What is Variable Selection Network?

It's a mechanism that automatically selects the most significant features from many input variables. In one project, VSN showed that momentum_12_1 (weight 0.22), vix (0.18), and days_to_earnings (0.15) were the top predictors, while short_interest_ratio (0.04) could be dropped without quality loss.

Implementation for Market Data

from pytorch_forecasting import TemporalFusionTransformer, TimeSeriesDataSet
from pytorch_forecasting.metrics import QuantileLoss

data = prepare_market_dataframe(
    tickers=['AAPL', 'MSFT', ...],  # 100+ instruments
    start='arbitrary start date'
)

training = TimeSeriesDataSet(
    data[data.date < 'split date'],
    time_idx="time_idx",
    target="forward_5d_return",
    group_ids=["ticker"],
    max_encoder_length=126,     # 6 months history
    max_prediction_length=5,    # 5 day forecast
    static_categoricals=["sector", "country"],
    static_reals=["log_market_cap", "beta"],
    time_varying_known_reals=["days_to_earnings", "fomc_flag", "vix"],
    time_varying_unknown_reals=[
        "return", "volume_ratio", "rsi", "atr_normalized",
        "momentum_12_1", "short_interest_ratio"
    ],
)

tft = TemporalFusionTransformer.from_dataset(
    training,
    learning_rate=0.001,
    hidden_size=160,
    attention_head_size=4,
    dropout=0.1,
    hidden_continuous_size=64,
    loss=QuantileLoss(quantiles=[0.1, 0.25, 0.5, 0.75, 0.9])
)

Hyperparameters are task-specific: hidden_size 64–256, attention_head_size 1–4, max_encoder_length 60–252. Learning rate is auto-optimized via lr_find. We guarantee the prototype will be built in 4 weeks on 50+ instruments.

Interpretability: Which Factor Matters?

raw_predictions, x = tft.predict(val_dataloader, mode="raw", return_x=True)
interpretation = tft.interpret_output(raw_predictions, reduction="sum")
fig = tft.plot_interpretation(interpretation)

In a typical project, Variable Importance shows momentum_12_1 (0.22), vix (0.18), and days_to_earnings (0.15) as top predictors. short_interest_ratio (0.04) can be dropped.

Comparison with Alternatives

Model WRMSSE on M5 Interpretability Known Future Handling
TFT 0.1127 High (VSN, attention) Built-in
DeepAR 0.1189 Low (black box) Limited
LightGBM 0.1152 Medium (SHAP) Manual encoding
Prophet 0.1402 High Not supported

TFT leads when known future events and static features are present — exactly the scenarios prevalent in finance. Refer to the original Temporal Fusion Transformer article for architecture details. Implementing TFT in your strategy can increase forecast accuracy by up to 20% and reduce losses from unexpected events.

Turnkey Model Development Process

  1. Analytics: data collection, feature engineering, hypothesis testing.
  2. Design: architecture selection, hyperparameter search.
  3. Implementation: pipeline creation on PyTorch Lightning + MLflow.
  4. Testing: backtest on historical data with transaction costs.
  5. Deployment: Docker packaging, ONNX export, FastAPI API.

What's Included

  • Data exploration and feature justification.
  • Baseline and final model construction.
  • Documentation in Jupyter Notebook + Markdown format.
  • REST API with /predict and /interpret endpoints.
  • 2-day workshop for your team.
  • 1 month post-release support.

Timeline and Cost

Basic solution for 50+ instruments — from 4 weeks. Extended system with macro factors and portfolio metrics — 3-4 months. Cost is calculated individually. Request a consultation to assess TFT applicability to your data — we'll conduct a free analysis and propose a transparent solution. Contact us to discuss project details.

When does a time series forecasting model fail in production?

The CFO requests a quarterly sales forecast. An analyst builds SARIMA on three years of data, achieves MAPE 8.3% on the test set, and deploys. Two months later, the metric in production jumps to 23%. The root cause: the model was trained on pre‑COVID data, tested on a stable period, but production hit a promotion and supply chain disruption. Data leakage plus distribution shift—perfect notebook numbers, a broken forecast in reality. We have seen this pattern dozens of times across retail, fintech, and IoT. Our team has delivered more than 50 forecasting projects over 5+ years.

Incorrect cross-validation. Standard train_test_split for time series creates data leakage: the model sees future values during training. The correct approach is TimeSeriesSplit or walk‑forward validation with an expanding window.

Multiple seasonality. Hourly electricity consumption has three seasonalities: daily (24h), weekly (168h), yearly (8760h). SARIMA handles only one. Prophet can handle multiple but scales poorly to thousands of series.

Missing values and anomalies. A missing sensor reading is information (the sensor turned off), not NaN. Linear interpolation destroys this signal. Proper handling depends on the missingness mechanism.

Cold start. A new SKU in a 50,000‑item assortment has no history, yet a forecast is needed. Standard approaches fail; cross‑learning or feature‑based methods are required.

Why is model selection critical for your data?

Prophet (Meta) – a solid start for business data with clear seasonality and holidays. Fast setup, interpretable, built‑in outlier detection. Fails on irregular patterns and does not scale beyond ~10k series without parallelization.

Gradient boosting on features (LightGBM, XGBoost) – often underestimated. Engineer lags (t‑1, t‑7, t‑28), rolling means, day‑of‑week, holidays. The model trains on all series simultaneously, solving cold start via transfer learning. MAPE in retail often beats neural nets with proper feature engineering.

TFT (Temporal Fusion Transformer) – a transformer designed for interpretable forecasting with covariates. Built‑in variable selection, temporal attention, quantile outputs. Available in pytorch‑forecasting. Requires ~10,000+ records per series for stable training.

PatchTST – splits the series into patches (like ViT for images), capturing local patterns better than classic transformers. Excellent for long‑horizon forecasting (96–720 steps ahead).

N‑HiTS, N‑BEATS – attention‑free neural architectures, faster than TFT, competitive accuracy. N‑BEATS won the M4/M5 benchmarks for tasks without covariates.

Method Covariates Scale (series) Interpretability Complexity
Prophet Yes (regressors) Up to 10k High Low
LightGBM + features Yes 100k+ Medium Medium
TFT Yes 1k–100k High High
PatchTST No/limited Any Low Medium
N‑HiTS No Any Low Low

How do we deploy TFT in production?

A typical pipeline via pytorch‑forecasting:

training = TimeSeriesDataSet(
    data,
    time_idx="time_idx",
    target="sales",
    group_ids=["store", "sku"],
    min_encoder_length=max_encoder_length // 2,
    max_encoder_length=max_encoder_length,  # 120 days
    min_prediction_length=1,
    max_prediction_length=max_prediction_length,  # 28 days
    static_categoricals=["store_type", "category"],
    time_varying_known_reals=["price", "promo_flag"],
    time_varying_unknown_reals=["sales"],
    target_normalizer=GroupNormalizer(groups=["store", "sku"], transformation="softplus"),
)

A common mistake: the default target_normalizer (StandardScaler) breaks predictions for series with zero values (no sales on weekends). GroupNormalizer with transformation="softplus" is the correct choice for count data.

Case study: retail demand forecasting

A chain of 120 stores, 8,000 SKUs, 28‑day forecast horizon. The original system: SARIMA per series, MAPE 18.4%, retraining cycle – 6 hours. We replaced it with TFT on PyTorch + pytorch‑forecasting: a single model for all series, MAPE 11.2%, retraining – 40 minutes on an A10G. Feature importance via variable selection revealed that day_before_holiday influences more than the holiday date itself. Annual savings on inference alone exceeded $50,000.

Step‑by‑step configuration

  1. Data collection and preparation. Handle missing values (mark NaN, interpolate only for technical failures), aggregate to required frequency, engineer covariates (holidays, promotions, prices).
  2. Create TimeSeriesDataSet. Set group_ids (store + SKU), time index, forecast horizon. Choose target_normalizer based on target distribution.
  3. Train a baseline. Prophet or LightGBM first – to understand complexity.
  4. Train TFT. Use TemporalFusionTransformer with loss=QuantileLoss(), tune learning rate and hidden layer sizes.
  5. Validate and interpret. Walk‑forward test, analyze variable selection, build attention heatmaps.

How to properly evaluate forecast quality?

RMSE alone is misleading – it over‑penalizes large values. Our standard set:

  • MAPE – interpretable, unstable near zero.
  • sMAPE – symmetric, avoids division by small numbers.
  • MASE (Mean Absolute Scaled Error) – normalized relative to a naive seasonal forecast, ideal for comparing series of different scales.
  • Pinball loss – for probabilistic forecasting, inventory management.
Metric When to use Drawback
MAPE Business reporting, series without zeros Unstable for small values
sMAPE Model comparison Asymmetric interpretation
MASE Multi‑scale series, benchmarks Needs seasonal naive baseline
Pinball loss Probabilistic models Multiple values for different quantiles

We guarantee a model card with these metrics on the validation set and walk‑forward results on at least 6 months of history.

What deliverables do you receive?

  • Documentation of chosen architecture and hyperparameter rationale.
  • Reproducible training and inference pipeline (Docker + CI/CD + Airflow/Prefect).
  • Committed code with unit tests for key components.
  • Team training: retraining, output interpretation, deployment of new versions.
  • 3 months of post‑delivery support (consultations, bug fixes, fine‑tuning).

The model is deployed via FastAPI or Triton Inference Server. Retraining is scheduled (e.g., weekly) via Airflow with drift validation and automatic rollback if metrics deteriorate.

Process and timeline

We start with EDA: visualization, ADF test, STL decomposition, analysis of missing values and outliers. This takes 2–3 days but often reveals systemic data issues that block forecasting. Then we build a baseline (naive seasonal, Prophet), engineer features for LightGBM, and select a neural architecture if needed. Walk‑forward validation with a realistic horizon. Deployment via API with automatic retraining scheduled via Airflow or Prefect.

Timeline: MVP forecast on one data type – 3–6 weeks. Hierarchical forecasting system with automation – 2–5 months. Cost is calculated individually based on data volume, number of series, and required accuracy.

Our team consists of certified ML engineers (AWS ML Specialty, GCP Professional ML Engineer) with 5+ years on the market and over 50 completed forecasting projects. Contact us for a free analysis of your data – we will assess the task and provide initial recommendations within 1–2 days. Request a consultation to ensure your forecasts work in production, not just in a notebook.