# Efficient calculation of bollinger bands (or sliding window standard deviation)

## 2018/08/21

The Bollinger bands used in technical analysis is the +/- 2 * standard deviation of the closing price plotted on the chart. This prices are expected to fluctuate in this band 95% of the time. As with any sliding window calculation the easy way is to calculate everything each time for each window. Which usually means quadratic algorithm. A better way exists to calculate the values for standard deviations using some smart manipulations on the standard deviation formula. (to be more precise the variance formula which is the square of the standard deviation.)

To the variance formula is (k = )  extracting the last constant term independent of i extract the term independent of i from the 2nd part first term and last term can be handled the way moving averages are handle. When the window slides right, add the new term remove the old term on the left. This is efficient. so the middle term becomes now the second term can also be calculated using the efficient method.

Here is an implementation in code for bollinger bands

```    public SuperList calculate() {
double totalAvg = 0d;
double totalSq = 0d;
int i = 0;
SuperList result = new SuperList<>();
for (Double value : values) {
totalAvg += value;
totalSq += value * value;
if (i >= PERIOD - 1) {
double avg = totalAvg / PERIOD;
double stddev = Math.sqrt((totalSq - (totalAvg*totalAvg)/PERIOD)/ PERIOD);
BollingerBand band = new BollingerBand(avg, avg + 2 * stddev, avg - 2 * stddev);