EPAT Final Project by Jacques Joubert

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

Statistical Arbitrage Strategy in R

By Jacques Joubert

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.


For those of you who have been following my blog posts for the last 6 months will know that I have taken part in the Executive Programme in Algorithmic Trading offered by QuantInsti.

It’s been a journey and this article serves as a report on my final project focusing on statistical arbitrage, coded in R. This article is a combination of my class notes and my source code.

I uploaded everything to GitHub in order to welcome readers to contribute, improve, use, or work on this project. It will also form part of my Open Source Hedge Fund project on my blog QuantsPortal

History of Statistical Arbitrage

First developed and used in the mid 1980s by Nunzio Tartaglia’s quantitative group at Morgan Stanly

  • Pair Trading is a “contrarian strategy” designed to harness mean-reverting behavior of the pair ratio
  • David Shaw, founder of D.E Shaw & Co, left Morgan Stanley and started his own “Quant” trading firm in the late 1980s dealing mainly in pair trading

What is Pair Trading?

Statistical arbitrage trading or pairs trading as it is commonly known is defined as trading one financial instrument or a basket of financial instruments – in most cases to create a value neutral basket.

It is the idea that a co-integrated pair is mean reverting in nature. There is a spread between the instruments and the further it deviates from its mean, the greater the probability of a reversal.

Note however that statistical arbitrage is not a risk free strategy. Say for example that you have entered positions for a pair and then the spread picks up a trend rather than mean reverting.

The Concept

Step 1: Find 2 related securities

Find two securities that are in the same sector / industry, they should have similar market capitalization and average volume traded.

An example of this is Anglo Gold and Harmony Gold.

Step 2: Calculate the spread

In the code to follow I used the pair ratio to indicate the spread. It is simply the price of asset A / price asset B.

Step 3: Calculate the mean, standard deviation, and z-score of the pair ratio / spread.

Step 4: Test for co-integration

In the code to follow I use the Augmented Dicky Fuller Test (ADF Test) to test for co-integration. I set up three tests, each with a different number of observations (120, 90, 60), all three tests have to reject the null hypothesis that the pair is not co-integrated.

Step 5: Generate trading signals

Trading signals are based on the z-score, given they pass the test for co-integration. In my project I used a z-score of 1 as I noticed that other algorithms that I was competing with were using very low parameters. (I would have preferred a z-score of 2, as it better matches the literature, however it is less profitable)

Step 6: Process transactions based on signals

Step 7: Reporting

R markdown for my project

Import packages and set directory

The first step is always to import the packages needed.

This strategy will be run on shares listed on the Johannesburg Stock Exchange (JSE). Because of this I won’t be using the quantmod package to pull data from Yahoo Finance, instead I have already gotten and cleaned the data that I stored in a SQL database and then moved to csv files on the Desktop.

I added all the pairs used in the strategy to a folder which I now set to be the working directory. (If you are connecting from GitHub then you will want to set the working directory to where you stored the file)

Functions that will be called from within other functions (No user interaction)

Next: I create all the functions that will be needed to run the strategy. The functions below will be called from within other functions so you dont need to worry about their arguments.


The AddColumns function is used to add columns to the dataframe that will be needed to store variables.


The PrepareData function calculates the pair ratio and the log10 prices of the pair. It also calls the AddColumns funtion within it.


The GenerateRowValue function Calculates the mean, standard deviation and the z-score for a given row in the dataframe.


The GenerateSignal function creates a long, short, or close signal based on the z-score. You can manually change the z-score. I have set it to 1 and -1 for entry signals and any z-score between 0.5 and -0.5 will create a close/exit signal.


The GenerateTransactions function is responsible for setting the entry and exit prices for the respective long and short positions needed to create a pair.

Note: QuantInsti taught us a very specific way of backtesting a trading strategy. They used excel to teach strategies and when I coded this strategy I used a large part of the excel methodology.

Going forward however I would explore other ways of storing variabels. One of the great things about this method is that you can pull the entire dataframe and analyze why a trade was made and all the details pertaining to it.



The next two arguments are used to generate reports. A report includes the following: Charting:

  1. An Equity curve
  2. Drawdown curve
  3. Daily returns bar chart


  1. Annual Returns
  2. Annualized Sharpe Ratio
  3. Maximum Drawdown
  4. Total trades
  5. Success ratio
  6. PnL ratio


  1. Top 5 Drawdowns and their duration

Note: If you have some extra time then you can further break this function down into smaller functions in order to reduce the lines of code and improve userbility. Less code = Less Bugs

Functions that the user will pass parameters to

The next two functions are the only functions that the user should fiddle with.


BacktestPair is used when you want to run a backtest on a trading pair (the pair is passed in via the csv file)

Function’s arguments:

  • pairData = the csv file date
  • mean = the number of observations used to calculate the mean of the spread.
  • slippage = the amount of basis points that act as brokerage as well as slippage
  • adfTest = a boolean value – if the backtest should test for co-integration
  • criticalValue = Critical Value used in the ADF Test to test for co-integration
  • generateReport = a boolean value – if a report must be generated


BacktestPortfolio accepts a vector of csv files and then generates an equaly weighted portfolio.

Function’s arguments:

  • names = an atomic vector of csv file names, example: c(‘DsyLib.csv’, ‘OldSanlam.csv’)
  • mean = the number of observations used to calculate the mean of the spread.
  • leverage = how much leverage you want to apply to the portfolio

Running Backtests

Now we can start testing strategies using our code.

Pure arbitrage on the JSE

When starting this project the main focus was on using statistical arbitrage to find pairs that were co-integrated and then to trade those, however I very quickly realised that the same code could be used to trade shares that had both its primary listing as well as access to its secondary listing on the same exchange.

If both listings are found on the same exchange, it opens the door for a pure arbitrage strategy due to both listings refering to the same asset. Therefore you dont need to test for co-integration.

There are two very obvious examples on the JSE.

First Example Investec:

Primary = Investec Ltd : Secondary = Investec PLC

Investec In-Sample Test (2005-01-01 – 2012-11-23)

Test the following parameters

  • The Investec ltd / plc pair
  • mean = 35
  • Set adfTest = F (Dont test for co-integration)
  • Leverage of x3
Statistical Arbitrage Strategy in R - Performance 1

Investec Out-of-Sample Test (2012-11-23 – 2015-11-23)

Note: if you increase the slippage, you will very quickly kiss profits good bye.

Statistical Arbitrage Strategy in R - Performance 2

Second Example Mondi:

Primary = Mondi Ltd : Secondary = Mondi PLC

Mondi In-Sample Test (2008-01-01 – 2012-11-23)

Test the following parameters

  • The Mondi ltd / plc pair
  • mean = 35
  • Set adfTest = F (Dont test for co-integration)
  • Leverage of x3
Statistical Arbitrage Strategy in R - Performance 3

Mondi Out-of-Sample Test (2012-11-23 – 2015-11-23)

Note: In all of my testing I found that the further down the timeline my data was, the harder it was to make profits on end of day data. I tested this same strategy on intraday data and it has a higher return profile.

Statistical Arbitrage Strategy in R - Performance 4

Statistical Arbitrage on the JSE

Next we will look at a pair trading strategy.

Typically a pair consits of 2 shares that:

  • Share a market sector
  • Have a similar market cap
  • Similar business model and clients
  • Are co-integrated

In all of the portfolios below I use 3x leverage

Contruction Portfolio

In-sample test (2005-01-01 – 2012-11-01)

Statistical Arbitrage Strategy in R - Performance 5

Out-of-sample test (2012-11-23 – 2015-11-23)

Statistical Arbitrage Strategy in R - Performance 6

Insurance Portfolio

In-sample test (2005-01-01 – 2012-11-01)

Statistical Arbitrage Strategy in R - Performance 7

Out-of-sample test (2012-11-23 – 2015-11-23)

Statistical Arbitrage Strategy in R - Performance 8

General Retail Portfolio

In-sample test (2005-01-01 – 2012-11-01)

Statistical Arbitrage Strategy in R - Performance 9

Out-of-sample test (2012-11-23 – 2015-11-23)

Statistical Arbitrage Strategy in R - Performance 10


At the end of all my testing, and trust me – there is a lot more testing I did than what this report, I came to the conclusion that the Pure Arbitrage Strategy has great hope in being used as a retail strategy using real money, but the Pair Trading Strategy is strained and not likely to be used in production in its current form.

More on the Pure Arbitrage Trading Strategy:

I have only found two shares that have duel listings on the same exchange; this means that we can’t allocate large sums of money to the strategy as it will have a high market impact. However we could use multiple exchanges and increase the number of shares used.

More on the Pair Trading Strategy:

  1. The number of observations used in the ADF Tests are largely to blame. The problems is that a test for co-integration has to be done in order to make a claim for statistical arbitrage, however by using 120, 90, and 60 as parameters to the three tests, it is very difficult to find pairs that match the criteria and that will continue in this form for the near future. (Kalman filtering may be useful here)
  2. I haven’t spent a lot of time changing the different parameters like the number of observations in the mean calculation. (This requires further exploration)
  3. From the above sector portfolios we can see that the early years are very profitable but the further down the timeline we go, the lower returns get.
  4. The same is noticed with other portfolios that I didn’t include in this report but is in the R Code file.
  5. I believe that this is due to large institutions using the same bread and butter strategy. You will note (if you spend enough time testing all the strategies) that in 2009 there seems to be a sudden shift in the data to lower returns.
  6. I feel that the end of day data I am using is limiting me and if I were to test the strategy on intraday data then profits would be higher. (I ran one test on intraday data on Mondi and the results were much higher, but I am still to test it on sector portfolios)
  7. This is one of the simpler statistical arbitrage strategies and I believe that if we were to improve on the way we calculate the spread and change some of the entry and exit rules, the strategy would become a more profitable.

If you made it to the end of this article, I thank you and hope that it added some value. This is the first time that I am using Github, so I am looking forward to see if there are any new contributors to the project.

Github repository: https://github.com/Jackal08/QuantInsti-Final-Project-Statistical-Arbitrage

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

Leave a Reply

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