Correlation() with variable range

How would something like this be implemented ? I get how amibroker uses arrays but I totally feel lost when it comes to thinking a work around. Can I get some advise on getting it started ?

Thanks.

bi = BarIndex(); 
S = Cross(MA(C, 4), MA(C,8)); 
c1 = ValueWhen( S, MA(C, 4), 1) > ValueWhen( S, MA(C, 4), 2); 
Range = ValueWhen( S, bi, 1) - ValueWhen( S, bi, 2); 
c2 = Correlation(C, Foreign("APPL", "C"), Range) > 0.7;
Buy = c1 and c2;

You can see the correlation range between the stocks are determined by the two cross over points which always changes. How can this be implemented ?

Built-in Correlation() function requires Range to be scalar (constant number).

Variable period correlation can be coded as follows:

// Variable period correlation
function VarCorrelation( x, y, number )
{
    nom = MA( x * y, number ) - MA( x, number ) * MA( y, number );
    denom = sqrt( MA( x ^ 2, number ) - MA( x, number ) ^ 2 ) *
            sqrt( MA( y ^ 2, number ) - MA( y, number ) ^ 2 );
    return nom / denom;
}

BTW: Use [code] ... your formula [/code] tags !!! I fixed it again but why don’t you read How to use this site first?

4 Likes

Thank you Tomasz for your help.