How To Calculate Bollinger Bands in VB.NET?

by bridie_mante , in category: Technical Analysis , 9 months ago

How To Calculate Bollinger Bands in VB.NET?

Facebook Twitter LinkedIn Whatsapp

1 answer

Member

by morton , 9 months ago

@bridie_mante 

To calculate Bollinger Bands in VB.NET, you first need to calculate the simple moving average (SMA) and the standard deviation of the closing prices of a stock or financial instrument.


Here is a simple example of how you can calculate Bollinger Bands in VB.NET:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Class BollingerBandsCalculator
    Private prices As List(Of Double)
    Private period As Integer
    Private k As Double

    Public Sub New(prices As List(Of Double), period As Integer, k As Double)
        Me.prices = prices
        Me.period = period
        Me.k = k
    End Sub

    Public Function CalculateBollingerBands() As List(Of List(Of Double))
        Dim bands As New List(Of List(Of Double))

        For i As Integer = 0 To prices.Count - period
            Dim sma As Double = CalculateSMA(i)
            Dim standardDeviation As Double = CalculateStandardDeviation(i, sma)

            Dim upperBand As Double = sma + k * standardDeviation
            Dim lowerBand As Double = sma - k * standardDeviation

            bands.Add(New List(Of Double) From {upperBand, lowerBand})
        Next

        Return bands
    End Function

    Private Function CalculateSMA(index As Integer) As Double
        Return prices.GetRange(index, period).Average()
    End Function

    Private Function CalculateStandardDeviation(index As Integer, sma As Double) As Double
        Dim sum As Double = prices
                        .GetRange(index, period)
                        .Select(Function(price) Math.Pow(price - sma, 2))
                        .Sum()

        Return Math.Sqrt(sum / period)
    End Function
End Class


You can then create an instance of the BollingerBandsCalculator class with the list of closing prices, the period for the moving average, and the value of k for the standard deviation multiplier. Finally, call the CalculateBollingerBands method to get a list of upper and lower Bollinger Bands for each data point.