Assistance Required for coding Pairs Trading AFL

pankajpari

RSITradeMaster
#1
Hi,
I have been studying Pairs since the last 2-3 months and find that this market neutral strategy can give small but consistent profits.

I need assistance of the seniors / experts in AmiBroker to code 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 wont be any lossesif 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.

Thanks.
 

pankajpari

RSITradeMaster
#2
AFL for Pairs Trading

Hey Guys,
Waited for the assistance from the seniors / experts but I guess they missed this post. So finally I put on my thinking cap and VOILA!!! I did it.

I successfully coded (actually modified) this AFL. I, by no means, want to take full credit for the same and would like to mention that base AFL was posted by one Mr. Gopinathan C on another forum around 6 months back. I also went thru a few other AFLs available on the AmiBroker Forum.

For those interested in the same, I am posting the AFL. You may find it very raw (some of the coding could have been better though) but pls understand that I am no expert in this field...... Most importantly, this AFL fully meets my requirement. So here it goes :

********************************************************

_SECTION_BEGIN("Pankaj Parimal - Pairs Trade");

// Enter the Variables Here

Mkt= ParamStr("Independent Scrip (A)", "<'Enter Independent Scrip'>");//Enter the other Scrip (henceforth 'Scrip A') of the Pair as per the NSE Nomenclature by right clicking the mouse and selecting 'Parameters'.

//Independent Scrip is the one with higher Volatility of the 2 scrips. But if one scrip is an Index, then the Index will become the Independent Scrip. Again, if both the scrips of the pair are Indices, then the one with the higher Volatility will be the Independent Scrip.

//Time Frame to be used is 'Daily'.

Period=5;//Enter the required Period for the calculation of Correlation, Spread and Averages

Observations=58;//Enter the No. of Observations for the calculation of R-Squared, Beta & Alpha

Std=0.5;//Enter the required Standard Deviation


//***Base Market************/

P=Foreign(Mkt,"C",1);//Closing Price of Independent Scrip (A) Entered Above

PH=Foreign(Mkt,"H",1);//High Price of Independent Scrip (A) Entered Above

PL=Foreign(Mkt,"L",1);//Low Price of Independent Scrip (A) Entered Above




//Description Calculation of R-Squared :
//R-Squared, which is an indicator for the validity of the Beta and Alpha measures.
//This is because the R-Squared value measures just how closely the Scrip tracks the Index with which it is being compared.
//An R-Squared value of 1.0 indicates a perfect match. In that case, one can trust that the Beta and Alpha measures are valid.
//But, the lower the R-Squared is, the less reliable the Beta and the Alpha measures are.
//The Beta and Alphas of a Scrip with an R-Squared value of below 0.50 are completely meaningless and hence should be ignored.
//Assuming the R-Squared is, say, 0.75 OR higher, one can move on to the Beta.


/***Spread****************/

AvgC=Sum(C,Period)/Period;//Average of Scrip B over a Set Period

AvgP=Sum(P,Period)/Period;//Average of Scrip A

Spr=P-C;//Spread of Scrip A & Scrip B (Difference of Closing Price of Scrip A & Scrip B)

Mspread=Sum(Spr,Period)/Period;//Average or Mean Spread of Scrip A & Scrip B

//Finding Max. & Min. Spread in the Last 10 Days, 20 Days & 30 Days
MaxSpr01=Max(Spr,Ref(Spr,-1));
MaxSpr23=Max(Ref(Spr,-2),Ref(Spr,-3));
MaxSpr45=Max(Ref(Spr,-4),Ref(Spr,-5));
MaxSpr67=Max(Ref(Spr,-6),Ref(Spr,-7));
MaxSpr89=Max(Ref(Spr,-8),Ref(Spr,-9));

MaxSpr10=Max(MaxSpr01,MaxSpr23);
MaxSpr20=Max(MaxSpr45,MaxSpr67);
MaxSpr30=Max(MaxSpr10,MaxSpr20);

MaxSpr10D=Max(MaxSpr30,MaxSpr89);//Max. Spread in the Last 10 Days

MaxSpr1011=Max(Ref(Spr,-10),Ref(Spr,-11));
MaxSpr1213=Max(Ref(Spr,-12),Ref(Spr,-13));
MaxSpr1415=Max(Ref(Spr,-14),Ref(Spr,-15));
MaxSpr1617=Max(Ref(Spr,-16),Ref(Spr,-17));
MaxSpr1819=Max(Ref(Spr,-18),Ref(Spr,-19));

MaxSpr11=Max(MaxSpr1011,MaxSpr1213);
MaxSpr21=Max(MaxSpr1415,MaxSpr1617);
MaxSpr31=Max(MaxSpr11,MaxSpr21);

MaxSpr41=Max(MaxSpr31,MaxSpr1819);
MaxSpr20D=Max(MaxSpr10D,MaxSpr41);//Max. Spread in the Last 20 Days

MaxSpr2021=Max(Ref(Spr,-20),Ref(Spr,-21));
MaxSpr2223=Max(Ref(Spr,-22),Ref(Spr,-23));
MaxSpr2425=Max(Ref(Spr,-24),Ref(Spr,-25));
MaxSpr2627=Max(Ref(Spr,-26),Ref(Spr,-27));
MaxSpr2829=Max(Ref(Spr,-28),Ref(Spr,-29));

MaxSpr12=Max(MaxSpr2021,MaxSpr2223);
MaxSpr22=Max(MaxSpr2425,MaxSpr2627);
MaxSpr32=Max(MaxSpr12,MaxSpr22);

MaxSpr42=Max(MaxSpr32,MaxSpr2829);
MaxSpr30D=Max(MaxSpr20D,MaxSpr42);//Max. Spread in the Last 30 Days

MinSpr01=Min(Spr,Ref(Spr,-1));
MinSpr23=Min(Ref(Spr,-2),Ref(Spr,-3));
MinSpr45=Min(Ref(Spr,-4),Ref(Spr,-5));
MinSpr67=Min(Ref(Spr,-6),Ref(Spr,-7));
MinSpr89=Min(Ref(Spr,-8),Ref(Spr,-9));

MinSpr1=Min(MinSpr01,MinSpr23);
MinSpr2=Min(MinSpr45,MinSpr67);
MinSpr3=Min(MinSpr1,MinSpr2);

MinSpr10D=Min(MinSpr3,MinSpr89);//Min. Spread in the Last 10 Days

MinSpr1011=Min(Ref(Spr,-10),Ref(Spr,-11));
MinSpr1213=Min(Ref(Spr,-12),Ref(Spr,-13));
MinSpr1415=Min(Ref(Spr,-14),Ref(Spr,-15));
MinSpr1617=Min(Ref(Spr,-16),Ref(Spr,-17));
MinSpr1819=Min(Ref(Spr,-18),Ref(Spr,-19));

MinSpr11=Min(MinSpr1011,MinSpr1213);
MinSpr21=Min(MinSpr1415,MinSpr1617);
MinSpr31=Min(MinSpr11,MinSpr21);

MinSpr41=Min(MinSpr31,MinSpr1819);
MinSpr20D=Min(MinSpr10D,MinSpr41);//Min. Spread in the Last 20 Days

MinSpr2021=Min(Ref(Spr,-20),Ref(Spr,-21));
MinSpr2223=Min(Ref(Spr,-22),Ref(Spr,-23));
MinSpr2425=Min(Ref(Spr,-24),Ref(Spr,-25));
MinSpr2627=Min(Ref(Spr,-26),Ref(Spr,-27));
MinSpr2829=Min(Ref(Spr,-28),Ref(Spr,-29));

MinSpr12=Min(MinSpr2021,MinSpr2223);
MinSpr22=Min(MinSpr2425,MinSpr2627);
MinSpr32=Min(MinSpr12,MinSpr22);

MinSpr42=Min(MinSpr32,MinSpr2829);
MinSpr30D=Min(MinSpr20D,MinSpr42);//Min. Spread in the Last 30 Days

RanC=H-L;//Range of Scrip B for the day

RangeC=Sum(RanC,Period)/Period;//Average Range of Scrip B over a Set Period

RanP=PH-PL;//Range of Scrip A for the day

RangeP=Sum(RanP,Period)/Period;//Average Range of Scrip A over a Set Period

Deviation=(RangeC+RangeP)/2*Std;//Sum of Average range of Scrip A and Scrip B Divided by 2 and then Multiplied by the Standard Deviation

UpperSpr=Mspread+Deviation;

LowerSpr=Mspread-Deviation;

Cspread=P-C;//Current Spread using (positive or negative) Difference between Scrip A & Scrip B

Corr5=Correlation(Max(P,C),Min(P,C),5);//5 D Correlation

Corr3=Correlation(Max(P,C),Min(P,C),3);//3 D Correlation

Corr30=Correlation(Max(P,C),Min(P,C),30);//30 D Correlation

Corr1Y=Correlation(Max(P,C),Min(P,C),365);//1 Year Correlation

Corr2Y=Correlation(Max(P,C),Min(P,C),730);//2 Year Correlation

Corr3Y=Correlation(Max(P,C),Min(P,C),1095);//3 Year Correlation


/***R-Squared*************/
R2=Corr5^2;


blsh=Cspread>UpperSpr;

bhsl=Cspread<LowerSpr;

Buy=bhsl;

Sell=blsh;

Plot(Mspread,"Mean Spread",colorBlue,styleDashed);

Plot(UpperSpr,"Upper Spread",colorGreen,styleLine);

Plot(Cspread,"Current Spread",ParamColor("Color",colorBlack),styleNoTitle | ParamStyle("Style"));

Plot(LowerSpr,"Lower Spread",colorRed,styleLine);

//Plot(MaxSpr,"Max. Spread",colorViolet,styleLine);

//Plot(MinSpr,"Min. Spread",colorCustom12,styleLine);

Title=EncodeColor(colorCustom12)+"Independent Scrip (A) is " +EncodeColor(colorBlue)+StrFormat(Mkt)+EncodeColor(colorBlack) +" AND "+
EncodeColor(colorCustom12)+"Dependent Scrip (B) is " +EncodeColor(colorBlue)+"'"+Name()+"'."+" "+
EncodeColor(colorOrange)+"[Key in the 'Independent' Scrip (A) by right-clicking the mouse & Selecting 'Parameters'.]"+"\n"+
EncodeColor(colorBlue)+"High Priced Scrip "+"("+WriteVal(Max(p,C),format=1.2)+");"+" "+
EncodeColor(colorBrown)+"Low Priced Scrip "+"("+WriteVal(Min(C,p),format=1.2)+");"+"\n"+
EncodeColor(colorViolet) +"Correlation [5 Day] "+ "("+WriteVal(Corr5,format=1.2)+");"+EncodeColor(colorBlue) +" R-Squared "+"("+WriteVal(R2,format=1.2)+");"+"\n"+
EncodeColor(colorTeal) +"Correlation [3 Day] "+ "("+WriteVal(Corr3,format=1.2)+");"+EncodeColor(colorCustom12) +" Correlation [30 Day] "+ "("+WriteVal(Corr30,format=1.2)+");"+"\n"+
EncodeColor(colorBlue) +"Correlation [1 Year] "+ "("+WriteVal(Corr1Y,format=1.2)+");"+EncodeColor(colorBrown) +" Correlation [2 Year] "+ "("+WriteVal(Corr2Y,format=1.2)+");"+
EncodeColor(colorGreen) +" Correlation [3 Year] "+ "("+WriteVal(Corr3Y,format=1.2)+");"+"\n"+"\n"+
EncodeColor(colorCustom12) +WriteIf(Cspread>UpperSpr,"Recommendation : "+EncodeColor(colorRed) +"[CS > US] - "+EncodeColor(colorBlue) +"Buy Low Priced Scrip & Sell High Priced Scrip",
WriteIf(Cspread<LowerSpr,"Recommendation : "+EncodeColor(colorGreen) +"[CS < LS] - "+EncodeColor(colorBlue) +"Buy High Priced Scrip & Sell Low Priced Scrip",
"Recommendation : "+EncodeColor(colorBlue) +"Wait - Do Not Trade"))+" "+"\n"+"\n"+
EncodeColor(colorGreen) +"Upper Spread "+"("+WriteVal(UpperSpr,format=1.2)+");" + EncodeColor(colorBlue) +" Mean Spread "+"("+WriteVal(Mspread,format=1.2)+");"+
EncodeColor(colorRed) +" Lower Spread "+"("+WriteVal(LowerSpr,format=1.2)+");"+EncodeColor(colorViolet) +" Current Spread "+"("+WriteVal(Cspread,format=1.2)+")"+"\n"+
EncodeColor(colorViolet) +"Max. Spread [10 Day] "+"("+WriteVal(MaxSpr10D,format=1.2)+");" + EncodeColor(colorCustom12) +" Min. Spread [10 Day] "+"("+WriteVal(MinSpr10D,format=1.2)+");"+"\n"+
EncodeColor(colorViolet) +"Max. Spread [20 Day] "+"("+WriteVal(MaxSpr20D,format=1.2)+");" + EncodeColor(colorCustom12) +" Min. Spread [20 Day] "+"("+WriteVal(MinSpr20D,format=1.2)+");"+"\n"+
EncodeColor(colorViolet) +"Max. Spread [30 Day] "+"("+WriteVal(MaxSpr30D,format=1.2)+");" + EncodeColor(colorCustom12) +" Min. Spread [30 Day] "+"("+WriteVal(MinSpr30D,format=1.2)+");";

Filter=1;//Corr>= 0.6018;

AddColumn( P, "Scrip A", 1.2 );

AddColumn( C, "Scrip B", 1.2 );

AddColumn( Corr5, "Correlation [5 Day]", 1.2 );

AddColumn( Corr3, "Correlation [3 Day]", 1.2 );

AddColumn( Corr30, "Correlation [30 Day]", 1.2 );

AddColumn( Corr1Y, "Correlation [1 Year]", 1.2 );

AddColumn( Corr2Y, "Correlation [2 Year]", 1.2 );

AddColumn( Corr3Y, "Correlation [3 Year]", 1.2 );

AddColumn( bhsl, "Buy High Sell Low"); //Buy High Priced Scrip and Sell Low Priced Scrip

AddColumn( blsh, "Buy Low Sell High"); // Buy Low Priced Scrip and Sell High Priced Scrip

PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, LowerSpr, Offset=-100);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0, LowerSpr, Offset=-110);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0, LowerSpr, Offset=-105);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, UpperSpr, Offset=100);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0, UpperSpr, Offset=110);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0, UpperSpr, Offset=-105);

_SECTION_END();

***************************************************

Disclaimer (just as a precautionary measure) :
This AFL is for academic purpose only. Kindly do not use this AFL for trading purpose unless you are fully aware of how to trade pairs and its consequences. Pls note that Pairs Trading also involves Risk and if not traded properly can lead to huge losses. However, those of you who decide to use it for Trading, will do so at their own risk and the Author(s) of this AFL are in no way responsible for any losses they incur.:D

All the very best. Do reply if you have any suggestions.

Also, anyone interested in Pairs Trading can ask their queries. (Though I may not be able to provide much support if the queries are on the AFL). I will try my level best to answer all the queries with whatever little knowledge that I have. Seniors / Experts on this topic are welcome to the share their knowledge for the benefit of all.
 
#3
Re: AFL for Pairs Trading

Hey Guys,
Waited for the assistance from the seniors / experts but I guess they missed this post. So finally I put on my thinking cap and VOILA!!! I did it.

I successfully coded (actually modified) this AFL. I, by no means, want to take full credit for the same and would like to mention that base AFL was posted by one Mr. Gopinathan C on another forum around 6 months back. I also went thru a few other AFLs available on the AmiBroker Forum.

For those interested in the same, I am posting the AFL. You may find it very raw (some of the coding could have been better though) but pls understand that I am no expert in this field...... Most importantly, this AFL fully meets my requirement. So here it goes :

********************************************************

_SECTION_BEGIN("Pankaj Parimal - Pairs Trade");

// Enter the Variables Here

Mkt= ParamStr("Independent Scrip (A)", "<'Enter Independent Scrip'>");//Enter the other Scrip (henceforth 'Scrip A') of the Pair as per the NSE Nomenclature by right clicking the mouse and selecting 'Parameters'.

//Independent Scrip is the one with higher Volatility of the 2 scrips. But if one scrip is an Index, then the Index will become the Independent Scrip. Again, if both the scrips of the pair are Indices, then the one with the higher Volatility will be the Independent Scrip.

//Time Frame to be used is 'Daily'.

Period=5;//Enter the required Period for the calculation of Correlation, Spread and Averages

Observations=58;//Enter the No. of Observations for the calculation of R-Squared, Beta & Alpha

Std=0.5;//Enter the required Standard Deviation


//***Base Market************/

P=Foreign(Mkt,"C",1);//Closing Price of Independent Scrip (A) Entered Above

PH=Foreign(Mkt,"H",1);//High Price of Independent Scrip (A) Entered Above

PL=Foreign(Mkt,"L",1);//Low Price of Independent Scrip (A) Entered Above




//Description Calculation of R-Squared :
//R-Squared, which is an indicator for the validity of the Beta and Alpha measures.
//This is because the R-Squared value measures just how closely the Scrip tracks the Index with which it is being compared.
//An R-Squared value of 1.0 indicates a perfect match. In that case, one can trust that the Beta and Alpha measures are valid.
//But, the lower the R-Squared is, the less reliable the Beta and the Alpha measures are.
//The Beta and Alphas of a Scrip with an R-Squared value of below 0.50 are completely meaningless and hence should be ignored.
//Assuming the R-Squared is, say, 0.75 OR higher, one can move on to the Beta.


/***Spread****************/

AvgC=Sum(C,Period)/Period;//Average of Scrip B over a Set Period

AvgP=Sum(P,Period)/Period;//Average of Scrip A

Spr=P-C;//Spread of Scrip A & Scrip B (Difference of Closing Price of Scrip A & Scrip B)

Mspread=Sum(Spr,Period)/Period;//Average or Mean Spread of Scrip A & Scrip B

//Finding Max. & Min. Spread in the Last 10 Days, 20 Days & 30 Days
MaxSpr01=Max(Spr,Ref(Spr,-1));
MaxSpr23=Max(Ref(Spr,-2),Ref(Spr,-3));
MaxSpr45=Max(Ref(Spr,-4),Ref(Spr,-5));
MaxSpr67=Max(Ref(Spr,-6),Ref(Spr,-7));
MaxSpr89=Max(Ref(Spr,-8),Ref(Spr,-9));

MaxSpr10=Max(MaxSpr01,MaxSpr23);
MaxSpr20=Max(MaxSpr45,MaxSpr67);
MaxSpr30=Max(MaxSpr10,MaxSpr20);

MaxSpr10D=Max(MaxSpr30,MaxSpr89);//Max. Spread in the Last 10 Days

MaxSpr1011=Max(Ref(Spr,-10),Ref(Spr,-11));
MaxSpr1213=Max(Ref(Spr,-12),Ref(Spr,-13));
MaxSpr1415=Max(Ref(Spr,-14),Ref(Spr,-15));
MaxSpr1617=Max(Ref(Spr,-16),Ref(Spr,-17));
MaxSpr1819=Max(Ref(Spr,-18),Ref(Spr,-19));

MaxSpr11=Max(MaxSpr1011,MaxSpr1213);
MaxSpr21=Max(MaxSpr1415,MaxSpr1617);
MaxSpr31=Max(MaxSpr11,MaxSpr21);

MaxSpr41=Max(MaxSpr31,MaxSpr1819);
MaxSpr20D=Max(MaxSpr10D,MaxSpr41);//Max. Spread in the Last 20 Days

MaxSpr2021=Max(Ref(Spr,-20),Ref(Spr,-21));
MaxSpr2223=Max(Ref(Spr,-22),Ref(Spr,-23));
MaxSpr2425=Max(Ref(Spr,-24),Ref(Spr,-25));
MaxSpr2627=Max(Ref(Spr,-26),Ref(Spr,-27));
MaxSpr2829=Max(Ref(Spr,-28),Ref(Spr,-29));

MaxSpr12=Max(MaxSpr2021,MaxSpr2223);
MaxSpr22=Max(MaxSpr2425,MaxSpr2627);
MaxSpr32=Max(MaxSpr12,MaxSpr22);

MaxSpr42=Max(MaxSpr32,MaxSpr2829);
MaxSpr30D=Max(MaxSpr20D,MaxSpr42);//Max. Spread in the Last 30 Days

MinSpr01=Min(Spr,Ref(Spr,-1));
MinSpr23=Min(Ref(Spr,-2),Ref(Spr,-3));
MinSpr45=Min(Ref(Spr,-4),Ref(Spr,-5));
MinSpr67=Min(Ref(Spr,-6),Ref(Spr,-7));
MinSpr89=Min(Ref(Spr,-8),Ref(Spr,-9));

MinSpr1=Min(MinSpr01,MinSpr23);
MinSpr2=Min(MinSpr45,MinSpr67);
MinSpr3=Min(MinSpr1,MinSpr2);

MinSpr10D=Min(MinSpr3,MinSpr89);//Min. Spread in the Last 10 Days

MinSpr1011=Min(Ref(Spr,-10),Ref(Spr,-11));
MinSpr1213=Min(Ref(Spr,-12),Ref(Spr,-13));
MinSpr1415=Min(Ref(Spr,-14),Ref(Spr,-15));
MinSpr1617=Min(Ref(Spr,-16),Ref(Spr,-17));
MinSpr1819=Min(Ref(Spr,-18),Ref(Spr,-19));

MinSpr11=Min(MinSpr1011,MinSpr1213);
MinSpr21=Min(MinSpr1415,MinSpr1617);
MinSpr31=Min(MinSpr11,MinSpr21);

MinSpr41=Min(MinSpr31,MinSpr1819);
MinSpr20D=Min(MinSpr10D,MinSpr41);//Min. Spread in the Last 20 Days

MinSpr2021=Min(Ref(Spr,-20),Ref(Spr,-21));
MinSpr2223=Min(Ref(Spr,-22),Ref(Spr,-23));
MinSpr2425=Min(Ref(Spr,-24),Ref(Spr,-25));
MinSpr2627=Min(Ref(Spr,-26),Ref(Spr,-27));
MinSpr2829=Min(Ref(Spr,-28),Ref(Spr,-29));

MinSpr12=Min(MinSpr2021,MinSpr2223);
MinSpr22=Min(MinSpr2425,MinSpr2627);
MinSpr32=Min(MinSpr12,MinSpr22);

MinSpr42=Min(MinSpr32,MinSpr2829);
MinSpr30D=Min(MinSpr20D,MinSpr42);//Min. Spread in the Last 30 Days

RanC=H-L;//Range of Scrip B for the day

RangeC=Sum(RanC,Period)/Period;//Average Range of Scrip B over a Set Period

RanP=PH-PL;//Range of Scrip A for the day

RangeP=Sum(RanP,Period)/Period;//Average Range of Scrip A over a Set Period

Deviation=(RangeC+RangeP)/2*Std;//Sum of Average range of Scrip A and Scrip B Divided by 2 and then Multiplied by the Standard Deviation

UpperSpr=Mspread+Deviation;

LowerSpr=Mspread-Deviation;

Cspread=P-C;//Current Spread using (positive or negative) Difference between Scrip A & Scrip B

Corr5=Correlation(Max(P,C),Min(P,C),5);//5 D Correlation

Corr3=Correlation(Max(P,C),Min(P,C),3);//3 D Correlation

Corr30=Correlation(Max(P,C),Min(P,C),30);//30 D Correlation

Corr1Y=Correlation(Max(P,C),Min(P,C),365);//1 Year Correlation

Corr2Y=Correlation(Max(P,C),Min(P,C),730);//2 Year Correlation

Corr3Y=Correlation(Max(P,C),Min(P,C),1095);//3 Year Correlation


/***R-Squared*************/
R2=Corr5^2;


blsh=Cspread>UpperSpr;

bhsl=Cspread<LowerSpr;

Buy=bhsl;

Sell=blsh;

Plot(Mspread,"Mean Spread",colorBlue,styleDashed);

Plot(UpperSpr,"Upper Spread",colorGreen,styleLine);

Plot(Cspread,"Current Spread",ParamColor("Color",colorBlack),styleNoTitle | ParamStyle("Style"));

Plot(LowerSpr,"Lower Spread",colorRed,styleLine);

//Plot(MaxSpr,"Max. Spread",colorViolet,styleLine);

//Plot(MinSpr,"Min. Spread",colorCustom12,styleLine);

Title=EncodeColor(colorCustom12)+"Independent Scrip (A) is " +EncodeColor(colorBlue)+StrFormat(Mkt)+EncodeColor(colorBlack) +" AND "+
EncodeColor(colorCustom12)+"Dependent Scrip (B) is " +EncodeColor(colorBlue)+"'"+Name()+"'."+" "+
EncodeColor(colorOrange)+"[Key in the 'Independent' Scrip (A) by right-clicking the mouse & Selecting 'Parameters'.]"+"\n"+
EncodeColor(colorBlue)+"High Priced Scrip "+"("+WriteVal(Max(p,C),format=1.2)+");"+" "+
EncodeColor(colorBrown)+"Low Priced Scrip "+"("+WriteVal(Min(C,p),format=1.2)+");"+"\n"+
EncodeColor(colorViolet) +"Correlation [5 Day] "+ "("+WriteVal(Corr5,format=1.2)+");"+EncodeColor(colorBlue) +" R-Squared "+"("+WriteVal(R2,format=1.2)+");"+"\n"+
EncodeColor(colorTeal) +"Correlation [3 Day] "+ "("+WriteVal(Corr3,format=1.2)+");"+EncodeColor(colorCustom12) +" Correlation [30 Day] "+ "("+WriteVal(Corr30,format=1.2)+");"+"\n"+
EncodeColor(colorBlue) +"Correlation [1 Year] "+ "("+WriteVal(Corr1Y,format=1.2)+");"+EncodeColor(colorBrown) +" Correlation [2 Year] "+ "("+WriteVal(Corr2Y,format=1.2)+");"+
EncodeColor(colorGreen) +" Correlation [3 Year] "+ "("+WriteVal(Corr3Y,format=1.2)+");"+"\n"+"\n"+
EncodeColor(colorCustom12) +WriteIf(Cspread>UpperSpr,"Recommendation : "+EncodeColor(colorRed) +"[CS > US] - "+EncodeColor(colorBlue) +"Buy Low Priced Scrip & Sell High Priced Scrip",
WriteIf(Cspread<LowerSpr,"Recommendation : "+EncodeColor(colorGreen) +"[CS < LS] - "+EncodeColor(colorBlue) +"Buy High Priced Scrip & Sell Low Priced Scrip",
"Recommendation : "+EncodeColor(colorBlue) +"Wait - Do Not Trade"))+" "+"\n"+"\n"+
EncodeColor(colorGreen) +"Upper Spread "+"("+WriteVal(UpperSpr,format=1.2)+");" + EncodeColor(colorBlue) +" Mean Spread "+"("+WriteVal(Mspread,format=1.2)+");"+
EncodeColor(colorRed) +" Lower Spread "+"("+WriteVal(LowerSpr,format=1.2)+");"+EncodeColor(colorViolet) +" Current Spread "+"("+WriteVal(Cspread,format=1.2)+")"+"\n"+
EncodeColor(colorViolet) +"Max. Spread [10 Day] "+"("+WriteVal(MaxSpr10D,format=1.2)+");" + EncodeColor(colorCustom12) +" Min. Spread [10 Day] "+"("+WriteVal(MinSpr10D,format=1.2)+");"+"\n"+
EncodeColor(colorViolet) +"Max. Spread [20 Day] "+"("+WriteVal(MaxSpr20D,format=1.2)+");" + EncodeColor(colorCustom12) +" Min. Spread [20 Day] "+"("+WriteVal(MinSpr20D,format=1.2)+");"+"\n"+
EncodeColor(colorViolet) +"Max. Spread [30 Day] "+"("+WriteVal(MaxSpr30D,format=1.2)+");" + EncodeColor(colorCustom12) +" Min. Spread [30 Day] "+"("+WriteVal(MinSpr30D,format=1.2)+");";

Filter=1;//Corr>= 0.6018;

AddColumn( P, "Scrip A", 1.2 );

AddColumn( C, "Scrip B", 1.2 );

AddColumn( Corr5, "Correlation [5 Day]", 1.2 );

AddColumn( Corr3, "Correlation [3 Day]", 1.2 );

AddColumn( Corr30, "Correlation [30 Day]", 1.2 );

AddColumn( Corr1Y, "Correlation [1 Year]", 1.2 );

AddColumn( Corr2Y, "Correlation [2 Year]", 1.2 );

AddColumn( Corr3Y, "Correlation [3 Year]", 1.2 );

AddColumn( bhsl, "Buy High Sell Low"); //Buy High Priced Scrip and Sell Low Priced Scrip

AddColumn( blsh, "Buy Low Sell High"); // Buy Low Priced Scrip and Sell High Priced Scrip

PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, LowerSpr, Offset=-100);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0, LowerSpr, Offset=-110);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0, LowerSpr, Offset=-105);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, UpperSpr, Offset=100);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0, UpperSpr, Offset=110);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0, UpperSpr, Offset=-105);

_SECTION_END();

***************************************************

Disclaimer (just as a precautionary measure) :
This AFL is for academic purpose only. Kindly do not use this AFL for trading purpose unless you are fully aware of how to trade pairs and its consequences. Pls note that Pairs Trading also involves Risk and if not traded properly can lead to huge losses. However, those of you who decide to use it for Trading, will do so at their own risk and the Author(s) of this AFL are in no way responsible for any losses they incur.:D

All the very best. Do reply if you have any suggestions.

Also, anyone interested in Pairs Trading can ask their queries. (Though I may not be able to provide much support if the queries are on the AFL). I will try my level best to answer all the queries with whatever little knowledge that I have. Seniors / Experts on this topic are welcome to the share their knowledge for the benefit of all.
Dear Friend,

Chart is not visible.... and i gave input icicibank and checked no chart nor figures , it onlys wait do not trade= recommendation

How ever kudos on your first afl

Let me know how to use this afl
 

pankajpari

RSITradeMaster
#4
Hi Kedarnath, first of all you need to check if both the scrips are active in AmiBroker, i.e., you need to ensure that the data for that scrip has been fetched from your data provider. In order to check this, you need to first open the normal Price chart of each scrip in a separate window. Once you have done it, you may close these individual charts and then open the Pairs Trade chart.
If you are still not getting the chart, PM me the TV id & password after the market hours tomm. Shall then personally check out the issue.
 
#10
BTW Aloakdutt, what version of AmiBroker do you use?

Not sure if that could be the reason for the same. I have written this code in AmiBroker version 5.50....

Hi Pankapari,

pankajpari has chosen not to receive private messages or may not be allowed to receive private messages. Therefore you may not send your message to him/her.

The is the above message i get when i try to send PM.

Kindly look into it as i have written my TV ID 168541453

Thanks
Aloakdutt:)
 

Similar threads