DEV Community

Cover image for Calculating the Relative Strength Index (RSI) with JavaScript
Mustafa Onur Çelik
Mustafa Onur Çelik

Posted on • Updated on

Calculating the Relative Strength Index (RSI) with JavaScript

To calculate the Relative Strength Index (RSI) with JavaScript, you can use the following formula:

RSI = 100 - (100 / (1 + (average of upward price changes / average of downward price changes)))

Enter fullscreen mode Exit fullscreen mode

Here's an example of how you can implement this formula to calculate the RSI for a given array of closing prices:

function calculateRSI(closingPrices) {
  // Calculate the average of the upward price changes
  let avgUpwardChange = 0;
  for (let i = 1; i < closingPrices.length; i++) {
    avgUpwardChange += Math.max(0, closingPrices[i] - closingPrices[i - 1]);
  }
  avgUpwardChange /= closingPrices.length;

  // Calculate the average of the downward price changes
  let avgDownwardChange = 0;
  for (let i = 1; i < closingPrices.length; i++) {
    avgDownwardChange += Math.max(0, closingPrices[i - 1] - closingPrices[i]);
  }
  avgDownwardChange /= closingPrices.length;

  // Calculate the RSI
  const rsi = 100 - (100 / (1 + (avgUpwardChange / avgDownwardChange)));

  return rsi;
}

// Example usage
const closingPrices = [100, 110, 105, 115, 120, 130, 140, 150, 145, 155];
const rsi = calculateRSI(closingPrices);
console.log(rsi); // Output: 71.43

Enter fullscreen mode Exit fullscreen mode

This code calculates the RSI for a given array of closing prices by first calculating the average of the upward and downward price changes, and then applying the formula to these values to calculate the RSI. You can adjust the number of closing prices used in the calculation by changing the length of the array passed to the calculateRSI() function.

Top comments (3)

Collapse
 
joseperales_ profile image
Jose Perales

:Heart

Thank you for the calculation and explanation. QQ: The constant closingPrices here is an array of the last n number of closing of a candle or closing price of the day?

Collapse
 
onurcelik profile image
Mustafa Onur Çelik

those closing prices are candle bar closing prices.

Collapse
 
void0 profile image
Charlie Martin

Thanks. You could do the calculation with a single loop for a small perf boost.

FYI I get 86.67 as the RSI when I run the code not 71.43