package finance

import "math"

// BollingerBands calcula las bandas de Bollinger: upper, middle (SMA), lower.
// Los primeros period-1 elementos de cada slice son 0.
func BollingerBands(data []float64, period int, numStdDev float64) (upper, middle, lower []float64) {
	n := len(data)
	upper = make([]float64, n)
	middle = make([]float64, n)
	lower = make([]float64, n)
	if period <= 0 || period > n {
		return
	}
	for i := period - 1; i < n; i++ {
		var sum float64
		for j := i - period + 1; j <= i; j++ {
			sum += data[j]
		}
		mean := sum / float64(period)
		var variance float64
		for j := i - period + 1; j <= i; j++ {
			diff := data[j] - mean
			variance += diff * diff
		}
		std := math.Sqrt(variance / float64(period))
		middle[i] = mean
		upper[i] = mean + numStdDev*std
		lower[i] = mean - numStdDev*std
	}
	return
}
