From Trading View, we see that the rsi can be written in pinescript as follows:
pine_rsi(x, y) =>
u = max(x - x[1], 0) // upward change
d = max(x[1] - x, 0) // downward change
rs = rma(u, y) / rma(d, y)
rsi = 100 - 100 / (1 + rs)
I've rewritten this in C#:
public static double RelativeStrengthIndex(List<double> input, int samples)
{
List<double> gains = new List<double>();
List<double> losses = new List<double>();
for (int i = input.Count - samples; i < input.Count; i++)
{
double change = input[i] - input[i - 1];
gains.Add(change >= 0 ? change : 0);
losses.Add(change < 0 ? -1 * change : 0);
}
double rs = RollingMovingAverage(gains, samples) / RollingMovingAverage(losses, samples);
return 100 - 100 / (1 + rs);
}
However, my results are not equivalent. They are different enough to rule out differences in data (data from trading view and other providers can be slightly different). I've been trying to fix this for a while and have completely given up.
Does anyone know why my code produces different results?