PyTorch Forecasting: Deep Learning Time Series Forecasting for Python

Jul 9, 2025

Introduction

Predicting future values in complex datasets is a constant challenge for data scientists, often requiring a tedious mix of manual feature engineering and boilerplate training loops. PyTorch Forecasting is a high-level Python library that simplifies the implementation of state-of-the-art deep learning architectures for time series forecasting, with over 4.9k GitHub stars. By leveraging PyTorch Lightning, it removes the infrastructure overhead, allowing developers to focus on model selection and data preparation rather than the mechanics of GPU scaling and logging.

What Is PyTorch Forecasting?

PyTorch Forecasting is a PyTorch-based package that provides a high-level API for forecasting with state-of-the-art deep learning architectures. It is designed for both real-world production use cases and research, balancing flexibility for professionals with reasonable defaults for beginners. The library is licensed under the MIT License and is maintained as part of the sktime ecosystem.

At its core, the library abstracts the most painful parts of neural time series forecasting: data transformation, training loops, and evaluation. By building on top of PyTorch Lightning, it enables seamless scaling from a single CPU to multiple GPUs without changing the underlying code, making it an ideal choice for scaling deep learning models to massive industrial datasets.

Why PyTorch Forecasting Matters

Traditional statistical models like ARIMA or Prophet often struggle with high-dimensional data, complex non-linear patterns, and the integration of exogenous variables (covariates). While deep learning offers a solution, building these models from scratch in raw PyTorch requires significant boilerplate code for data loading, normalization, and multi-horizon prediction. PyTorch Forecasting fills this gap by providing a standardized framework for these tasks.

The library’s significance lies in its ability to handle “global” models—models trained across multiple time series simultaneously. This allows the network to learn shared patterns across different products, stores, or regions, which is a massive advantage over traditional “local” models that fit a separate model to every single series. This capability, combined with integrated hyperparameter tuning via Optuna, makes it a powerful tool for enterprise-grade forecasting.

Key Features

  • TimeSeriesDataSet: A comprehensive dataset class that abstracts variable transformations, handles missing values, and manages randomized subsampling for efficient training.
  • Base Model Class: A standardized base class that provides built-in training loops, TensorBoard logging, and generic visualizations such as actual vs. predictions plots.
  • Advanced Architectures: Includes state-of-the-art models like the Temporal Fusion Transformer (TFT), DeepAR, N-HiTS, and N-Beats, optimized for real-world deployment.
  • Multi-Horizon Metrics: Specialized metrics designed for time series forecasting that evaluate performance across different prediction horizons.
  • Integrated Hyperparameter Tuning: Native support for Optuna, allowing users to automatically find the best learning rates, hidden sizes, and architecture parameters.
  • PyTorch Lightning Integration: Out-of-the-box support for multi-GPU training, automatic checkpointing, and hardware-agnostic execution.
  • Model Interpretability: Built-in tools to visualize attention weights and variable importance, helping users understand why a model made a specific prediction.
  • Covariate Support: Native handling of known future covariates (e.g., holidays) and unknown past covariates (e.g., weather) to improve forecast accuracy.

How PyTorch Forecasting Compares

Feature PyTorch Forecasting Darts GluonTS Prophet
Deep Learning Focus High High High Low
Backend PyTorch Lightning PyTorch/Various MXNet/PyTorch Stan
Ease of Setup Medium High Medium High
Interpretability High (TFT) Medium Medium High
Global Models Native Native Native Local

When comparing PyTorch Forecasting to other libraries, the primary differentiator is its deep integration with PyTorch Lightning. While Darts provides a broader range of models (including classical ones), PyTorch Forecasting is more specialized in providing a highly structured, production-ready pipeline for deep learning models. It is particularly strong in the Temporal Fusion Transformer (TFT) implementation, which is often cited as one of the most interpretable deep learning forecasting models available.

Compared to GluonTS, PyTorch Forecasting offers a more intuitive API for data preparation via the TimeSeriesDataSet class. GluonTS is powerful but can be more complex to modify due to its object inheritance structure. Prophet, on the other hand, is a statistical additive model. While it is significantly easier to set up for a single time series, it cannot learn shared patterns across multiple series, making it unsuitable for large-scale industrial forecasting where deep learning is required.

Getting Started: Installation

PyTorch Forecasting requires PyTorch to be installed first. Depending on your operating system and hardware, follow the appropriate method below.

Using pip (Standard)

pip install pytorch-forecasting

Using pip (CPU only)

pip install pytorch-forecasting --extra-index-url https://download.pytorch.org/whl/cpu

Using Conda

conda install pytorch-forecasting pytorch>=2.0.0 -c pytorch -c conda-forge

Windows Installation

Windows users should first install PyTorch using the official stable channel to ensure GPU compatibility:

pip install torch -f https://download.pytorch.org/whl/torch_stable.html

Specialized Installation (MQF2 Loss)

To use the multivariate quantile loss (MQF2), install the package with the following extra:

pip install pytorch-forecasting[mqf2]

How to Use PyTorch Forecasting

The workflow in PyTorch Forecasting follows a structured pipeline: data preparation, model instantiation, training, and prediction. The most critical step is defining the TimeSeriesDataSet, which acts as a blueprint for how the raw data is transformed into tensors.

First, you define your target variable, the time index, and the group IDs (the unique identifiers for each time series). You then specify which variables are known in the future (like holidays) and which are only known in the past. Once the dataset is created, you use the .from_dataset() method to ensure that the validation and test sets use the exact same normalization and encoding parameters as the training set.

Finally, you instantiate a model (e.g., the Temporal Fusion Transformer) using the .from_dataset() method, which automatically configures the model’s input and output layers based on the dataset’s metadata. This eliminates the manual calculation of input dimensions, a common source of errors in deep learning.

Code Examples

The following example demonstrates the basic implementation of a Temporal Fusion Transformer (TFT) model.

import lightning.pytorch as pl
from lightning.pytorch.callbacks import EarlyStopping
from pytorch_forecasting import TimeSeriesDataSet, TemporalFusionTransformer, QuantileLoss

# 1. Define the dataset
max_encoder_length = 36
max_prediction_length = 6

training = TimeSeriesDataSet(
    data, 
    time_idx=1, 
    target="value", 
    group_ids=["series"], 
    max_encoder_length=max_encoder_length,
    max_prediction_length=max_prediction_length,
    time_varying_known_reals=["month", "day_of_week"],
    time_varying_unknown_reals=["value"],
    target_normalizer=None
)

# 2. Create validation set from training set
validation = TimeSeriesDataSet.from_dataset(training, data, stop_random_sampling=True)

# 3. Create dataloaders
train_dataloader = training.to_dataloader(train=True)
val_dataloader = validation.to_dataloader(train=False)

# 4. Instantiate the model
tft = TemporalFusionTransformer.from_dataset(training, learning_rate=0.03, hidden_size=16)

# 5. Train using PyTorch Lightning
trainer = pl.Trainer(max_epochs=100, accelerators="auto")
trainer.fit(tft, train_dataloaders=train_dataloader, val_dataloaders=val_dataloader)

In this snippet, the TimeSeriesDataSet handles the scaling and encoding of categorical variables automatically. The TemporalFusionTransformer is instantiated directly from the dataset, which ensures the model architecture matches the data dimensions perfectly.

Real-World Use Cases

PyTorch Forecasting shines in scenarios where you have thousands of related time series and need a global model that can learn shared patterns.

  • Retail Demand Forecasting: A retailer can train a single model across thousands of SKUs across different stores. The model learns that certain products share similar seasonal patterns, allowing it to forecast demand for new products (cold-start problem) using only their category metadata.
  • Energy Grid Load Prediction: Utility companies can use PyTorch Forecasting to predict electricity demand across hundreds of different substations. By including weather data as a known future covariate, the model can accurately anticipate peaks in energy consumption based on temperature forecasts.
  • Financial Market Volatility: Analysts can model the price movements of multiple assets simultaneously. By using the Temporal Fusion Transformer, they can interpret which specific time lags or exogenous variables are most influential in driving price changes.

Contributing to PyTorch Forecasting

Contributions to PyTorch Forecasting are welcome and you do not need to be an expert in deep learning to help. The project follows a standard GitHub flow: users are encouraged to open an issue to discuss proposed changes before submitting a pull request. This ensures that the library remains stable and backward compatible.

To contribute, fork the repository, install dependencies using poetry install, and create a feature branch from the master branch. The project emphasizes powerful abstractions that allow for quick experimentation while maintaining full control for the user. If you find a bug or miss a feature, the maintainers encourage you to propose it via GitHub Issues.

Community and Support

The PyTorch Forecasting community is active and provides support through several official channels. The primary hub for technical discussions and bug reporting is the GitHub Discussions and Issues tabs. For real-time collaboration, the project provides links to Discord and Slack channels.

Comprehensive documentation is available at the official Read the Docs site, which includes detailed tutorials and an API reference. Because the library is built on PyTorch Lightning, users can also leverage the broader PyTorch Lightning community for questions regarding training loops, GPU acceleration, and hardware optimization.

Conclusion

PyTorch Forecasting is the right choice for data scientists who need to scale deep learning forecasting models to production. It is particularly effective when dealing with “global” forecasting problems where shared patterns across multiple time series are required. While it has a steeper learning curve than statistical tools like Prophet, the predictive power and scalability of models like the Temporal Fusion Transformer provide a massive advantage in industrial settings.

If you are working with a single, simple time series with strong seasonality, a classical statistical model may be sufficient. However, for high-dimensional, multi-horizon forecasting with complex covariates, PyTorch Forecasting is the most robust framework available in the PyTorch ecosystem. Star the repo, try the quickstart, and join the community to start building advanced forecasting pipelines.

What is PyTorch Forecasting and what problem does it solve?

PyTorch Forecasting is a high-level library for time series forecasting using deep learning. It solves the problem of excessive boilerplate code and infrastructure overhead associated with building neural networks for forecasting, providing a standardized API for data preparation and training.

How do I install PyTorch Forecasting?

You can install it via pip using pip install pytorch-forecasting or via conda using conda install pytorch-forecasting pytorch>=2.0.0 -c pytorch -c conda-forge. Windows users should install PyTorch first from the official stable channel.

Can I use PyTorch Forecasting for anomaly detection?

While the library is primarily focused on forecasting, the prediction errors (residuals) from its models can be used to identify anomalies. However, it is not a dedicated anomaly detection library like ADTK or Merlion.

How does PyTorch Forecasting compare to Prophet?

PyTorch Forecasting uses deep learning (neural networks) and can learn shared patterns across multiple time series (global models), whereas Prophet is a statistical additive model designed for a single time series (local models). PyTorch Forecasting is generally more accurate for complex, high-dimensional data.

What is the Temporal Fusion Transformer (TFT)?

The Temporal Fusion Transformer is a state-of-the-art architecture implemented in the library that combines LSTM layers with attention mechanisms to provide high-accuracy forecasts and interpretable variable importance.

Does PyTorch Forecasting support multi-GPU training?

Yes, because it is built on PyTorch Lightning, it supports multi-GPU training and distributed training across multiple nodes out-of-the-box without requiring changes to the model code.

How do I handle missing values in my time series data?

The TimeSeriesDataSet class provides built-in mechanisms to handle missing values and normalization, ensuring that the data is transformed correctly for the model without requiring manual preprocessing pipelines.