Algorithmic Trading Pair trading strategy using reinforcement learn...

Pair trading strategy using reinforcement learning algortihms (PPO and A2C)

Pair trading strategy using reinforcement learning algortihms (PPO and A2C)

Deep Reinforcement Learning for Pair Trading

Can a learning algorithm improve on a trading rule that is already simple, interpretable, and grounded in a statistical relationship? That question motivated a personal research project on pair trading using reinforcement learning (RL). The goal was not just to train an agent that produced an attractive return curve. It was to test whether that agent could offer a meaningful improvement over a classical strategy once trading costs and variability in its decisions were taken into account.

Pair trading focuses on the relationship between two assets rather than predicting the market’s overall direction. A typical mean-reversion strategy tracks a spread, a measure of their relative prices, and takes offsetting long and short positions when that spread moves unusually far from its reference level. The trade seeks to profit if the relationship moves back toward that level. The important qualification is that convergence is an expectation, not a guarantee.

Reinforcement learning approaches the decision differently. An agent observes information about the market and its portfolio, chooses an action, and receives a reward that guides learning during training. A policy is the rule the agent learns for choosing those actions. With deep reinforcement learning (DRL), neural networks represent components of that decision-making process. Our research primarily examines Proximal Policy Optimization (PPO) and Advantage Actor-Critic (A2C), with the findings reported in two articles (Quintero et al., 2024; Quintero et al., 2025).

For readers who want a broader introduction to pair trading and statistical arbitrage, Isichenko’s The Art and Science of Statistical Arbitrage provides useful foundations and statistical methods for managing these strategies. Our experiments explore a different way of making trading decisions while retaining the underlying idea of trading a relative-price relationship.

From Experimental Frameworks to Comparative Strategy Analysis

The project developed through three stages, leading to the two publications discussed below. Each stage changed not only the implementation, but also what we understood a convincing evaluation should look like.

The first stage, an initial experiment in Quantitative Finance, explored three learning environments. Two used discrete action spaces and trading rules that differed from strict pair trading. The third followed pair trading rules with a continuous action space. Here, continuous refers to the range of available actions, such as position sizes, rather than to trading continuously in time. Comparing these settings helped us examine how much the result depended on the way the trading problem was presented to the agent.

One lesson stood out: a single trading path is not enough to judge a stochastic policy. PPO and A2C can sample actions from learned probability distributions, so repeated evaluations can produce different decisions even on the same market history. Repeated simulations, in the spirit of Monte Carlo evaluation, help reveal that variability. They do not create new market histories or replace out-of-sample testing. Even choosing deterministic actions at evaluation time does not remove uncertainty from training or from future market conditions.

The second stage became a conference paper for the 11th Workshop on Engineering Applications, WEA 2024, in Barranquilla, Colombia, with co-authors Diego Leon, Javier Sandoval, and German Hernandez. It also exposed a weakness in our initial assumptions. Drawing on my experience in traditional trading, we had included technical indicators expecting them to help the agent. The later comparison did not support the contribution we had expected in this experimental setting. Familiarity with an indicator was not, by itself, evidence that it added useful information (Quintero et al., 2024).

The third stage, published as a comparative case study, responded to those findings. We removed the technical indicators, redefined the trading signal, and used the Ray framework to tune model hyperparameters, the settings that govern training. The revised approach suggested a modest improvement, which we associated mainly with a signal that helped agents identify opportunities to enter and exit pair trades. Because several parts of the setup changed, this should not be read as proof that the signal alone caused the improvement (Quintero et al., 2025).

The open-source FinRL framework made this work considerably more accessible. It allowed us to inspect the implementation rather than treat the agent as a black box, including its interaction with OpenAI’s gym environment interface. Small changes in how observations, actions, and rewards are connected can materially affect learning. FinRL’s three-layer architecture documentation is a useful starting point for readers who want to explore that structure.

Data

Before an agent could learn to trade, we had to decide which relationships were worth studying. We screened stock-pair combinations using the S&P 500 constituents as of October 17, 2022, applying statistical tests and a selection measure to identify candidates. The screening took several hours on my laptop, but it gave the experiments a defined starting universe rather than an arbitrary collection of pairs.

The studies use a subset of five stock pairs, with the dataset covering 2018–2023. The first publication provides the selection details. Keeping the same universe in the second study made the comparison more informative, although pair selection remains part of the strategy and must be considered when interpreting historical results.

The two publications below trace the move from an experimental DRL framework to a more focused comparison with classical mean reversion.


Conference paper and paper

📘 Phase 1: Experimental DRL Framework for Pair Trading

The first publication, Reinforcement Learning Model Applied in a Pair Trading Strategy, appeared in the Springer WEA 2024 proceedings. The full chapter describes the experimental framework and its comparison with a classical strategy.

🧪 Highlights

The framework explored three customized RL environments over the five selected stock pairs, treating trading as a single-agent control task. In other words, one decision-maker controlled the trading actions rather than delegating the two sides of the pair to separate agents.

In the continuous-action formulation, the agent could choose both position direction and size, rather than select only from a small menu of fixed trades. Technical indicators were included in the initial setup as information for decision-making. These inputs should be distinguished from the action space itself, which describes what the agent is allowed to do.

The reward function used portfolio value with trading costs deducted. This matters because a strategy can appear attractive before costs while losing its advantage through frequent trading. The learning objective therefore needed to reflect the cost of acting, not only the price movement that followed.

Manual optimization

How long should an agent be allowed to learn? More training sounds like an obvious improvement, but in these experiments it could also mean giving an unstable learning process more time to deteriorate. Before the later automated tuning work, I addressed that question manually by inspecting training diagnostics and choosing a practical training budget.

The four figures below show part of that manual process in the earlier experiment closely connected to the WEA 2024 chapter. They provide additional context on training rather than additional performance results from the published chapter. The original curves, axes, and highlighted regions are retained, with colors adapted to this site’s dark theme.

The experiment used a heuristic approach to hyperparameter selection, guided by the behavior of training metrics rather than an exhaustive search. Agents were retrained in rolling windows with a 63-trading-day rebalance interval, approximately three months. Here, the training budget is the number of environment steps used to train an agent, not the number of market days in an evaluation period. Replaying a historical window during training can generate many more learning steps than that window contains observations.

A2C: looking for instability in the actor and critic

For A2C, I examined policy loss and value loss together. Policy loss is the objective used to update the actor, the network that determines the agent’s actions. Its sign and magnitude are not measures of trading profit, and a lower number is not automatically a better strategy. What mattered here was the change in behavior: increasingly large, erratic fluctuations were a warning that continuing training deserved scrutiny.

A2C policy loss for A–AVGO fluctuates around zero, with much larger oscillations later in training. The original rounded highlight marks the early training region considered during manual selection.
Figure 1. A2C policy loss for A–AVGO in the beta-balanced environment, which links position sizing across the two assets. The highlighted early region was considered alongside value loss when choosing a training budget. Horizontal coordinates are training steps, not trading dates.

Value loss measures the discrepancy between the critic’s estimate of expected cumulative reward and the return targets used in training. It provides another view of the same learning process. A small value loss can be encouraging, but a sudden collapse toward zero does not, by itself, prove that the agent has learned a useful trading policy.

A2C value loss for A–AVGO has large early spikes inside the original rounded highlight, falls close to zero, and shows intermittent spikes later in training.
Figure 2. A2C value loss for the same pair and environment. The original highlight identifies the early region inspected manually. Neither a near-zero loss nor an isolated spike is sufficient to judge the trading strategy.

Read together, these plots motivated keeping the A–AVGO A2C training budget at or below approximately 480,000 steps in this experiment. The final configuration used 450,000 training steps for both A2C and PPO. These were practical choices for that setup, not universal stopping thresholds. In particular, value loss need not rise before learning succeeds or fall to zero when it fails. Its interpretation depends on the reward scale, the targets, and the behavior of the policy.

PPO: balancing policy changes against value prediction

For PPO, the manual inspection focused on approximate Kullback–Leibler (KL) divergence and explained variance. Approximate KL divergence estimates how much the action distribution changes between the previous policy and an updated policy. Larger values indicate larger policy changes. In this experiment, a marked increase was treated as a reason to question whether additional training was still producing controlled improvements.

PPO approximate KL divergence for AAP–SO stays relatively low early in training, rises around 300,000 steps, and becomes larger and noisier as training continues toward 1.5 million steps.
Figure 3. PPO approximate KL divergence for AAP–SO in the beta-balanced environment. The rise shows larger changes between policy updates. It is a training diagnostic, not direct evidence of random decisions or worsening investment returns.

Explained variance asks a complementary question: how well does the critic account for variation in its return targets? For targets with nonzero variance, it is commonly expressed as $1-\operatorname{Var}(G-\hat{V})/\operatorname{Var}(G)$, where $G$ is the training return target and $\hat{V}$ is the critic’s prediction. A value near one indicates small residual variance relative to target variance. A value near zero indicates little variance explained, while a negative value means the residual variance exceeds the variance of the targets themselves. These are learning targets based on rewards, not a measure of how much stock-return variation the strategy predicts.

PPO explained variance for AAP–SO remains near zero early on, rises sharply after roughly 250,000 steps, and then levels off above 0.8 with occasional downward dips.
Figure 4. PPO explained variance for the same pair and environment. The critic's fit improves substantially before later gains become smaller. A strong fit to training targets does not establish profitable out-of-sample trading.

Together, the PPO plots show why “train longer” was not a sufficient rule. The critic could explain much more of its target variation while policy updates were also becoming larger. The manual decision was to weigh those signals together rather than maximize one metric in isolation.

The broader lesson is that training diagnostics help investigate learning, but they do not replace strategy evaluation. The experiment also compared trading outcomes using 1,000 simulated action trajectories for each evaluated agent, reflecting the variability of stochastic policies. Those repetitions sampled decisions on historical data, not 1,000 independent market histories. Manual inspection helped narrow the training choices, but claims about a trading advantage still require cost-aware evaluation on data not used to select those choices.

✅ Results

PPO produced the most consistent performance among the tested RL models in terms of Sharpe ratio, a measure of excess return relative to return variability, and cumulative return, the compounded change in value over the evaluation period. A2C and Deep Deterministic Policy Gradient (DDPG) showed greater variability, highlighting how sensitive the outcome could be to hyperparameters and reward design.

The central result was more cautious than a compelling backtest might suggest: the RL models did not consistently outperform the classical pair trading method. Learning a policy was possible, but that alone did not establish an advantage over a simpler rule.


🚀 Phase 2: Comparative Study of A2C and PPO, but with new signal

The follow-up article, Deep Reinforcement Learning in Continuous Action Spaces for Pair Trading: A Comparative Study of A2C and PPO, appeared in SN Computer Science in 2025. The full article asks whether a revised signal and more structured trading decisions could improve on the first phase.

🧠 Methodology

Rather than change the stock universe, we changed how the trading opportunity was represented. The new signal was adjusted using a moving average over the preceding month to reduce the influence of a changing local trend. This gave the agents a different view of deviations relevant to entering and exiting a pair trade.

We also removed the previously included technical indicators and revised the environment so that continuous actions were bounded according to the strategy’s trading bands. A trading band identifies a region of the signal associated with a trading response. The agent retained flexibility within the permitted range, but no longer had the same freedom to act regardless of that context.

The comparison again used the classical mean-reversion strategy as a benchmark. That reference point is essential: improving on an earlier RL experiment is not the same as improving on a practical alternative.

📊 Key Results

Both A2C and PPO partially outperformed the benchmark, improving on the first phase without establishing consistent superiority over the classical method. The word partially is important. It describes a qualified result within the experiments, not evidence that either agent should be expected to win across pairs, evaluation criteria, or future market conditions.

PPO showed faster convergence, meaning that its learning settled more quickly, and lower drawdowns, the declines from a previous portfolio-value peak. Bounding the action space by trading band also helped the learning process. Taken together, these findings suggest that representing the trading problem clearly can matter as much as choosing a sophisticated algorithm.


🔁 Summary of Contributions

The table brings the two publications together. The underlying data universe and cost-aware reward remained common reference points, while the second phase narrowed the algorithm comparison and refined the decision-making setup. Read the final row as a summary of these experiments, not as a general ranking of RL against classical trading.

Feature Phase 1 Phase 2
Environment Design ✅ Custom built ✅ Reused and validated
DRL Algorithms Tested A2C, PPO, DDPG A2C, PPO
Dataset S&P500 subset, 2018–2023 S&P500 subset, 2018–2023
Reward Design Portfolio Value, including costs Portfolio Value, including costs
Benchmark Comparison ✅ Yes, (mean-reversion) ✅ Yes (mean-reversion)
Real-world Pair Trading Viability No outperforms classical method Partially outperforms classical method

The main progression is therefore not from “RL fails” to “RL wins.” It is from a broad prototype to a more disciplined test of when a learned policy may add value. The partial improvement is worth investigating, but it does not remove the need for repeated evaluation, realistic costs, and testing beyond the conditions used to develop the strategy.


🔮 Future Directions

One next step is to explore multi-agent frameworks, in which separate agents could coordinate the long and short sides of a trade. That would change the control problem rather than simply replace one algorithm with another, so the value of coordination would need to be tested against the existing single-agent setup.

Another direction is to examine market microstructure features, such as order book signals and bid/ask spreads. These describe trading conditions more directly than prices alone and could help connect a decision to its execution costs. Technical indicators also deserve a controlled impact analysis. Their limited contribution in this setup does not establish that they are unhelpful in every setting.

Finally, transformer architectures offer another way to model sequences of observations. Their inclusion would be a research question, not an assumed upgrade. Across all these directions, the standard should remain the same: does the added complexity deliver a robust improvement over a simpler, cost-aware benchmark?


📂 Resources

For the full experimental details, start with the experimental framework chapter and then the comparative DRL study. Code and data are not yet linked here and can be requested.


📚 Full References 📢

  1. Quintero, C., Leon, D., Sandoval, J., & Hernandez, G. (2024). Reinforcement Learning Model Applied in a Pair Trading Strategy. In J. C. Figueroa-García, F. S. Garay-Rairán, G. J. Hernández-Pérez, & Y. Díaz-Gutierrez (Eds.), Applied Computer Science in Engineering (Vol. 2094, pp. 29–42). Springer Nature Switzerland. https://doi.org/10.1007/978-3-031-74595-9_3
  2. Quintero, C., Leon, D., Sandoval, J., & Hernandez, G. (2025). Deep Reinforcement Learning in Continuous Action Spaces for Pair Trading: A Comparative Study of A2C and PPO. SN Computer Science, 6(3), 348. https://doi.org/10.1007/s42979-025-03854-0