- find the gains from the difference between closing prices for each period
- negative gains (losses) and gains are separated and the exponential averages for each is calculated
- the RSI is the ratio of the average gains to the average losses.

Code: Select all

```
public class RSIFinder {
List<Double> data = new ArrayList<>();
public RSIFinder(List<Double> data) {
this.data = data;
}
public double[] find() {
double[] diff = new double[data.size()];
for (int i = 1; i < diff.length; i++) {
diff[i] = data.get(i) - data.get(i - 1);
}
double[] gain = new double[data.size()];
double[] loss = new double[data.size()];
for (int i = 1; i < diff.length; i++) {
if (diff[i] < 0) {
loss[i] = -diff[i];
gain[i] = 0;
} else {
gain[i] = diff[i];
loss[i] = 0;
}
}
double total = 0;
for (int i = 1; i < 14; i++) {
total += gain[i];
}
double[] avgGain = new double[diff.length];
double[] avgLoss = new double[diff.length];
avgGain[14] = total / 14;
total = 0;
for (int i = 1; i < 14; i++) {
total += loss[i];
}
avgLoss[14] = total / 14;
for (int i = 15; i < avgGain.length; i++) {
avgGain[i] = (avgGain[i - 1] * 13 + gain[i]) / 14.0;
avgLoss[i] = (avgLoss[i - 1] * 13 + loss[i]) / 14.0;
}
double[] rsi = new double[avgGain.length];
for (int i = 14; i < avgGain.length; i++) {
if (avgLoss[i] == 0) {
rsi[i] = 100;
} else {
double rs = avgGain[i] / avgLoss[i];
rsi[i] = 100 - (100 / (1 + rs));
}
}
return rsi;
}
}
```