How To Compute Relative Strength Index (RSI) using Java?

Member

by kenny , in category: Technology , 2 months ago

How To Compute Relative Strength Index (RSI) using Java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cristobal , 2 months ago

@kenny 

Here is an example code snippet in Java to compute Relative Strength Index (RSI) based on a given set of price data:

 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
public class RSI {
    
    public static double calculateRSI(double[] prices, int period) {
        double[] changes = new double[prices.length - 1];
        double[] gains = new double[prices.length - 1];
        double[] losses = new double[prices.length - 1];
        
        for (int i = 0; i < prices.length - 1; i++) {
            changes[i] = prices[i + 1] - prices[i];
            if (changes[i] >= 0) {
                gains[i] = changes[i];
            } else {
                losses[i] = Math.abs(changes[i]);
            }
        }
        
        double avgGain = calculateAverage(gains, period);
        double avgLoss = calculateAverage(losses, period);
        
        double rs = (avgGain / avgLoss);
        
        return 100 - (100 / (1 + rs));
    }
    
    private static double calculateAverage(double[] values, int period) {
        double sum = 0;
        for (int i = 0; i < period; i++) {
            sum += values[i];
        }
        
        return sum / period;
    }
    
    public static void main(String[] args) {
        double[] prices = {10.4, 11.6, 12.5, 13.3, 12.8, 12.9, 12.4, 13.6, 14.2, 13.8};
        int period = 14;
        
        double rsi = calculateRSI(prices, period);
        System.out.println("RSI: " + rsi);
    }
}


In this code snippet, the calculateRSI method takes an array of price data and a period as input, and computes the Relative Strength Index (RSI) based on the Wilder's smoothing method. The calculateAverage method is used to calculate the average gain and average loss over a given period. The main method provides an example usage of the calculateRSI method with sample price data and a period of 14.