GluonTS: A Powerful Python Library for Time Series Forecasting

Click the card above to follow me

Set a star to learn more skills

Time series forecasting is an important branch of data science, widely used in scenarios such as financial market analysis, sales forecasting, and energy demand planning. Traditional time series methods like ARIMA, while classic, struggle to capture complex nonlinear patterns. GluonTS, developed by the Amazon AWS team, is a specialized time series modeling toolkit that introduces deep learning techniques into time series forecasting, with a particular emphasis on probabilistic forecasting rather than point forecasting. GluonTS is built on the PyTorch and MXNet frameworks and offers a variety of cutting-edge models, including DeepAR, Transformer, and Time Fusion Transformer.

Installation

1. Basic Installation

GluonTS supports both PyTorch and MXNet backends. The PyTorch version is recommended, and the installation command is as follows:

# Install the PyTorch-supported version (recommended)
pip install "gluonts[torch]"

# Or install the MXNet-supported version
pip install "gluonts[mxnet]"

2. Full Installation

If you need all features and dependencies, you can perform a full installation:

# Install the full version, including all optional dependencies
pip install "gluonts[torch,pro]"

3. Install Additional Tools

For better visualization and data processing capabilities, it is recommended to also install the following libraries:

pip install pandas matplotlib seaborn

4. Verify Installation

Verify if GluonTS is correctly installed with the following code:

import gluonts
print(f"GluonTS version: {gluonts.__version__}")

# Test importing core modules
from gluonts.dataset.repository import get_dataset
from gluonts.torch import DeepAREstimator
print("GluonTS installation successful!")

Core Features

  • Probabilistic Forecasting Capability: Generates complete probability distributions rather than point forecasts, providing prediction intervals and uncertainty quantification.
  • Rich Model Library: Built-in deep learning models such as DeepAR, Transformer, and N-BEATS.
  • Flexible Architecture: Modular design supports custom models and rapid experimentation.
  • Standardized Data Pipeline: Provides a unified interface for data loading, processing, and iteration.
  • Support for Multiple Distributions: Supports various probability distributions such as Gaussian, Student’s t, and Negative Binomial.
  • Automatic Feature Processing: Automatically handles time features, holidays, covariates, etc.
  • Built-in Evaluation Tools: Provides comprehensive model evaluation metrics and visualization capabilities.
  • Pre-trained Models: Supports pre-trained models for zero-shot forecasting, such as Chronos.

Basic Functions

1. Load Datasets

GluonTS provides several built-in standard time series datasets for quick start and model testing. You can easily download and load these datasets using the get_dataset function, and the data will be automatically cached locally to avoid repeated downloads.

from gluonts.dataset.repository import get_dataset

# Load the built-in airline passenger dataset
dataset = get_dataset("airpassengers")

# View dataset information
print(f"Dataset metadata: {dataset.metadata}")
print(f"Prediction length: {dataset.metadata.prediction_length}")
print(f"Time frequency: {dataset.metadata.freq}")

# View the first time series of the training data
train_entry = next(iter(dataset.train))
print(f"Time series start time: {train_entry['start']}")
print(f"Time series length: {len(train_entry['target'])}")

2. Train DeepAR Model

DeepAR is one of the most popular models in GluonTS, which implements probabilistic time series forecasting based on recurrent neural networks. This model can learn patterns across multiple related time series and automatically capture seasonality and trends.

from gluonts.torch import DeepAREstimator
from gluonts.dataset.repository import get_dataset

# Load data
dataset = get_dataset("airpassengers")

# Create DeepAR estimator
estimator = DeepAREstimator(
    prediction_length=dataset.metadata.prediction_length,
    freq=dataset.metadata.freq,
    trainer_kwargs={"max_epochs": 20}
)

# Train model
predictor = estimator.train(dataset.train)
print("Model training completed!")

3. Generate Forecasts

The trained model can make predictions on the test set, generating probabilistic forecast results that include multiple sample paths. GluonTS’s forecasts are not single values but a distribution that encompasses multiple possible future realizations.

from gluonts.evaluation import make_evaluation_predictions

# Generate forecasts
forecast_it, ts_it = make_evaluation_predictions(
    dataset=dataset.test,
    predictor=predictor,
    num_samples=100
)

# Convert to list
forecasts = list(forecast_it)
tss = list(ts_it)

# View the first forecast result
print(f"Number of forecast samples: {forecasts[0].num_samples}")
print(f"Forecast interval: {forecasts[0].mean}")

Advanced Features

1. Model Evaluation and Metrics

GluonTS provides a complete evaluation framework that can automatically calculate various forecasting performance metrics. The Evaluator class can compute standard metrics such as MASE, sMAPE, and RMSE, providing both global aggregate metrics and detailed metrics for each time series.

from gluonts.evaluation import Evaluator

# Create evaluator, specifying the quantiles to calculate
evaluator = Evaluator(quantiles=[0.1, 0.5, 0.9])

# Calculate evaluation metrics
agg_metrics, item_metrics = evaluator(tss, forecasts)

# View aggregate metrics
print("Aggregate evaluation metrics:")
for key, value in agg_metrics.items():
    print(f"{key}: {value:.4f}")

# View MASE and sMAPE
print(f"\nMASE: {agg_metrics['MASE']:.4f}")
print(f"sMAPE: {agg_metrics['sMAPE']:.4f}")

2. Custom Distributions

GluonTS supports various probability distributions, allowing users to choose the appropriate distribution type based on data characteristics.

from gluonts.torch import DeepAREstimator
from gluonts.torch.distributions import StudentTOutput, NegativeBinomialOutput

# Use Student's t distribution (more robust to outliers)
estimator_student = DeepAREstimator(
    prediction_length=12,
    freq="M",
    distr_output=StudentTOutput(),
    trainer_kwargs={"max_epochs": 20}
)

# Use Negative Binomial distribution (suitable for count data)
estimator_nb = DeepAREstimator(
    prediction_length=12,
    freq="M",
    distr_output=NegativeBinomialOutput(),
    trainer_kwargs={"max_epochs": 20}
)

3. Multivariate Time Series Forecasting

GluonTS not only supports univariate time series but can also handle multivariate time series and covariates. By adding time features, static features, or dynamic covariates, forecasting performance can be significantly improved.

from gluonts.torch import DeepAREstimator
import pandas as pd
import numpy as np

# Create data with covariates
training_data = [{
    "start": pd.Period("2020-01-01", freq="D"),
    "target": np.random.randn(100),
    "feat_dynamic_real": np.random.randn(2, 100)  # Two dynamic features
}]

# Train model supporting covariates
estimator = DeepAREstimator(
    prediction_length=10,
    freq="D",
    use_feat_dynamic_real=True,
    trainer_kwargs={"max_epochs": 10}
)

predictor = estimator.train(training_data)
print("Model supporting covariates training completed!")

Conclusion

GluonTS, as a professional deep learning time series toolkit, provides a complete and powerful solution for probabilistic time series forecasting. It integrates various cutting-edge deep learning models and offers a full toolchain from data processing, model training to evaluation and visualization. Compared to traditional methods, GluonTS’s probabilistic modeling approach better quantifies the uncertainty of predictions, which is of significant value in risk management and decision-making. Whether for retail sales forecasting, energy load planning, or financial risk management, GluonTS can provide accurate and reliable forecasting support. Its modular design and rich model library enable researchers and engineers to quickly build and test new forecasting solutions.

💡 Recommended Reading

If you encounter difficulties in using programming tools, I recommend a third-party sharing platform aigocode.com, which can handle Codex and Claude Code in one go, for content introduction and payment exchange details, see the original text at the end of the article.

📘 We have compiled an “AI Programming Overseas Blue Book,” gathering the core experiences accumulated by the team in practical overseas operations over the past few months. The content is continuously updated.

From demand, tools, deployment, payment collection, to SEO, promotion, and traffic generation, step by step, we will help you understand the overseas path that ordinary people can start. This material can help you quickly get started and avoid pitfalls.

Scan or search WeChat 257735 to add WeChat, reply【Overseas Materials】 to receive it for free.

GluonTS: A Powerful Python Library for Time Series Forecasting

One-click deployment of Vercel templates makes launching overseas websites easier than you think!

Essential tools for website SEO: Google Search Console usage tutorial

Claude Code and Codex, one platform to handle it all, developers rejoice!

Set up intranet penetration in 3 minutes to allow others to access your local services

From the surge in Sora’s popularity, understand the logic of finding words in Google Trends

Leave a Comment