Calculating the Relative Strength Index (RSI) with JavaScript
Mustafa Onur Çelik
Posted on December 11, 2022
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.
💖 💪 🙅 🚩
Mustafa Onur Çelik
Posted on December 11, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.