Mongol Forex

News

How we trained an RL gold bot: HMM, Sortino and PPO

Our article on the RL gold bot tells you what the tests showed. This one opens the workshop: the learning algorithm, the reward designs, the regime model and the validation machinery we used while training it. Every method below was implemented in Python, trained on gold history and tested with the same written rules, and all of it ships inside the RL Gold Research Kit.

The learner: PPO with small networks

We used Proximal Policy Optimization from Stable-Baselines3 with small neural networks (two hidden layers of 64 or 32 units). Training runs for a fixed number of steps with no early stopping and no picking of the best checkpoint, and each agent is evaluated exactly once per test window with a deterministic policy. Choosing the best moment after seeing the test result is one of the quiet ways a backtest lies, so we removed the choice.

Framing the problem: from bar-by-bar control to a contextual bandit

Round one let the agent choose long, short or flat at every hourly bar. Round two moved to a contextual bandit: each breakout signal is one decision (skip, half size or full size) and its reward is that trade's own result in units of risk, with the discount factor set to zero. One decision per event removes the credit-assignment noise of long trades with many bars between action and result.

Reward engineering

The reward is where a trading agent learns what we really want, so we built it in layers and tested each layer on its own:

  • Log equity return, with the round-trip cost already inside the account value, so the agent feels every fee.
  • Drawdown penalty. A term that charges the agent for each new increase in drawdown. We removed it as an experiment and counted the trades: without it the agent traded about three times as often, which showed us the penalty was acting as a brake on over-trading.
  • Sortino-style asymmetry. A variant that weights a losing decision twice as heavily as a winning one, so that downside risk is punished more than upside is rewarded.

Regime features with hmmlearn

We added a market-regime signal from a two-state Gaussian hidden Markov model (hmmlearn) fitted to daily log returns, one state for calm markets and one for volatile ones. Three details keep it honest:

  • Fitted on training days only, separately for every walk-forward fold.
  • A forward filter, not forward-backward. The usual smoothing call reads the future of the series. We compute the probability of the volatile state with a causal forward recursion, so the value on day t uses days up to t only. A test rewrites every later bar and requires the earlier features to be bit-identical.
  • Hysteresis. A flag switches to the volatile state only after three consecutive days above 0.8 and back only after three days below 0.2, so a single noisy day cannot flip the regime.

The regime enters the agent as two observation features, not as an on-off switch.

Observations built to be leak-free

Every feature is computed from closed bars only and is expressed in ATR units, so there is no fitted scaler that could leak the test period into training. The agent sees candle shape, Bollinger position on the 4-hour and 1-hour charts, the distance from the 50-bar average, the recent move, the position inside the 20-day range, the distance from the 200-day average, and the time of day and week. The ATR is used only as a size unit, never as a direction signal.

Validation machinery

  • Walk-forward windows with an embargo between training and test, five random seeds per window, and a final period kept untouched behind a lock file that allows a single read.
  • A random baseline built from the agent's own decisions: the same skips and sizes in a random order, or its action sequence shifted in time. The agent has to beat the 95th percentile of 200 such versions.
  • Rules written before the run: the claim, the pass / fail thresholds and a forecast of the outcome go on file first.
  • Replay and cross-checks: every saved run is replayed to the cent, and the engine was compared trade by trade with an independent earlier implementation.

What these methods did to the results is in We built an RL trading bot for gold: what the tests showed. To run the same machinery on your own ideas, see the RL Gold Research Kit.

Send it to someone who needs it:FacebookMessengerTelegramX

← All newsQuestions? Message us on Telegram