Pair Trading Strategy and Backtesting using Quantstrat

Share on Facebook0Tweet about this on Twitter0Share on LinkedIn21Share on Google+0

Pair Trading marco project

By Marco Nicolas Dibo

This article is the final project submitted by the author as a part of his coursework in Executive Programme in Algorithmic Trading (EPAT) at QuantInsti. Do check our Projects page and have a look at what our students are building.


Marco cover picMarco has spent his career as a trader and portfolio manager, with a particular focus in equity and derivatives markets. He specializes in quantitative finance and algorithmic trading and currently serves as head of the Quantitative Trading Desk and Vice-president of Argentina Valores S.A. Marco is also Co-Founder and CEO of Quanticko Trading SA, a firm devoted to the development of high frequency trading strategies and trading software. Marco holds a BS in Economics and an MSc in Finance from the University of San Andrés.


One of my favorite classes during EPAT was the one on statistical arbitrage, so the pair trading strategy seemed a nice idea for me. My strategy triggers new orders when the pair ratio of the prices of the stocks diverge from the mean. But in order to work, we first have to test for the pair to be cointegrated. If the pair ratio is cointegrated, the ratio is mean-reverting and the greater the dispersion from its mean, the higher the probability of a reversal, which makes the trade more attractive. I chose the following pair of stocks:

  • Bank of America (BAC)
  • Citigroup (C)

The idea is the following: If we find two stocks that are correlated (they correspond to the same sector), and the pair ratio diverges from a certain threshold, we short the stock that is expensive and buy the one that is cheap. Once they converge to the mean, we close the positions and profit from the reversal.

Trading Strategy Logic

The logic is simple. The algorithm calculates the daily Z-score for every pair of stocks. The Z-score is the number of standard deviations that the pair ratio has diverged from its mean:

Z = (R – μ) / σ 

Where R is the  price ratio of both stocks, μ is the mean of the ratio and σ is the standard deviation of the price ratio.

Once the Z-score is outside of a certain threshold, we fulfill the first condition required for sending an order.

But the algorithm must also meet a second condition: It calculates the rolling Augmented Dickey Fuller test for the pair of stocks. More specifically, it gets the p-value from the test. Then it compares it with a defined significance level (alpha) and if the p-value is less than the alpha, it means that the price ratio series are stationary and the second condition is met. If both conditions are met, then the algorithm buys the loser and sells the winner. The exit rules apply at a certain Z-score threshold. For the optimization of the strategy the variables that I used were the following:

  1. Z-Score entry thresholds
  2. Z-Score exit thresholds
  3. Second condition (cointegration) True or False

Code details and In-Sample Backtest:

The in-sample period for backtesting was 01-01-2009 till 31-12-2012. The Z-score was calculated using the following parameters:

  1. Moving average of the price ratio: 20 days
  2. Standard Deviation of the price ratio: 20 days
  3. ADF test window: 60 days
  4. Initial Equity = 100.000 USD
  5. Buy/Sell quantities of spread = 3000

When we short the spread we are selling “C” and buying “BAC” and when we buy the spread we are doing the opposite. I used quantstrat library [1] for backtesting the strategy. Let us dive into the code:

marco project pic 1

Join EPAT!

As mentioned earlier, I will use quantsrat library for the optimization of my strategy. In order to use quantstrat we first have to define and initialize instruments, strategy, portfolio, account and orders:

Then we calculate and add to the strategy our two indicators to the strategy:

– Z-Score

– ADF Test (True or False)

In the following chart we can see the evolution of the Z-score during the period and the possible values for the threshold where the ratio reverts to the mean and the extreme values. I set some lines in the +/-2 Z-score threshold, where it seems to be a reversal of the pair ratio. This value of the z-score means that the pair ratio is +/- standard deviations from its mean.

marco pic 2

Now we set our optimization variables:

marco pic 8

As we can see from our summary there are 2 indicators, 7 signals and 3 rules defined in our strategy. Now we can run the backtest, check the transactions and the performance of our strategy.

The optimization was done with the following values for the variables:

marco pic 3

From the in-sample backtest we got the following results:

marco pic 4

From this table we can get the values for the variables that optimize the strategy. At first sight it seems that there are 3 candidates (case 4, case 6 and case 8). If we compare between cases 6 and 8 we arrive to the conclusion that case 8 is the best one as it has a greater annualized Sharpe ratio and profit to max drawdown, a higher percentage of positive trades, a greater end equity and with the same number of trades. So now we are left with only 2 candidates: 4 and 8. If we would only be checking for the one with the greatest annualized Sharpe ratio, we would prefer case 4. Case 8 also doesn’t take into account that the series must be cointegrated, and case 4 does, so this would be another plus for case 4. But if we take into account the number of transactions, the profit to max drawdown, the end equity, the percentage of positive trades and the fact that the difference in the Sharpe ratio is not a big difference we would definitely select case 8 as our best candidate.

Join EPAT!

Out of Sample Backtest:

Now that we have optimized the strategy and obtained the optimal values for the parameters, we can run an out of sample blacktest and see how the strategy performs. The out of sample period for the back test goes from the 01-01-2013 to the 31-12-2015 and the optimized values for the thresholds and rules were the following:

  • Z-Score Buy Threshold = -2
  • Z-Score Sell Threshold = 2
  • Z-Score Long Exit Threshold = -1
  • Z-Score Short Exit Threshold = 1
  • ADF Test = False

The following chart show us the different transactions, the end equity and the drawdown results for our strategy:

marco pic 5

From the table below we can see that the results from the out of sample backtest are not as good as the ones we got from the in sample backtest.

marco pic 6


The annualized Sharpe ratio is still positive but smaller than the 3.52 that we got before. The profit to max drawdown is quite worse than the 4.23 but the max drawdown decreased from 16327 to 8641. Our strategy delivers a cumulative return of 16.04% and annualized return of 5.08% during the three years that it was deployed.

marco pic 7


The idea when I started the Executive Program in Algorithmic trading was to learn how to model a quantitative trading strategy, backtest it and then optimize it. Thanks to my professors and QuantInsti staff I feel that the objective was accomplished. Everything in the course was excellent and would recommend it to everyone interested in learning algorithmic trading.

Next Steps

For understanding the statistics behind Pair Trading, Correlation and Cointegration, have a look at our post here. Learn the application of mean reversion and optimising trading parameters using this Excel Downloadable model. 

If you are a coder or a tech professional looking to start your own automated trading desk. Learn automated trading from live Interactive lectures by daily-practitioners. Executive Programme in Algorithmic Trading covers training modules like Statistics & Econometrics, Financial Computing & Technology, and Algorithmic & Quantitative Trading. Enroll now!

Share on Facebook0Tweet about this on Twitter0Share on LinkedIn21Share on Google+0

One thought on “Pair Trading Strategy and Backtesting using Quantstrat

  1. September 19, 2016

    Vikas Reply

    How can we do ADF test in Excel

Leave a Reply

Your email address will not be published. Required fields are marked *