Instead of troubleshooting your example, I am posting the code I experimented with as well as an Excel spreadsheet I used to verify the results from the code below:
Here is my code (it should look familiar):
Code: Select all
Vars: stockNetChange(0), indexNetChange(0), pairCovariance(0), indexVariance(0),beta(0);
If BarStatus = 2 Then Begin
stockNetChange =(close[0] of data1 - close[1] of data1)/(Close[1] of data1) * 100; //Stock
indexNetChange =(close[0] of data2- close[1] of data2)/(close[1] of data2) * 100; //Index
pairCovariance =Covar(stockNetChange,indexNetChange,100);
indexVariance=Variance(indexNetChange,100);
beta=pairCovariance/indexVariance;
Print(Date,",",NumToStr(stockNetChange,6),",",NuMToStr(indexNetChange,6),
",",NumToStr(pairCovariance,6),",",NumToStr(indexVariance,6),",",NumToStr(Beta,6));
End;
plot11(beta);
For each bar, this will print out the date, the stock's net change, the index's net change, the covariance between the two going back 100 days, the index variance going back 100 days and the calculated beta.
In the attached Excel spreadsheet I show the output of this code using AAPL as my stock and SPY as my index. If you scroll to the bottom of the spreadsheet, you will see that the resulting calculations tie out exactly.
Hope this helps.
P.S. You'll note that my formula for net change is different from yours but the numbers shouldn't cause any difference between MultiCharts and Excel.