Calculate RSI(Relative Strength Index) using some programming language (JS/C#..)

Blu picture Blu · Mar 25, 2014 · Viewed 12.9k times · Source

I am working to calculate RSI (Relative Strength Index). I have data like this

**Date|Close|Change|Gain|Loss**

The formula for calculating this is

RSI = 100 - 100/(1+RS)
where RS = Average Gain / Average Loss

Source

So I want to calculate via some programming language either in JavaScript or C# but i don't know exactly how to convert that in programming language or what steps do I need.

If there is anything you want more to understand my problem i will try to explain.

Answer

Riga picture Riga · Dec 13, 2014

Simple way to translate the RSI formula:

    public static double CalculateRsi(IEnumerable<double> closePrices)
    {
        var prices = closePrices as double[] ?? closePrices.ToArray();

        double sumGain = 0;
        double sumLoss = 0;
        for (int i = 1; i < prices.Length; i++)
        {
            var difference = prices[i] - prices[i - 1];
            if (difference >= 0)
            {
                sumGain += difference;
            }
            else
            {
                sumLoss -= difference;
            }
        }

        if (sumGain == 0) return 0;
        if (Math.Abs(sumLoss) < Tolerance) return 100;

        var relativeStrength = sumGain / sumLoss;

        return 100.0 - (100.0 / (1 + relativeStrength));
    }

There are plenty of projects implementing RSI in different ways. An incremental way can be found here