# all files / technicalindicators/lib/Utils/ SD.js

100% Statements 42/42
100% Branches 12/12
100% Functions 5/5
100% Lines 41/41

    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
    62
    63
    64
    65
    66
    67
    68
    69

    1×
    1×
    1×

    1×

    1×

    8×
    8×

    8×

    64×

    8×

    8×
    8×
    8×
    8×
    8×
    8×
    8×
    116×
    116×
    116×
    64×
    64×
    500×

    64×

    116×

    8×

    8×
    33×
    33×
    21×

    1×
    2×
    2×
    2×
    2×

    1×
    1×

    1×
    83×
    83×
    43×

     /**
     * Created by AAravindan on 5/7/16.
     */
    "use strict"

    const SMA = require('../moving_averages/SMA');
    const LinkedList = require('../Utils/FixedSizeLinkedList');
    const nf = require('./../Utils/NumberFormatter');

    let SD;

    module.exports = SD = function(input) {

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

      this.format = input.format || nf;

      var sma = new SMA({period : period, values : [], format : (v) => {return v}});

      this.result = [];

      this.generator = (function* (){
        var tick;
        var mean;
        var currentSet = new LinkedList(period);;
        tick = yield;
        var sd;
        while (true) {
          currentSet.push(tick);
          mean = sma.nextValue(tick);
          if(mean){
            let sum = 0;
            for(let x of currentSet.iterator()){
              sum = sum + (Math.pow((x - mean),2))
            }
            sd = Math.sqrt(sum / (period ))
          }
          tick = yield sd;
        }
      })();

      this.generator.next();

      priceArray.forEach((tick) => {
        var result = this.generator.next(tick);
        if(result.value){
          this.result.push(this.format(result.value));
        }
      });
    };

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

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

    SD.prototype.nextValue = function (price) {
      var nextResult = this.generator.next(price);
      if(nextResult.value)
        return this.format(nextResult.value);
    };