Market data arrives as a stream of trades and quotes: every execution, bid, and ask, timestamped to the microsecond. Preparing this data for AI-based market forecasting requires turning price and volume histories into consistent inputs for model training and inference. A common first step is aggregating the data into bars—one row per instrument per time unit—with price, volume, and other statistics. Neural networks can learn patterns from these histories across instruments and forecast horizons.
NVIDIA Megatron Core is an open-source library of GPU-optimized components for training transformer models at scale. Megatron-LM is a GitHub repository that combines that library with preconfigured training scripts. A preprocessing script turns intraday market bars into model-ready tensors, and a dataset provider feeds them into Megatron’s distributed training loop.
This post shows how to preprocess market-bar data and train a model with Megatron-LM to forecast returns and trading volume across multiple horizons.
Forecast returns and trading volume
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, so the model can learn instrument-specific behavior within shared parameters. You can also explore longer contexts, different sampling frequencies, and additional features through the same interface.
The example forecasts 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. Point and interval forecasts address different research questions while using the same input representation.
You 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. Data from a new vendor or sampling scheme can follow the same row schema, while the dataset provider supplies the same batch fields. Figure 1 shows the pipeline from market bars to training.

From price and volume to model-ready sequences
The input is a directory of Parquet files with one row per bar and Symbol, Date, Timestamp, Close, and Volume columns, plus optional numeric feature columns. Bars can come from different vendors and sampling schemes, such as one-minute or sub-minute aggregates of tick data. Keep each instrument’s trading day in one file and the files in chronological order. The script sorts each instrument’s daily observations by timestamp. The script derives within-day log returns and log volumes itself, so the overnight gap never enters the inputs. The preprocessor treats rows as observation steps and leaves gaps unchanged. Align the data upstream if you need a regular time grid.
preprocessing.py 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 (Figure 2).

Run preprocessing and training
Before running the example, see the preprocessing README for environment setup, input-file requirements, configuration options, and output tensor formats.
First, preprocess the market bars into training-ready tensors:
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-targets
Then, run the Megatron training example 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 2000
This small model shows the expected input and output formats. Use it to check that preprocessing, the data loader, target masking, and loss computation work together before substituting your forecasting architecture.
You can replace this model while keeping the data layer unchanged. forward_step calls the model with patches (B, L, P, F), inst_id (B,), and patch_tod (B, L). 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 it.
Defining forecast targets
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.
Forecast horizons can be defined in observation steps or patches. A point target uses the return and volume at a future step; a cumulative target uses the summed log return and total volume over the interval. Volume targets are represented on a log scale. Figure 3 shows both target definitions for the same context.
For regular one-minute bars, a horizon of five observation steps corresponds to five minutes. For event-based data, it counts events.

Efficient data loading for distributed training
The data pipeline consists of two 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.
Prepare once, reuse across runs
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.
Map tensors and share batches
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.
Preserving time in financial modeling
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 keeps validation or test observations from entering 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.
Per-horizon target statistics are computed from the training split only. If you standardize targets, use these statistics during training, validation, and testing. Future evaluation data therefore does not determine the target scaling applied in training. The example trainer leaves targets unscaled.
Session boundaries are configurable. Input log returns reset at the start of each day. For cumulative forecasts, targets can include the overnight move; intraday-only targets instead mask horizons that cross the close. A separate setting keeps the input context within one trading day when that matches the task. The loader reconstructs valid-target masks from the saved values, so the loss can exclude unavailable targets.
These settings make the forecasting question explicit: which history is visible, how far ahead the target reaches, and whether the model is predicting within a session or across sessions.
Getting started
Use the preprocessing script and Megatron dataset provider with your own market-bar Parquet files. The input schema, tensor formats, and configuration options are documented in the preprocessing README, alongside a training example that connects the data interface to a forecasting model.
Choose the sampling frequency, context length, and forecast horizons that match your research question. Prepare the dataset, check its metadata and split counts, and use the saved tensors in a Megatron training run. Then experiment with other instruments, feature sets, and model configurations.