Topic: Learning Section
Pankaj Parimal
View Profile

AmiBroker AFL for Pairs Trading

From : Pankaj Parimal at 11:57 AM - Aug 17, 2012 ( )
Total Views: 6002
7 , 24 Bookmark

Share it on Facebook

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 - - 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 "" 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 |
1 to 20 out of 31 | First | << Previous | Next >> | Last |
(1) 2

Login to participate in discussion.

Recently Discussed Posts of Pankaj Parimal

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