Sunday, April 7, 2019

Calculating RSI (Relative Strength Index)


Calculating RSI (Relative Strength Index)

A momentum oscillator indicator which measures speed and change of price movement
RSI is counted between 0 and 100.
Traditionally considered Overbought when above 70 and Oversold when below 30.

Calculation :
RSI = 100 – 100 / (1 + RS)


 RS   = Average Gain of Up Periods  in specified time frame / Average loss of down  Periods during the specified time frame


§  First Average Gain = Sum of Gains over the past  n periods /n
§  First Average Loss = Sum of Losses over the past n periods /n
    • N = number of period for which RSI is being calculated

The second, and subsequent, calculations are based on the prior averages and the current gain loss:
§  Average Gain = [(previous Average Gain) x n + current Gain] / n.
§  Average Loss = [(previous Average Loss) x n + current Loss] / n.


So now lets code it simply in C#  to give rsi value for a particular interval.

public static double Rsi(double[] closePrices)
    {
        var prices = closePrices;

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

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

        var relativeStrength = sumProfit / sumLoss;

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