#include <profile.c>
var Corr(var* Close)
{
var AvgLength = 0;
var M;
var X;
var Y;
var Lag;
var count;
var Sx;
var Sy;
var Sxx;
var Syy;
var Sxy;
var Corr[48];
var* HP = series(HighPass2(Close, 48), 50);
var* Filt = series(Smooth(HP, 10), 50);
//Pearson correlation for each value of lag
for (Lag = 0; Lag < 48; Lag++) {
//Set the averaging length as M
M = AvgLength;
if (AvgLength == 0) M = Lag;
Sx = 0;
Sy = 0;
Sxx = 0;
Syy = 0;
Sxy = 0;
for (count = 0; count < M; count++) {
X = Filt[count];
Y = Filt[Lag + count];
Sx = Sx + X;
Sy = Sy + Y;
Sxx = Sxx + X*X;
Sxy = Sxy + X*Y;
Syy = Syy + Y*Y;
}
if ( (M*Sxx - Sx*Sx)*(M*Syy - Sy*Sy) > 0 ) {
Corr[Lag] = (M*Sxy - Sx*Sy)/sqrt((M*Sxx-Sx*Sx)*(M*Syy-Sy*Sy));
}
}
return Corr[3];
}
function run()
{
set(NFA|PLOTNOW);
StartDate = 20210903;
EndDate = 20210903;
Outlier = 0;
BarPeriod = 1;
LookBack = 100;
BarMode = BR_FLAT;
Verbose = 2;
var* Close = series(priceClose());
var* x = series(Corr(Close));
var* HP = series(HighPass2(Close, 48), 50);
var* Filt = series(Smooth(HP, 10), 50);
var y = Correlation(Filt, Filt+3, 3);
plot("x", x, NEW, RED);
plot("y", y, END, BLUE);
}