How To Calculate Relative Strength Index (RSI) in Ruby?

Member

by darion , in category: Third Party Scripts , 5 months ago

How To Calculate Relative Strength Index (RSI) in Ruby?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 5 months ago

@darion 

To calculate the Relative Strength Index (RSI) in Ruby, you can use the following code snippet:

 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
def calculate_rsi(data, period)
  gains = []
  losses = []
  
  data.each_cons(2) do |current, previous|
    change = current - previous
    
    if change > 0
      gains << change
      losses << 0
    else
      gains << 0
      losses << change.abs
    end
  end
  
  average_gain = gains.first(period).sum / period
  average_loss = losses.first(period).sum / period
  
  rs = average_gain / average_loss
  rsi = 100 - (100 / (1 + rs))
  
  return rsi
end

# Example usage
data = [45, 50, 52, 48, 55, 60, 58, 52, 56, 54]
period = 14

rsi = calculate_rsi(data, period)
puts "RSI: #{rsi.round(2)}"


In this code snippet, the calculate_rsi method takes two arguments: data, which is an array of historical prices, and period, which is the RSI period (typically 14). The method then calculates the gains and losses based on price changes, calculates the average gain and loss over the specified period, and finally calculates the RSI value using the formula. The RSI value is then returned and printed to the console.


You can adjust the data array and period value to calculate the RSI for different sets of historical prices and different RSI periods.