Skip to content
Applied engineeringExperiments

Verace Aurum

A six-stream multi-timeframe transformer for gold spot (XAUUSD) price forecasting and position decisions, trained in four phases.

Verace Research
  1. Gold spot (XAUUSD): Synthetic here; the model reads it at six timeframes
  2. Direction probability: Opens above 0.6, closes below 0.4
  3. Hysteresis and Kelly policy: Maps outputs to a target position
  4. Probability exceeds 0.6: Opens a position only above it
Figure 1. Policy rules over a synthetic gold series in Verace Aurum. Schematic: a synthetic gold price series as Verace Aurum reads it, with the direction probability, the trust gate and the points where the hysteresis and Kelly policy acts. No real prices or results are drawn.
Open the simulator on its own pageA rule reading a series: an interactive toy model of the principle. You can also try it below

Overview

Verace Aurum is a transformer model built to read gold spot (XAUUSD) price history at six timeframes at once and output a direction forecast, a calibrated distribution of the next return and a target position. Its research name in the lab's papers and code is MTF-PriceLLM. The question it addresses is whether one model, trained on public third-party historical minute bars aggregated to M1, M5, M15, H1, H4 and D1 streams, can combine short-horizon microstructure with daily regime context. It must also produce position decisions that stay consistent under strict causal data handling and transaction costs.

The architecture gives each timeframe its own encoder (width 128, 4 layers), pools each stream to a fixed set of tokens with learned queries, and fuses 52 tokens plus a learned [FUSE] token with cross-stream attention, for about 7M parameters. Separate heads output direction logits, 11 monotonic quantiles, a seven-slot trade output, a meta-label trust probability and a value estimate. Training runs in four phases: pretraining of the backbone with direction and quantile losses, supervised fine-tuning on triple-barrier labels, meta-label training of the trust head from backtest rollouts, and PPO fine-tuning with LoRA adapters, which keeps the checkpoint that scores best on holdout evaluation.

The full pipeline is implemented: data aggregation, causal alignment, purged walk-forward splits, model, losses, training phases, a backtest environment, conformal calibration, an ensemble and a hysteresis and Kelly inference policy. The code also covers an execution path for a third-party trading terminal with drawdown breakers, and a browser terminal. The smoke test records all 9 stages passing on synthetic data and 68 unit tests passing; this verifies wiring only, not convergence on real data, a Sharpe improvement from the later phases or holdout evaluation. The lab's backtest records report returns of +145.9% on holdout A (2018-2019) and +125.6% on holdout B (2023-2024), which the documentation calls out-of-sample. Random baselines lost 10-20% in the same simulator.

The model, training pipeline, backtest environment and inference stack are implemented and tested. The holdout figures are the lab's own backtest measurements, have not been independently reproduced, and the holdouts informed checkpoint selection. The lab's records describe a Sharpe above 5 as a best-case backtest and expect it to compress under realistic friction. Critiques of an earlier reinforcement learning version found an action space the deployed policy ignores and an oversized stop-out penalty; the current code uses a discrete three-action PPO policy with a value head, GAE and a trust gate, and the records do not say whether the penalty was rescaled. The paper-to-live readiness checklist records the status NOT READY, and no paper or live trading results are recorded.

Status

Experiments. The code implements the full training, backtest and inference pipeline, a smoke test and unit suite pass, and the lab's records report holdout backtest results, while the readiness checklist marks the system NOT READY for live use.

Simulator

A made-up series, and a rule that fires when a point lies far from the average of the points before it. Set how far, and how many points it looks back over.

  • synthetic data: not a record of any market
  • score: distance from the average, in units of the spread
Times the rule fired
14
Points outside the band
19%
Longest stretch without firing
35 points
The series
Synthetic

Narrow the band and the rule fires on noise; widen it and it misses moves. A longer window makes the band slower to follow.

This simulator is an illustration of the principle, with made-up numbers. It does not run the lab's code or show the lab's data, and nothing in it is a measurement.

Architecture

  1. Causal multi-timeframe data pipeline

    Aggregates minute bars to five coarser timeframes, computes a 16-dimensional feature frame per timeframe and exposes only fully closed bars at each prediction time, with padding masks.

  2. Per-stream transformer encoders

    Six encoders, one per timeframe, built from pre-norm RMSNorm blocks with rotary attention and SwiGLU feed-forward layers, applied after reversible instance normalization.

  3. Attention pooling and cross-stream fusion

    Learnable query tokens summarise each stream to a fixed size. A fusion transformer then attends across 52 stream tokens and a learned [FUSE] token, whose output feeds the heads.

  4. Regime embedding

    Combines 7 continuous regime statistics, a learned regime-id embedding and a CUSUM scalar through an MLP, with a k-means helper for fitting regime ids.

  5. Output heads

    Direction, monotonic quantile, seven-slot trade, zero-initialised meta-label trust and PPO value heads. An 8-dimensional portfolio state enters only the trade head.

  6. Four-phase training pipeline

    Pretraining, supervised fine-tuning, meta-label training and PPO fine-tuning with LoRA, each phase starting from the previous checkpoint.

  7. Backtest environment

    A gymnasium environment for XAUUSD with spread and commission fills, session-close and news-embargo forced flats, gap fills, stop-outs and a daily drawdown breaker.

  8. Inference stack

    Split-conformal calibration of the quantiles, a checkpoint ensemble and a hysteresis and Kelly policy that maps outputs to a target position in [-1, 1].

  9. Live execution and safety chain

    An execution path for a third-party trading terminal, configured to build observations from its bars, size orders by volatility targeting with caps, and stop through drawdown breakers, a kill-switch file and a notional cap.

  10. Trading terminal interface

    A browser interface that draws candles with the model's quantile forecast as a fan of bands past the last bar.

Implementation

Mechanisms as they are implemented in the source code, with the constants the code uses.

Strict causal stream alignment
align_streams returns, for each timeframe, the last N bars with tclose≤tt_{\text{close}} \le t at prediction time tt, so the bar still forming is excluded. Short histories are zero-padded with per-stream masks. A searchsorted index is precomputed for speed, and the test suite checks that no later bar is ever included.
Purged embargoed walk-forward splits
purged_walk_forward() builds folds with an embargo gap between train and validation, excludes holdouts A and B, carves out Christmas and Easter periods and reserves a dev_val slice per fold. Tests verify disjoint sets, holdout exclusion, embargo and immutability.
Triple-barrier labeling
labels.py labels each bar by which barrier is touched first: a volatility-scaled upper barrier, a lower barrier or a time limit. Direction labels use the convention UP=0, DOWN=1, FLAT=2, and undefined targets get the sentinel -1, which the weighted cross-entropy ignores through ignore_index=-1.
Monotonic quantile head
QuantileHead predicts a median and builds the other quantiles by adding softplus-transformed cumulative deltas, so qi+1≥qiq_{i+1} \ge q_i holds by construction for all 11 outputs. Tests check monotonicity even at extreme input scales.
Rotary attention with LoRA hooks
MultiHeadAttention applies half-rotation rotary position embeddings to queries and keys. Its projections keep stable names so lora.py can wrap Q, K, V and O with low-rank A and B matrices of rank 8 while the base weights stay frozen.
Kendall-Gal loss balancing
pretrain.py holds a fixed quantile weight for a warmup number of epochs, then switches to learnable uncertainty-weighted balancing of the direction and pinball losses. Training uses a warmup-cosine learning rate and early stopping on dev pinball loss.
Seven-slot trade head
The trade head writes disjoint raw outputs: action logits in slots [0:3], then a pre-tanh position mean, a log standard deviation, a stop-loss distance and a take-profit distance. Supervised and reinforcement learning updates therefore act on separate slots.
Meta-label trust head
meta_label.py rolls out the fine-tuned policy in the discrete backtest environment and records observations at trade opens with a profitability label. It then trains the zero-initialised trust head with binary cross-entropy and gates acceptance on AUC. Rollout start indices whose windows overlap a holdout are excluded with an O(N) cumulative-sum check.
PPO fine-tuning with trust gate
rl_ppo.py trains a discrete three-action policy through the trade and value heads plus LoRA adapters, with a KL penalty to the reference policy, an entropy bonus and a drawdown curriculum, and keeps the checkpoint that scores best on holdout evaluation, so the holdouts take part in model selection. ppo_utils.py computes categorical log-probabilities, entropy, KL and GAE with value bootstrapping. Actions are forced FLAT when the trust probability falls below a threshold.
Differential Sharpe reward
The reinforcement learning reward is the differential Sharpe ratio minus transaction cost, a drawdown penalty and an action-change penalty, with a stop-out penalty of -10. The lab's critique of an earlier version notes that per-bar reward is of order 1e-3, so this penalty dominates; the records do not say whether its scale was fixed.
Split conformal calibration
conformal.py fits an additive offset δi\delta_i per quantile on dev_val residuals. Monotonicity is restored by a cumulative maximum, q~i=max⁡j≤i(qj+δj)\tilde q_i = \max_{j \le i}(q_j + \delta_j), so calibrated quantiles stay ordered.
Hysteresis and Kelly policy
HysteresisKellyPolicy opens a position only when the direction probability exceeds 0.6 and closes it when the probability falls below 0.4, which avoids churn near the boundary. Size comes from a Kelly fraction computed on the interquartile spread of the quantile distribution and is scaled by the trust probability.
Log-probability ensembling
ensemble.py averages N MTFPriceLLM checkpoints and averages direction logits in log-probability space. The policy is then applied either to the averaged output or per member.
Drawdown circuit breakers
safety.py defines a daily drawdown threshold of 2.5% and a total threshold of 5%. Crossing either triggers a flatten and halt, and trip state persists in SQLite together with a kill-switch file check.

Results

From the lab's own experiments and records. They have not been independently replicated.

  1. End-to-end wiring passes on synthetic data

    The smoke test records all 9 stages passing on 43,200 synthetic minute bars, with a 10-step pretraining loss falling from 4.151 to 2.604. The unit suite records 68 tests passing, covering masks, monotonic quantiles and the action mapping. The smoke test records state that this verifies wiring only: not convergence on real data, a Sharpe improvement from the later phases or holdout evaluation.

  2. Holdout backtest returns reported by the lab

    The lab's backtest records report +145.9% return, Sharpe 5.20, 1.4% maximum drawdown and 56.1% win rate over 756 trades on holdout A (2018-2019). On holdout B (2023-2024) they report +125.6%, Sharpe 4.86, 1.6% maximum drawdown and 55.3% win rate over 669 trades. The documentation calls these periods out-of-sample, but the reinforcement learning phase selects its checkpoint by holdout evaluation, so the holdouts are not untouched by model selection.

  3. Random baselines lose money in the simulator

    Random policies over 4 seeds on both holdouts lost 10-20%, with Sharpe between -0.26 and -0.36 and win rates of 42-48%, in the lab's records. The lab reads this as evidence that the cost model is not lenient.

  4. Backtest Sharpe is a best-case figure

    The lab's own records state that Sharpe above 5 is a best-case backtest and expect tick-level slippage and variable spreads to bring it to roughly 1.5-2.5.

  5. Critique rounds found and fixed core bugs

    The lab's reviews recorded data pipeline bugs C1-C9, including dropped Friday D1 bars and NaN directions treated as FLAT. They also recorded model bugs M1-M3, including ignored masks and shared trade-head columns, and environment bugs E1-E6, including an inverted discrete action mapping and double-counted commission. The simulator went through four rounds of fixes.

  6. Earlier reinforcement learning version had design issues

    The lab's critique of an earlier version found that the RL phase optimized a continuous Gaussian head the deployed hysteresis and Kelly policy never used, kept the trust gate off in training, lacked a value head, and set a -10 stop-out penalty against per-bar rewards near 1e-3 that would push the policy toward always flat. The current code uses a discrete three-action PPO policy with a value head, GAE and a trust gate; the records do not say whether the stop-out penalty scale was fixed.

  7. Inference latency measured at about 20 ms

    The lab's inference benchmark records a median latency of about 20 ms.

  8. Not ready for live operation

    The paper-to-live readiness checklist records the status NOT READY. Its gates include 30 days of paper trading, for which no results are recorded.

Concepts

Multi-timeframe streams
The same price series is resampled to M1, M5, M15, H1, H4 and D1 bars, and each resolution is encoded separately. Short-horizon patterns and daily context are then combined by attention.
Look-ahead leakage
Using information that would not have been available at prediction time, such as a bar that has not yet closed. The alignment rule, embargoed splits and holdout-safe rollout starts all exist to prevent it.
Quantile forecast
Instead of a single predicted return, the model outputs 11 quantile levels of the next normalized return, from the far lower tail to the far upper tail, trained with pinball loss and kept in order by construction.
Reversible instance normalization
Each input window is normalized by its own per-feature mean and spread, and the normalization can be inverted. This handles the large change in gold's price level across the training period.
Triple barrier
A labeling scheme that marks a trade outcome by whichever comes first: a profit barrier, a loss barrier or a time limit, with barriers scaled by volatility.
Meta-labeling
A second model that, given a proposed action, predicts the probability that the trade will be profitable. Here it gates and scales position size.
Differential Sharpe ratio
An incremental, per-step form of the Sharpe ratio that can serve as a dense reinforcement learning reward.
Conformal calibration
A distribution-free method that adjusts predicted quantiles with offsets fit on held-out data so that observed coverage matches the nominal level.
Hysteresis thresholds
Separate, asymmetric thresholds for entering and leaving a position, so small fluctuations around one threshold do not cause repeated flips.
Kelly sizing
Choosing position size as a fraction of capital derived from the forecast edge relative to its uncertainty. Here the uncertainty is read from the quantile distribution.
LoRA adapters
Low-rank trainable matrices added to frozen attention projections, so fine-tuning changes few parameters. Rank 8 is used in the PPO phase.
Random baseline as simulator check
The lab ran random policies through the same backtest to confirm that spread and commission costs drain returns. The records report losses of 10-20% for these policies.
Paper and live same code
A design invariant in the lab's records: paper and live operation run identical code and differ only in credentials, with risk shaped through configuration.
Critique-fix rounds
The lab reviewed each subsystem in written critique rounds, covering data, model and losses, backtest environment, training scripts and inference, and fixed the numbered bugs it found.

About this page

Written from the lab's own documents and source code. Figures and results are the lab's measurements as it recorded them at the time, and have not been independently replicated.

Market results here are backtests and logs kept by the lab. Nothing on this page is financial advice.

Published under the PolyForm Noncommercial License 1.0.0: free for noncommercial use.