// StandardDeviationSinglePass.afl
//
// A function to compute the standard deviation
// of a price series in a single pass.
// AmiBroker implementation by Howard Bandy
// www.BlueOwlPress.com
// November 2011
//
function SDSP( p, LB )
{
// p is the price series beign processed
// LB is the number of bars in the lookback period
// for the calculation of the standard deviation
if ( LB <= 1 )
{
// set standard deviation to zero
// if the lookback period is too short
// to give meaningful results.
Std = 0;
}
else
{
for ( i = 0; i < LB; i++ )
{
// set std dev to zero for the
// bars in the rampup period
Std[i] = 0;
}
for ( i = LB; i < BarCount; i++ )
{
// compute the std dev for all bars
// for each element
// k runs from 1 through LB
// k = 1
x = p[i-LB+1];
mo = x;
so = 0;
// k = 2 through LB
for ( k = 2; k <= LB; k++ )
{
x = p[i-LB+k];
mn = mo + ( x - mo ) / k;
sn = so + ( x - mo ) * ( x - mn );
mo = mn;
so = sn;
} // end for k loop
// for the ith element --
// mo holds the mean (which is not returned)
// so holds the sum of squared differences
// used to compute the variance.
// Divide by LB to get the population variance,
// of by (LB-1) to get the sample variance.
Var = so / LB;
// standard deviation is the square root of the variance
Std[i] = sqrt( Var );
} // end for i loop
}
return( Std );
} // end of function SDSP
// Program to compute and plot the
// standard deviation using two methods.
//
// Plot the candlesticks of price
Plot( C, "C", colorBlack, styleCandle );
// Set the length
LB = 10;
// Use the method built in to AmiBroker
// and plot it as a green line
SDBuiltin = StDev( C, LB );
Plot( SDBuiltIn, "SDBI", colorGreen, styleLine | styleOwnScale, -1, 3 );
// Use the function
// and plot it as a red line
SDSPass = SDSP( C, LB );
Plot( SDSPass, "SDSPass", colorRed, styleLine | styleOwnScale, -1, 3 );
//////////////////////////// end ///////////////////////////////
You need to be loged to make a comment