Topic: Learning Section
Pankaj Parimal
View Profile

AmiBroker AFL for Pairs Trading

From : Pankaj Parimal at 11:57 AM - Aug 17, 2012 ( )

Total Views: 6938 Share it on Facebook

7 24 Bookmark

Hi, Request all seniors / experts in AmiBroker to help me in coding an AFL for Pairs Trading. Your assistance will be highly appreciated.

Pls find below the details of Pairs Trading and the requirements.

Pairs Trading Background :
1. Pairs Trading is a process of buying the cheaper stock and selling the costly stock simultaneously in the futures segment to benefit from all kinds of market condition.
2. When two correlated stocks are chosen for the trade with market neutral approach then the trading method known as Pairs Trading. Example : ICICI Bank and HDFC Bank both in the private banking sector and have close similarity in the business model.
3. In Pairs Trading, the 2 stocks can be traded in 2 following ways :
a) Mean Reverting Stocks : If the 2 stocks are highly correlated & cointegrated, however far the Spread (between the 2 stocks) moves away (increases) from the Mean Spread, at some point in time it will start moving back towards its Mean. In such pairs, a trade can be entered into whenever the Spread moves (2% or more) away from the Mean and then squared off, when the Spread moves back towards its Mean.
b) Directional Strategies : Pairs that are not Mean Reverting can be traded similar to trading any individual scrip, with the only difference being that the Spread between the two stocks is to be used for trading. We can use Moving Average, MACD, RSI, Pivot Points, Fibonacci, etc., on the Spread.
4. A Spread is the Difference between 2 Stocks (OR 1 Index & 1 Stock OR 2 Indices). This difference should not be an Absolute number, i.e., the differential can be Positive as well as Negative. The advantage of trading Spreads is that it is not as Volatile as the individual scrips. (But this does not mean that there won’t be any losses……if not traded & managed properly, this strategy can lead to huge losses.)
5. Current Spread is the Difference between Last Traded Price (LTP) or Current Market Price (CMP) of the 2 stocks.
6. Mean Spread is the Average Spread [Sum of Spread divided by No. of Observations]
7. Upper Spread is Average Spread multiplied by 102% [Average Spread + (Average Spread x 2%)]
8. Lower Spread is Average Spread multiplied by 98% [Average Spread - (Average Spread x 2%)]
9. Maximum Spread is the Maximum Difference between the 2 stocks over a period of time, say 1 month, 3 months, 1 year, etc.
10. Minimum Spread is the Minimum Difference between the 2 stocks over a period of time, say 1 month, 3 months, 1 year, etc.

Trade Initiation Criteria :-
(we will take the price of SBI - Rs. 1920/-, & ICICI Bank - Rs. 975/-, into consideration as an example)
1. Current Spread > Upper Spread : When the Current Spread trades above the Upper Spread, the following signal should be generated,
Buy Inexpensive Stock and Sell Expensive Stock (Example – Buy ICICI Bank and Sell SBI)
2. Current Spread < Lower Spread : When the Current Spread trades below the Lower Spread, the following signal should be generated,
Buy Expensive Stock and Sell Inexpensive Stock (Example – Buy SBI and Sell ICICI Bank)

AmiBroker Requirements :

I would like to have the following requirements in AmiBroker,
A. The Chart Style should be a Line chart.
B. The AFL should ask the user to select the 2 required scrips.
C. The various Spreads (Lines) should be differently coloured - Current Spread (Black), Mean Spread (Blue), Upper Spread (Brown), Lower Spread (Teal), Maximum Spread (Purple) & Minimum Spread (Magenta / Fuchsia).
D. If the Current Spread is going up, it should be coloured Green and if it is going down, Red.
E. Maximum & Minimum Spread period should be 1 calendar month.
F. An Arrow should be displayed above / below the Current Spread whenever the Buy & Sell signal is generated.
G. The current values of the various Spreads should be displayed on the Right hand side of the X-Axis (Price Margin).
H. A Box should be displayed in one corner of the chart and should include the following,
(i) Buy & Sell Signal as per the position of the Current Spread vis-à-vis the Upper & Lower Spread.
(ii) 3 Year, 1 Year, 30 Day & 5 Day Correlation Coefficients of the 2 scrips.
(iii) Profit or Loss of Individual scrips (Difference of Buy / Sell Price and the Last Traded Price)
(iv) Total Profit or Loss (Net Profit / Loss of both the scrips)

Pls let me know if you require any other information.


From: Pankaj Parimal at 01:46 PM - Sep 11, 2012( )

Find below the link to the updated AFL for Pairs Trading :



Have changed the following :

(i)         I have replaced ‘Independent’ & ‘Dependent’ scrips (which were based of the Annual Volatility of the scrips) to ‘High Priced Scrip’ & ‘Low Priced Scrip’. This is being done to simplify the AFL as many may not know how to find which scrip of the 2 scrips is more volatile. This will also take care of the ‘contradictory recommendations’ as there will be no confusion in selecting the ‘High Priced’ scrip (as compared to selecting the more volatile scrip).

(ii)         I have changed the method to calculate the Upper & Lower Spread. It is now based on +/- 2% of the Mean Spread. This will reduce the number of recommendations received as the distance between the Mean Spread and Upper / Lower Spread will increase. With this method, one will notice that in most of the pairs, 95% of Current Spread is enveloped by the Upper & Lower Spread and hence can be used similar to Bollinger Bands.

(iii)        The variables can now be changed using the Parameters dialog box.

(iv)        The Recommendation will now display the name of the scrips instead of just stating “Buy High Priced Scrip & Sell Low Priced Scrip” or “Buy Low Priced Scrip & Sell High Priced Scrip”.

From: Pankaj Parimal at 08:47 PM - Oct 04, 2012( )

Hey All,
Finally succeeded in writing the code for MACD of Spread.

Pls find the link to the AFL for the same.



From: Pankaj Parimal at 02:39 AM - Oct 05, 2012( )

Another AFL...... RSI of Spread....



Now you have a complete suite of Tools to Trade Pairs :-

(i) Primary AFL for identifying opportunities in Pairs Trading :


(ii) Trend Following AFL (MACD) for identifying the trend of Spread :


(iii) Oscillator AFL (RSI 8 & 21) for identifying Over Bought & Over Sold markets :


From: Pankaj Parimal at 08:02 PM - Nov 23, 2012( )

Dear Seniors / Experts,
Coming back to you for your help. I want the Pairs Trading AFL with Candlestick. Currently the same is a Line Chart.

I tried working on the same using HHV, Highest, TimeFrameGetPrice, etc. functions, but just couldn't code it.

The following is a small brief on the requirement :
(i) A simple code using the difference between the Open, High, Low and Close of one Scrip with that of the second Scrip (like, 'PH - H' or 'PL - L') will not work [H - High of Scrip 1, L - Low of Scrip 1, PH - High of Scrip 2, PL - Low of Scrip 2].

This is becos, even if Scrip 1 is making a high at say, 12:30 PM, Scrip 2 may not make a high at that exact time (though, it is possible that the Scrip 2 may make a high at an earlier or a later time, say at 12:32 PM, but is its highly unlikely that the high will be exactly at 12:30 PM).

(ii) If the chart is seen in a smaller TF, say, 15 minute TF, one can easily notice the Highs & Lows made by the Current Spread during the day. This is unlike viewing the chart in a Daily TF, where we can notice only one price point of the Current Spread at the extreme right of the chart, which is the CMP / LTP of the Current Spread.

Pls find attached the images of 2 charts, one showing the High made (in 15 Minute TF) on 22nd Nov '12 and the other showing the Low made (in 15 Minute TF) on 22nd Nov '12.


You may also download the AFL of the Line Chart from the below mentioned link. (In order to view the chart of 'Line with Dots', go to "View > Price Chart Style > Line with Dots" in AmiBroker.

Pankaj Parimal - Pairs Trade (New Updated).txt - 4shared.com - document sharing - download

The attached images are of the pair - Bank Nifty & SBI. The same can be viewed by first selecting the chart of SBI and then using parameters (by right clicking on the chart) to key in the High Priced Scrip, i.e., Bank Nifty.

If one views the chart in a lower TF, say, 1 Minute TF, we can find a more accurate value of High or Low made by the Current Spread during the day.

Though AmiBroker has various functions like, TimeFrameGetPrice, TimeFrameExpand, TimeFrameCompress, HHV, LLV, Highest, Lowest, HighestVisibleValue, LowestVisibleValue, etc., I am not able to use the same to code this requirement.

(iii) The Open and Close values can be got by a simple code like 'PO - O' and 'PC - C', where PO - Opening Price of Scrip 2, PC - Closing Price of Scrip 2, O - Opening Price of Scrip 1 and C - Closing Price of Scrip 1. [But again, as in the case of High & Low, the Opening and the Closing prices of the 2 scrips may not be executed at the same time and may differ a little.]

Request the Seniors to suggest a better way, if any, of retrieving the Opening & Closing prices of Current Spread.

(iv) Once we have the Open, High, Low & Close values of the Current Spread, we can plot the Candlestick of Current Spread.

I would like to request all the seniors & experts to kindly help me with my requirement.

Pls let me know if you require further explanation or are unable to understand my requirement.

From: Pankaj Parimal at 10:45 PM - Dec 12, 2012( )

Hi All,

Pls find below some more information on Pairs Trading :

Pairs Trading is a process of buying the cheaper stock and selling the costly stock simultaneously in the Futures segment to benefit from all kinds of market condition.
• When two correlated stocks are chosen for the trade with market neutral approach then the trading method is known as Pairs Trading. Example: HDFC Bank and Axis Bank both in the private banking sector and have close similarity in the business model.

• How to choose pair of stocks for trading?
o Both the stocks must be from the same industry.
o Stocks must be a component of a sectorial index.
o Stocks must have a close correlation in business model and business structure.
o Technical Parameters :
 The volatility in annual terms for the pair must not defer by 50%, i.e., if the annual volatility of one stock is 50%, then the other stock should have an annual volatility of more than 25% & less than 75%. A plus / minus 4-5% in the annual volatility of other stock is considered ok.
 The Annual Volatility of both the scrips should be more than 20%.
 The high volatile stock (as per the % Annual Volatility) will be the dominating partner in the pair, i.e., it becomes the Independent Stock (X), while the other becomes the Dependent Stock (Y). But if the pair has one Index and one Stock, then the Index becomes Independent, while the Stock becomes Dependent.
 The correlation coefficient of the pair must exist either in the +ve or –ve zone
 The spread difference between the stock must show some correction

• Important Statistical parameters for pairs trade :
o Correlation Coefficient :
 This statistical parameter gives a value between -1 to +1.
 A Positive correlation means both the stocks in the pair will move in the same direction, while a Negative correlation means both the stocks will move in the opposite direction.
 If the correlation is '0' means both are moving randomly.
 An ideal correlation is +/- 0.6018.
 For Positive Correlation, the recommendation to buy & sell should be followed as is. But in case of Negative Correlation, the recommendation received should be reversed and then traded. This means that if the recommendation received is to [Buy Stock 'A' and Sell Stock 'B'] and in case of Pairs with Negative Correlation, one should do the opposite, i.e, [Buy Stock 'B' and Sell Stock 'A'].

o Hedging Using Options : It is always a good practice to hedge the pairs using Options as Pairs can sometimes lead to huge losses if not managed properly. Though this will reduce the profits, but it will also ensure that the losses are minimised.

Trade Initiation Process : A trade will be initiated if one of the following criteria is met,
o If the Current Spread is above or below 2% of the Mean Spread. (The Current Spread is the price difference between the two stocks.)
o If the correlation changes from + ve to – ve or vice versa.
o If the correlation increases or decreases by 50% from its previous recorded data.

These are the basics of Pairs Trading. Those who are really interested will need to do a lot of research on it and experiment with Paper Trading before actually going ahead with real trades.

I would recommend those interested in Pairs Trading to also visit "http://www.smartfinancein.com/" and register for the free webinars on this topic. They have uploaded on their site some e-books and videos on various strategies including Pairs Trading. (Kindly note that I do not have any commercial interest in recommending Smart Finance. One of my friends recommended me this website and it has immensely helped me.) Further, I would also like to inform that I have read mixed reviews about them and there are a quite a few people who do not find their strategies profitable but it is up to us as to how we can benefit from them. Also, I would like to update that the above mentioned details on Pairs Trading have been taken from a free webinar given by Mr. Soumya Ranjan Panda, the Proprietor of Smart Finance.

In Reply to above Message (1 to 20 out of 31) - Latest Replies are put on Top | First | << Previous | Next >> | Last |

From : Mulesh P at 03:45 PM - Dec 03, 2012 ( )


From : Pankaj Parimal at 01:03 AM - Dec 01, 2012 ( )

hey Mulesh,

checkout the below mentioned link :


From : Mulesh P at 06:25 PM - Nov 30, 2012 ( )

Pankaj Parimal - Pairs Trade (New Updated).txt - 4shared.com - document sharing - download



From : Yograj Jadeja at 08:46 PM - Nov 18, 2012 ( )

ok thanks

i have tested it on Hourly & Daily results is good. i think daily TF is more better.

From : Pankaj Parimal at 07:54 PM - Nov 18, 2012 ( )

Hi Yograj,

Though I use it with Daily TF (since I would like to trade for 3-5 days........giving the trade some room for movement), this AFL can be used with any time frame. But it is better to use it with higher that 30 minutes TF for better results. But I cannot say this with guarantee as I have not tested the same with lower TFs.

From : Yograj Jadeja at 07:25 PM - Nov 18, 2012 ( )

Mr. Pankaj. pls tell which TF is ideal to use this 

From : Pankaj Parimal at 06:55 PM - Nov 18, 2012 ( )

Hi Yograj,

Thnx for your compliments. But I was unable to understand the observations posted by you. Can you pls upload some images and give examples to explain your observations. It will go a long way in making this system robust.

From : Yograj Jadeja at 06:09 PM - Nov 18, 2012 ( )

hi thanks Pankajji for reply

first i though high price should be kept in symbol identical & low price script in parameters.but have look what i have found.

1) Axis icici pair : if i took Identical Axis(in amibroker symbol)(highprice) & icici (low price) into Parameters. then all calls are in good profit. but if taking icici identical (in amibroker symbol) & axis into parameters mostlly all calls turn in loss. so here we can see if high price taken then turning good profitable pair trade.

2nd SBIN & ICICI pair : if u take icici identical ( in amibroker symbol ) & sbin which is high price into parameters then its giving good profitable calls. otherwise not so i think its better to becktest old signals and then decide :p i no its no technicall to selecting like this but its logical :p

by the way many thanks for your afl its o'some.

thanks again yograj

From : Pankaj Parimal at 05:15 PM - Nov 18, 2012 ( )

Hi All, Apologies for the late revert. A very Happy & a Prosperous Diwali to you all and all your family members.

Hi Bulan Sarkar,

Let me check how I can add the exit signal to this AFL. As mentioned earlier, I am not so good at AmiBroker but will try my level best to work on the same.

Would appreciate if you can share the details of the actual trade taken by you. Was it profitable or not. Also, kindly upload the image so that all of us can learn from your trade.

Hi Yograj,

The Current Spread (CS) of the pair is to be found by deducting the Low Priced LTP from the High Priced LTP. If you notice, the Current Spread in the first image is -141.3 (a negative value, which means that in the first image, the CS is calculated by deducting the High Priced LTP from the Low Priced LTP (1103.7 - 1245 = -141.3), which is incorrect).

The second image has the correct CS calculation (1245 - 1095.9 = 149.1).

The reason for this is that in the first image, the Low Priced Scrip (ICICI Bank) was incorrectly entered in 'Parameters' => 'High Priced Scrip' column. While in the second image, the High Priced LTP (Axis bank) was correctly entered in 'Parameters' => 'High Priced Scrip' column.

You will also notice that both the images are Mirror Images and also has the exactly opposite recommendations as the calculation of Current Spread is opposite in both. This is the reason why it is necessary that when you right click and enter the name of the scrip in 'Parameters', we need to enter the name of the High Priced Scrip only and not the Low Priced Scrip. The same is also displayed in the first line of the image. Hope this clarifies your "Kolavari Di".

As regards the Profit, kindly use the MACD and RSI AFLs along with the Pairs Trade AFL. Before entering the Pairs Trade, always check the direction of the trend and the following rules :

(i) When the recommendation is "Current Spread < Lower Spread", the Profits will increase as the Current Spread increases. This will happen in an Up Trend. Also, one needs to enter the trade only when the Current Spread has turned upwards and starts moving towards the Mean Spread.

(If I am not wrong, the Time Frame that you have selected is Hourly. In the first image, you will see that 2 recommendations were received on 7th Nov '12. One should have entered the trade only after the second recommendation was recd and that too after the Current Spread turned upwards. If you see, the first recommendation was received when the CS < LS (Lower Spread) but the CS was still moving downwards and turned upwards only after the second recommendation. This trade would have been profitable only for that day, i.e., in the last hour as the 2nd reco was recd in the last hour. But if I was to trade here, I would have avoided both the recommendations becos the general trend was down. Had you taken the trade and kept it for 2 days for more, the trade would have gone in a major loss due to the Down Trend)

(ii) When the recommendation is "Current Spread > Upper Spread", the Profits will increase as the Current Spread decreases. This will happen in a Down Trend. Also, one needs to enter the trade only when the Current Spread has turned downwards and starts moving towards the Mean Spread.

(In the second image, you will see that 3 recommendations were received on 7th Nov '12. If at all, you had to take this trade, you should have entered the trade only after the second recommendation was recd and that too after the Current Spread turned downwards. If you see, the first recommendation was received when the CS > US (Upper Spread) but the CS was still moving upwards and turned down only after the second recommendation. But if I were to trade here, I would have avoided the first two recommendations and would have taken the third recommendation when the CS was lower than LS (CS < LS) becos the general trend was up.)

In addition to using MACD to find the trend, you can also use Moving Averages to identify the trend........just drag the MA (SMA or EMA or which ever you are comfortable with) and select the Price Field (in Parameters) as "Current Spread" instead of "Close".

Do write back in case of any further clafications.

From : Nirmal Baba at 11:56 AM - Nov 13, 2012 ( )

yes any one solve above sir ji yogi raj qution good pridict bhai and also same worked paire sent plz thanks all is well

From : Yograj Jadeja at 11:41 AM - Nov 13, 2012 ( )

From : Bulan Sarkar at 08:15 PM - Nov 12, 2012 ( )

Hi Pankaj Ji,

May God Bless all of us in this auspecious Diwali!

I am testing your AFL's and matching them with Pairtrade Finder to filter the best trade. Today based on your AFL, I took a real trade in commodity. Shorted ZINCMINI and went long on LEADMINI.

It is very much appriciated that if you also add an EXIT signal in your AFL when spread returns to mean or something like that.

Jai Sri Krishna.

From : Vinubhai Dave at 09:10 PM - Oct 04, 2012 ( )

Thanks Pankajbhai....... Will Try Later........ 

From : Mahadeo Gaikwad at 04:30 PM - Aug 27, 2012 ( )

same problem i am facing

From : Amjad Siddiqui at 04:27 PM - Aug 27, 2012 ( )

Neil bhai done as u told but the problem is same


From : Pankaj Parimal at 01:45 PM - Aug 27, 2012 ( )

Hi Shiv Kumar, I had sent you the details. Pls check.

From : Shiv Kumar at 01:41 PM - Aug 27, 2012 ( )

PM your teamviewer ID & password to me will fix your issue. Smile

From : Pankaj Parimal at 01:39 PM - Aug 27, 2012 ( )

Can someone pls contact the Admin, I am unable to reply to any posts or open any new thread due to the following error :

http://www.mudraa.com/trading/145201/0/amibroker-afl-for-pairs-trading.html /postcomment.php Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; MAMI) We have got some problem. please give us some time to rectify it.

From : Vignesh K at 12:47 PM - Aug 27, 2012 ( )

Hi pankaj and gopinathan sir thank you for posting pair afl .......i have copied afl ,but i cant view graph in amibroker ,other than that i dint get any error......can u help me to solve this by coming through teamviewer when u r free.........same problem as amjad siddique ......thanks in advance sir........

From : Neil S at 12:33 PM - Aug 27, 2012 ( )

go to parameter and add symbol name of 2nd stock


like if you want to pair hdfc bank and icici bank


then 1st select hdfc bank on chart after go to parameter and put icici bank symbol name which is your databse provide


you will get both

1 to 20 out of 31

Login to participate in discussion.

Recently Discussed Posts of Pankaj Parimal

Learning Section >> AmiBroker AFL for Pairs Trading (32)

Learning Section >> Error while replying to a Post / Creating a new Post (1)