Variance and Covariance

We had a question come in on how to do variance and covariance in scripting. So I thought I would put the answers in here for anyone else who is interested.

Variance

This is simply taking an average and then for each data point measuring the distance from that close to the average. We square the value to remove the sign.

var

// get the rolling daily returns 
r1 = Change(INT_TYPE=Day, INT_COUNT=1);

// Calculate the average
a1 = MA(r1, Bars=5);

// Calc the square of the distance from the average
d1 = r1 - a1;
sd1 = d1 * d1; 

// Average those values - this may need to be 4 bars (n-1) for a sample variance.
v1 = MA(sd1, Bars=5, CALC=Close);

//output v1
v1

Covariance

This is trying to find how two datasets move in parallel. It is the combined variance of x & y from their respective averages. ‚Äč

Note that I have not got anything to compare this with, so let me know if you find examples that show this script to need adjusting.

// Get the SPX Data - if not using Bloomberg change BLMB to WI
g1 = GETDATA(CODE=SPX:BLMB);

// get the rolling daily returns 
r1 = Change(INT_TYPE=Day, INT_COUNT=1);
r2 = Change(g1, INT_TYPE=Day, INT_COUNT=1);

// Calculate the average
a1 = MA(r1, Bars=5);
a2 = MA(r2, Bars=5);

// Calc the product of the distances from the respective averages
d1 = r1 - a1;
d2 = r2 - a2;
sd12 = d1 * d2;

// Average those values by adding them and dividing by n-1
v1 = ACC(sd12, BARS=5, RANGE=Look Back Period, BACKTYPE=Bars) / 4;

v1

Hopefully that helps if you are doing this type of work.