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)))
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
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)
: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?
those closing prices are candle bar closing prices.
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