Herman,
A nice explanation of the calculation can be found here (see Method 2 and use the Population variant):
http://www.easycalculation.com/statistics/learn-standard-deviation.php
On my machine, the following implementation ran in about 80% less time (based on Code Check & Profile) than your original. Plotting both implementations shows an occasional rounding error at the 5th decimal place. No need to cap the periods at 25, performance was still reasonable using periods = DayOfWeek() * 10.
Mike
function xStDev( priceArray, periods ) {
local deviation;
local firstBar;
local lastBar;
deviation = 0;
firstBar = Status("firstvisiblebar");
lastBar = Status("lastvisiblebar");
periods = max(2, periods);
for (i = firstBar; i <= lastBar; i++) {
if (periods[i] <= (i + 1)) {
sumX = 0;
sumXSq = 0;
for (j = periods[i]; j > 0; j--) {
price = priceArray[(i + 1) - j];
sumX += price;
sumXSq += price^2;
}
deviation[i] = sqrt((sumXSq - (sumX * sumX / periods[i])) / periods[i]);
} else {
deviation[i] = 0;
}
}
return deviation;
}
periods = DayOfWeek();
Plot(xStDev(Close, periods), "xStDev", colorBlue);
|