How To Calculate On-Balance Volume (OBV) in Ruby?

by clyde_reichert , in category: General Help , 8 months ago

How To Calculate On-Balance Volume (OBV) in Ruby?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aglae_feil , 8 months ago

@clyde_reichert 

To calculate On-Balance Volume (OBV) in Ruby, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def calculate_obv(prices, volumes)
  obv = 0
  previous_price = prices[0]
  
  prices.each_with_index do |price, index|
    if price > previous_price
      obv += volumes[index]
    elsif price < previous_price
      obv -= volumes[index]
    end
    previous_price = price
  end
  
  return obv
end

# Example prices and volumes arrays
prices = [100, 105, 110, 108, 115]
volumes = [1000, 1200, 800, 700, 900]

# Calculate OBV
obv = calculate_obv(prices, volumes)
puts "OBV: #{obv}"


In this code, the calculate_obv method takes two arrays as input: prices and volumes. It then iterates over the prices array, comparing each price with the previous one. If the current price is higher than the previous one, the volume is added to the OBV. If the current price is lower than the previous one, the volume is subtracted from the OBV. Finally, the method returns the calculated OBV.


You can replace the example prices and volumes arrays with your own data to calculate the On-Balance Volume for a different set of price and volume data.