Hi,
I have modified the code as described here: https://www.amibroker.com/kb/2014/12/04/how-to-display-correlation-between-symbols/ to display correlation of prices or returns.
// How to display correlation between symbols
//-------------------------------------------
/// @link https://www.amibroker.com/kb/2014/12/04/how-to-display-correlation-between-symbols/
// To use the formula we need to do the following:
// (1) select Tools -> Send to Analysis menu
// (2) in the Analysis window, Apply to: Filter
// (in Include tab hit Clear and choose the CORRECT watchlist)
// (3) CHOOSE YOUR PARAMETER SETTINGS
// (4) select Range: 1 recent bar(s)
// (5) make sure you clicked on the CORRECT watchlist on the LHS
// (6) press Explore button
//===============================
// CHOOSE
// Watchlist Number
WLN = Param( "WLN#", 63, 1, 1000, 1);
// Correlation Period
range = Param( "Periods", 757, 0, 2000, 1);
//===============================
// read the list of symbols from Watchlist WLN
symlist = CategoryGetSymbols( categoryWatchlist, WLN );
// display only last bar from the Analysis range
Filter = Status( "lastbarinrange" );
SelectedIndicator = ParamList( "Prices_OR_Returns", "Prices,Returns", 1 );
// iterate through symbols
for ( i = 0; ( sym = StrExtract( symlist, i ) ) != ""; i++ )
{
switch ( SelectedIndicator )
{
case "Prices":
//===============================
// Correlation of PRICES
Corr = Correlation( C, Foreign( sym, "C" ), range );
break;
case "Returns":
//===============================
// Correlation of RETURNS
Var1 = Foreign( sym, "C" );
Var1ret = ROC( Var1, 1 );
// calculate correlation RETURNS over range bars
Corr = Correlation( ROC( C, 1 ), Var1ret, range );
break;
}
//===============================
// set color dynamically based on correlation values
// and display the output in exploration column
Clr = 32 + SelectedValue( Corr ) * 32;
AddColumn( Corr, sym, 1.2,
ColorHSB( 128 + Clr, 255, 255 ),
ColorHSB( Clr, 255, 255 ) );
}
SetSortColumns( 1 );
I have 3 questions:
- How do I sort the matrix so that there are 1's on the leading diagonal ?
- The question of do I use prices or returns for analysis? There's an interesting discussion: http://www.portfolioprobe.com/2011/01/12/the-number-1-novice-quant-mistake/ , however I would be very interested to hear views on which to use and when and why?
- In the above code how do I show significance of correlation coefficients? Ideally a highlight of values or a star next to them or some other away?
The t-stat is:
t-stat = (r * sqrt( n-2) ) / sqrt ( 1 -( r^2) ), where
r = correlation coefficient
n = sample size
For large degrees of freedom the t-tends to the normal, so values of +/-1.96, apply for 95% significance.
Also, there's a p-value https://onlinecourses.science.psu.edu/stat501/node/259
Thanks.