Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

Backtest your Pair Trading Strategies – Amibroker AFL code

3 min read

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.

[wp_ad_camp_5]

 

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

Backtest
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

Disadvantages
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

Advantages
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

Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

[Webinar] Understanding and Mitigating Curve Fitting in System Trading

"Understanding and Mitigating Curve Fitting in System Trading"! This dynamic session aims to equip novice to intermediate traders, quantitative analysts, and financial engineers with...
Rajandran R
1 min read

P-Signal Strategy Long Only Strategy – Amibroker AFL Code

This tutorial provides an overview of the P-Signal reversal strategy, a quantitative trading strategy that utilizes statistical parameters and error functions to generate probabilistic...
Rajandran R
2 min read

9 Replies to “Backtest your Pair Trading Strategies – Amibroker AFL code”

    1. HI Ashish,

      Its just a sample prototype strategy to explain simple model based pair trades and yes the strategy shows a Compounded Annual return of 11.61%

    1. 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.

  1. Dear Sir

    I want to learn about pair trading.
    Can you provide any training class.

  2. DEAR SIR
    PLS TEL ME ABOUT MY STRATEGY I HAVE USED SUPER TREND AND HAIEKIN ASHI SUPER TREND DECIDE TREND AND HA GIVE BUY OR SELL SIGNAL WHAT IS THE BACKTESTING REPORT THIS

    2)PLS TELL ME BEST STRATEGY FOR IFTY ADD BANKNIFTY FOR SHORTTERM

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More