Calculation of bbands

Posted By: johnnyp

Calculation of bbands - 09/14/17 19:02

I have a working strategy in Zorro and I need to code it in MQL4 in order to run it in a context that doesn't permit the use of DLLs. But I am having trouble implementing BBands properly.

Some plotting for testing purposes.
Code:
// compare Bollinger bands separation to StdDev, Moment, and Variance functions
int bbperiod = 10;
BBands(Price,bbperiod,2,2,MAType_SMA);
var bbdist = rRealUpperBand + rRealLowerBand;

var std = StdDev(Price, bbperiod);
plot("STD", 4.*std - bbdist, NEW, RED);
var mom = sqrt(Moment2(Price, bbperiod, 2));
plot("Moment", 4.*mom - bbdist, NEW, RED);
var vari = sqrt(Variance(Price, bbperiod));
plot("Var", 4.*vari - bbdist, NEW, RED);

printf("\nStd %f mom %f var %f", 4.*std-bbdist, 4.*mom-bbdist, 4.*vari-bbdist);


For periods >= 4, StdDev and Variance give the same results, for period = 3 there are three different results.

I may have found a bug in the implementation of Moment in indicators.c ... here is an extract
Code:
// rMean contains the mean over Period values
var variance=0.;
int i;
for(i=0; i<Period; i++) {
	var f = Data[i]-rMean;
	variance += f*f;
}
variance /= (Period-1);


This code takes the sum of Period values and divides that sum by (Period-1). Shouldn't the sum be divided by Period?

I tried a second test with a corrected version of the Moment function. For periods >= 4, StdDev and Variance give the same results, for period = 3 Variance gives the same result as Moment.

In any case, StdDev always gives the closest result. I have tried reading the ta-lib sources but I can't see the difference between Moment and StdDev. Any help would be appreciated.
Posted By: jcl

Re: Calculation of bbands - 09/18/17 11:16

Period-1 is the normally used formula. The difference that I know between Moment and StdDev is that the TA-LIB rounds StdDev down to zero when below 0.0001.
Posted By: johnnyp

Re: Calculation of bbands - 09/18/17 14:52

Some more research reveals that using Period-1 instead of Period is called Bessel's correction.

The justification is that among (x1 - x_mean, ..., xn - x_mean) there are only n-1 independant values because their sum is zero.

A quick inspection of the ta-lib sources suggests that ta-lib uses Period rather than Period-1.
Posted By: firecrest

Re: Calculation of bbands - 09/19/17 03:01

Originally Posted By: johnnyp
Some more research reveals that using Period-1 instead of Period is called Bessel's correction.

The justification is that among (x1 - x_mean, ..., xn - x_mean) there are only n-1 independant values because their sum is zero.

A quick inspection of the ta-lib sources suggests that ta-lib uses Period rather than Period-1.


Interesting as n/(n-1) approaches infinity, n/(n-1) will approach 1.
© 2024 lite-C Forums