[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

code for correlation



PureBytes Links

Trading Reference Links

Rus Newton is certainly correct in pointing out that the correlation
function in TS4.0 is wrong.  This seems surprising since the code for the
closely related regression of Variable y on Variable x is correct for the
special case in which Variable x is bar number.  The following code for
correlation was written by Geoffrey Ihle, who was then my programmer.  I
believe it to be correct.  It is a shorter code than would be needed for
some of the more complex, but algebraically equivalent ,computational
formulas.-   Lorenzo

{ GCORRELAT2 -- Calculates CORRELATION COEFFICIENT BETWEEN
	INDEP AND DEP (THE INDEPENDENT AND DEPENDENT VARIABLES)
	OVER "LENGTH" BARS.
	WRITTEN 3/22/97}

inputs: INDEP(NUMERICSeries), DEP(NumericSeries), LENGTH(NUMERIC);
Vars: CTR(0), AVEX(0), AVEY(0), SXX(0), SYY(0), SXY(0);

AVEX = AVERAGE(INDEP, LENGTH);
AVEY = AVERAGE(DEP, LENGTH);

SXY = 0; 
SXX = 0;
SYY = 0;

{PRINT(" ");
print(Indep[Length-1], Dep);
print(Average(Indep,Length));
PRINT("AVERAGE X = ", AVEX:4:4, " AVERAGE Y = ", AVEY:4:4);
}
FOR CTR = 1 TO LENGTH BEGIN
{	PRINT("INDEP = ", INDEP[LENGTH-CTR]:4:4, " DEP = ", DEP[LENGTH - CTR]:4:4);}
	SXY = SXY + (INDEP[CTR-1] - AVEX) * (DEP[CTR-1] - AVEY);
	SXX = SXX + (INDEP[CTR-1] - AVEX) * (INDEP[CTR-1] - AVEX);
	SYY = SYY + (DEP[CTR-1] - AVEY) * (DEP[CTR-1] - AVEY);
	END;

{PRINT("SXX = ", SXX:4:4, " SYY = ", SYY:4:4, " SXY = ", SXY:4:4);
}
IF SXX <> 0 AND SYY <> 0 THEN
	GCORRELAT2 = SXY/(SQUAREROOT(SXX) * SQUAREROOT(SYY))
	ELSE
	GCORRELAT2 = 0;