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.
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”.
Finally succeeded in writing the code for MACD of Spread.
Pls find the link to the AFL for the same.
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 :
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.
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.
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.
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.