Prepare Market Data for Forecasting with NVIDIA Megatron Core
NVIDIA Megatron Core offers GPU-optimized components for training transformer models at scale. This guide details how to preprocess intraday market bars into model-ready tensors, manage distributed data loading, and apply temporal safeguards to forecast returns and trading volume effectively.
Tags
Quick summary
NVIDIA Megatron Core offers GPU-optimized components for training transformer models at scale. This guide details how to preprocess intraday market bars into model-ready tensors, manage distributed data loading, and apply temporal safeguards to forecast returns and trading volume effectively.
Prepare Market Data for Forecasting with NVIDIA Megatron Core
Market data arrives as a continuous stream of trades and quotes, timestamped to the microsecond. Preparing this data for AI-based market forecasting requires transforming price and volume histories into consistent inputs suitable for model training and inference. A common first step involves aggregating raw data into bars—one row per instrument per time unit—containing price, volume, and other statistics. Neural networks can then learn patterns from these histories across instruments and forecast horizons.
NVIDIA Megatron Core is an open-source library of GPU-optimized components designed for training transformer models at scale. The Megatron-LM repository combines this library with preconfigured training scripts. Within this ecosystem, a preprocessing script converts intraday market bars into model-ready tensors, while a dataset provider feeds them into Megatron’s distributed training loop. This approach allows researchers to preprocess market-bar data and train a model to forecast returns and trading volume across multiple horizons.
From Price and Volume to Model-Ready Sequences
Price and volume remain continuous features. A learned patch embedding turns each group of observations into a model input without converting market values into text. A common data interface supports training a shared forecasting model on histories from many instruments. Each training window belongs to one instrument and includes its identifier, allowing the model to learn instrument-specific behavior within shared parameters.
The input consists of a directory of Parquet files with one row per bar. Essential columns include Symbol, Date, Timestamp, Close, and Volume, alongside optional numeric feature columns. Bars can originate from different vendors and sampling schemes, such as one-minute or sub-minute aggregates of tick data. It is critical to keep each instrument’s trading day in one file and maintain files in chronological order.
The preprocessing script sorts each instrument’s daily observations by timestamp and derives within-day log returns and log volumes itself, ensuring the overnight gap never enters the inputs. The preprocessor treats rows as observation steps and leaves gaps unchanged, though upstream alignment is recommended if a regular time grid is required.
The script groups consecutive bars for one instrument on one trading day into patches—the model’s tokens—and slides fixed-length context windows over them. Each patch retains the features of its constituent rows. For example, eight bars per patch and 32 patches per window provide 256 observations in a sequence of 32 model positions. An instrument ID identifies the series, and each patch carries its position within the trading day.
Defining Forecast Targets
The framework enables forecasting returns and trading volume at several horizons from the same context. Quantitative researchers can use these outputs to study short-term market behavior, trading activity, or execution timing. Both point and interval forecasts address different research questions while utilizing the same input representation.
Forecast horizons can be defined in observation steps or patches. A point target uses the return and volume at a future step, whereas a cumulative target uses the summed log return and total volume over the interval. Volume targets are represented on a log scale. For regular one-minute bars, a horizon of five observation steps corresponds to five minutes. For event-based data, it counts events.
The example configuration uses the following command to run preprocessing:
python examples/financial_timeseries/preprocessing.py \
--data-dir /data/bars --out-dir /data/tensors \
--patch-len 8 --context-len 32 --window-stride 16 \
--time-units-per-day 390 --horizons 1,2,5,15 \
--target-mode cumulative --no-allow-overnight-targetsThis command groups consecutive bars, defines the context length, and sets the forecast horizons. The --target-mode cumulative flag specifies the aggregation method for targets, while --no-allow-overnight-targets prevents overnight gaps from affecting target construction.
Efficient Data Loading for Distributed Training
The data pipeline consists of two distinct stages: preprocessing and data loading. Preprocessing builds the features, patches, windows, and targets offline, then writes them as PyTorch tensor files: train.pt, val.pt, test.pt, and meta.pt. Training reads these saved tensors, keeping Parquet parsing and target construction outside the training loop.
During preprocessing, the script handles files in order and uses array operations for regular bar layouts, with a per-instrument path for irregular observations. It computes each instrument’s target sequence once and reuses it across overlapping windows. Temporary memory-mapped arrays hold the completed split tensors before they are saved to disk.
The saved metadata records instrument mappings, feature names, patch and context lengths, forecast horizons, and normalization statistics. Model and dataset settings can be checked against the same description before training.
The data loader reads the saved splits and supplies batches for training or inference. Validation checks that required keys are present, sample counts align, and the stored context length matches the model. Each worker opens the saved file lazily through memory mapping; fetching a sample copies only its selected rows into private memory.
Within each tensor-parallel group, rank zero reads the microbatch and broadcasts it to the other ranks. Megatron’s sampler handles data-parallel sampling and can reshuffle and cycle through the saved windows for the requested number of training iterations. This connects the market-data interface to the training loop, parallelism, and checkpointing used by the forecasting model.
Temporal Safeguards and Model Architecture
The outputs are split by date into training, validation, and test sets. A window is retained only when its entire context and future observations needed for the longest forecast horizon fall within the same split. This ensures validation or test observations do not enter training windows or training targets.
An embargo removes trading days from the end of the training period before validation begins; validation and test are adjacent. The script also checks that the context patches used by different splits do not overlap. These safeguards address cross-split leakage that could introduce forward-looking bias.
The framework separates the data interface from the model architecture, allowing researchers to substitute custom forecasting models while reusing the same preprocessing, data loader, and target masking logic. The forward_step function calls the model with patches (B, L, P, F), inst_id (B,), and patch_tod (B, L). The loss_func expects a dictionary with return and volshare tensors of shape (B, L, H), with one forecast per context position and horizon.
Any MegatronModule that takes those three inputs and returns that dictionary can replace the default model. Each window includes future targets for every context position, so one forward pass produces forecasts throughout the context rather than only at the end. A causal forecasting model uses only the history available at each position.
Getting Started
To run the training example, use the following command with the saved tensors:
torchrun --nproc_per_node=4 -m examples.financial_timeseries.pretrain_ts \
--ts-data-path /data/tensors --dataloader-type cyclic \
--num-layers 4 --hidden-size 256 --num-attention-heads 4 \
--seq-length 32 --max-position-embeddings 32 \
--micro-batch-size 64 --global-batch-size 256 --train-iters 2000 \
--lr 3e-4 --min-lr 3e-5 --lr-decay-style cosine --lr-warmup-iters 100 \
--tokenizer-type NullTokenizer --bf16 \
--log-interval 50 --eval-interval 500 --eval-iters 20 \
--save /data/ckpt --save-interval 2000This small model demonstrates the expected input and output formats. It allows researchers to check that preprocessing, the data loader, target masking, and loss computation work together before substituting their forecasting architecture.
Researchers can change the model architecture, optimizer, or training duration while reusing a prepared dataset. Preprocessing records the patch size, context length, and forecast horizons in the saved metadata, making the data configuration an explicit part of each experiment. A consistent representation also separates the source feed from the model, allowing data from a new vendor or sampling scheme to follow the same row schema while the dataset provider supplies the same batch fields.
For environment setup, input-file requirements, configuration options, and output tensor formats, users should review the preprocessing README. The framework enables the preparation of datasets and the execution of training experiments using the preprocessing script and Megatron dataset provider with custom market-bar Parquet files.
Source: https://developer.nvidia.com/blog/prepare-market-data-for-forecasting-with-nvidia-megatron-core



