Backtest your Pair Trading Strategies – Amibroker AFL code

Pair Trading is a neutral strategy which involves two stocks/indices with opposite positions at any given point of time to profit from any kind of market situations. The pair trading was pioneered by Gerry Bamberger and later led by Nunzio Tartaglia’s quantitative group at Morgan Stanley in the 1980s.

Algortihmic Pair Trading

Today, pairs trading is often conducted using algorithmic trading strategies(Rule based) on an Execution Management System. These strategies are typically built around mathematical models that define the spread based on historical data mining and analysis. The algorithm monitors for deviations in price, automatically buying and selling to capitalize on market inefficiencies. The advantage in terms of reaction time allows traders to take advantage of tighter spreads.

Challenge in Backtesting PAIR Trading Strategy

One of the main Challenge in backtesting a trading pair is most of Commercially available technical software doesnt supports pair trading backtesting and so implementing model based pair trading is really a challenge for retail traders.

Pair Trading in Amibroker

By Default Amibroker doesnt supports pair trading. However there are certain ways we can backtest a trading pair with few disadvantages. will explain more in details about how to backtest amibroker pair trading strategies and the disadvantages involved in it. In this example i had choosen Nifty and Bank nifty as trading pair where 2 lots of nifty and 2 lots of bank nifty is involved and Rs400 as brokerage inclusive of taxes for one buy and sell transaction of 2lots of Nifty and Banknifty pair.

Steps involved in Backtesting a Trading Pair

1)Download Pair Trading Amibroker AFL code
2)Unzip and Place under amibroker\formulas\system folder. Edit the code to set the trading pair symbols in the code. in my case ($NIFTY-NSE, $BANKNIFTY-NSE) and also set the trade size under the function setpositionsize function. You have to edit the code with your own pair trading symbols in your amibroker database(Without Editing the symbols in the AFL code you cant do backtesting.

if( Name() == “$NIFTY-NSE” )
Buy = EntrySignal;
Sell = ExitSignal;
Short= Sell;
Cover = Buy;

SetPositionSize( 100, spsShares ); //set your no of shares size for Symbol1

if( Name() == “$BANKNIFTY-NSE” )
Short = EntrySignal;
Cover = ExitSignal;
Buy = Cover;
Sell = Short;

SetPositionSize( 50, spsShares ); //set your no of shares size for Symbol2

3)Make sure you have enough backfill data for Nifty and Banknifty for the period you are planning to backtest. In our case we backtested the trading pair on EOD timeframe sine 2008. Also ensure the data is 100% free from wrong ticks/spikes.
4)Now open Amibroker and Goto New Analysis if you are using amibroker version 5.4 and above. You have to use Auto Analysis(AA) in case if you are using lower version.

5)Now Add Nifty and Bank Nifty in a Watchlist(in my case it is list 1)

6)Set the backtest settings and symbol information settings as shown below

Now goto New Analysis and Set Apply to as Filter and in the filter select the list 1 from the watchlist section. And also select Portfolio Backtesting from the backtesting inverted triangle option.

Backtest Settings

i)Initial Capital – Rs4,00,000
ii)Positions – Long/Short
iii)Periodicity – Daily(you can choose your own timeframe)
iv)Min Shares – 50
v)Enable Futures Mode
vi)Per Trade Commisions as Rs100/Leg. i.e Rs400 for one buy and sell side transaction for two lots Nifty and Banknifty.
vii)Account Margin as 10%

Symbol Information Settings

Now Open Nifty Chart from the symbol menu select Information. And in the symbol information go to contract specification and enter Round Lot Size = 50, Margin Deposit = -10 (negative sign represents the percentage terms).

Now Open BankNifty Chart from the symbol menu select Information. And in the symbol information go to contract specification and enter Round Lot Size = 20, Margin Deposit = -10 (negative sign represents the percentage terms).

7)Now goto New Analysis Window and press the scan button this will push the Ratio Charts(Banknifty/Nifty) to the Composite symbol ~Pair which you can find in the symbols after performing the scan and which has to be done pre-backtesting.

Banknifty-Nifty Ratio Charts
Banknifty - Nifty Ratio Charts

8)Long/Short Pair Trade Rules : System will choose Nifty long and Bank nifty short if there is a positive EMA crossover and Nifty short and Bank nifty short simultaneously if there is a negative EMA crossover. The AFL condition is shown below

EntrySignal = Cross(EMA(C3,2),C3);
ExitSignal = Cross(C3,EMA(C3,2));

9)Now Press the backtest Button to get complete backtest reports.

Backtested Results of Nifty-Banknifty Pair Trading since 2008 on EOD timeframe
Backtest Results

1)Here the backtested performance is shown for inidividual nifty and Banknifty trades as the One Pair Trade is considered as two trades(One Long/Short of Bank nifty and nifty). So the performance of the system is represented as individual instrument level not at pair trade level.

Portfolio Equity Curve for the Nifty/Banknifty Pair Trades
1. Portfolio Equity

1)Able to capture the system risk involved in the Pair Trading
2)Able to capture the Equity Curve of the Trading system and Test for profitability of the system

Download Backtest Results for the Nifty/Banknifty Pair Trades since 2008

Related Readings and Observations

  • How to do Portfolio Backtesting in Amibroker Portfolio Trading (Trading with Multiple Stocks/Instruments) is the next big step in a traders life once he understand that he want to reduce the volatility in his trading strategy. And […]
  • Supertrend V3.0 AFL code with Buy and Sell Alerts Supertrend V3.0 is the upgraded version of Supertrend Indicator. The trading logic remains the same however lot of bugs got removed and few features added in the current version. Multiple […]
  • N Bar High-Low Dots – Amibroker AFL code Here is a simple strategy that alerts by plotting dots over the candle whenever a new N bar high-low is made. The below chart shows Nifty future EOD charts and the Yellow dots in this […]
  • William VIX FIX Indicator – Amibroker AFL Code We know that VIX most of the time reflects the investor/traders sentiment. When VIX is higher it means lot of fear in the market and lower VIX indicates lack of fear in the market. The […]


    • says

      You need to have enough idea about Pair Trading. IF you havent gone through Pair Trading then it is a technique to find deviation between two highly correlated pairs within the same sector(for ex TCS and INFY) and play a simple mean reversion with the spread. i,e long and one stock and short in another stock of same sector.

Leave a Reply

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