# all files / technicalindicators/lib/oscillators/ RSI.js

97.14% Statements 34/35
91.67% Branches 11/12
100% Functions 5/5
97.14% Lines 34/35

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61

    1×
    1×

    1×

    1×

    4×
    4×

    4×
    4×
    4×
    4×
    4×
    4×
    88×
    88×
    88×
    32×

    32×
    32×

    88×

    4×

    4×

    4×
    66×
    66×
    24×

    1×
    2×
    2×
    2×
    2×

    1×
    1×

    1×
    22×

     /**
     * Created by AAravindan on 5/5/16.
     */
    "use strict"
    const AverageGain = require('../Utils/AverageGain');
    const AverageLoss = require('../Utils/AverageLoss');

    let RSI;

    module.exports = RSI = function(input, options) {

      var period = input.period;
      var values = input.values;

      var GainProvider = new AverageGain({period : period, values : [] });
      var LossProvider = new AverageLoss({period : period, values : [] });
      this.generator = (function* (period){
        var current = yield;
        var lastAvgGain,lastAvgLoss, RS, currentRSI;
        while(true){
          lastAvgGain = GainProvider.nextValue(current);
          lastAvgLoss = LossProvider.nextValue(current);
          if(lastAvgGain && lastAvgLoss){
            if(IlastAvgLoss === 0){
              currentRSI = 100;
            }else{
              RS = lastAvgGain / lastAvgLoss;
              currentRSI = parseFloat((100 - (100 / (1 + RS))).toFixed(2));
            }
          }
          current = yield currentRSI;
        }
      })(period);

      this.generator.next();

      this.result = [];

      values.forEach((tick) => {
        var result = this.generator.next(tick);
        if(result.value !== undefined){
          this.result.push(result.value);
        }
      });
    };

    RSI.calculate = function(input) {
      input.reversedInput ? input.values.reverse(): undefined;
      let result = (new RSI(input)).result;
      input.reversedInput ? result.reverse():undefined;
      return result;
    };

    RSI.prototype.getResult = function () {
      return this.result;
    };

    RSI.prototype.nextValue = function (price) {
      return this.generator.next(price).value;
    };