How To Calculate Bollinger Bands using Ruby?

Member

by maci , in category: SEO Tools , 9 months ago

How To Calculate Bollinger Bands using Ruby?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

2 answers

A

Administrator

by admin , 9 months ago

@maci You can use the code below to calculate bollinger bands using Ruby programming language:

 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
require 'csv'
require 'statistics2'


def calculate_bollinger_bands(data, window_size, num_standard_deviations)
  bands = []
  data.each_cons(window_size) do |window|
    middle_band = window.sum / window_size.to_f
    standard_deviation = Statistics2.standard_deviation(window)
    upper_band = middle_band + num_standard_deviations * standard_deviation
    lower_band = middle_band - num_standard_deviations * standard_deviation
    bands << [upper_band, middle_band, lower_band]
  end
  bands
end


# Example usage:
# Load data from CSV file (assuming the first column is the price data)
data = CSV.read('your_data.csv', converters: :numeric).transpose[0]


# Set parameters
window_size = 20
num_standard_deviations = 2


# Calculate Bollinger Bands
bollinger_bands = calculate_bollinger_bands(data, window_size, num_standard_deviations)


# Display the Bollinger Bands
puts "Upper Band, Middle Band, Lower Band"
bollinger_bands.each do |band|
  puts "#{band[0]}, #{band[1]}, #{band[2]}"
end


You can find the actual values bollinger bands to compare on https://finquota.com/GOOGL/ or similar websites.

Member

by jamison , 9 months ago

@maci 

To calculate Bollinger Bands using Ruby, you can follow these steps:

  1. Import the required libraries:
1
require 'finance'


  1. Define a function for calculating Bollinger Bands:
1
2
3
4
5
6
7
8
def calculate_bollinger_bands(data, window_size=20, num_std_dev=2)
  bb = Finance::BollingerBands.new(data, window_size, num_std_dev)
  upper_band = bb.upper_band
  lower_band = bb.lower_band
  middle_band = bb.mid_band

  return upper_band, lower_band, middle_band
end


  1. Prepare the data for calculation:
1
data = [10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]


  1. Call the function with the data:
1
upper_band, lower_band, middle_band = calculate_bollinger_bands(data)


  1. Print the Bollinger Bands values:
1
2
3
puts "Upper Band: #{upper_band}"
puts "Lower Band: #{lower_band}"
puts "Middle Band: #{middle_band}"


This is a simple example of how to calculate Bollinger Bands using the Finance gem in Ruby. Make sure to adjust the parameters according to your specific requirements and data.