Class: TechnicalAnalysis::Momentum::Rsi

Inherits:
Object
  • Object
show all
Defined in:
lib/technical_analysis/momentum/rsi.rb

Instance Method Summary collapse

Constructor Details

#initialize(period: 15, data: [], strict: true) ⇒ Rsi

The RSI is calulated by

            ExpMA( Deltas of up-trending Periods )
 RSI  =   ----------------------------------------------
           ExpMA( Deltas of down-trending Periods )

If the average of Delta values is zero, then according to the equation, the RS value will approach infinitiy


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/technical_analysis/momentum/rsi.rb', line 19

def initialize period: 15, data: [], strict: true
  # strict is always true

  raise "Periods must be greater then one" if period <= 1

  @queue = []
  @buffer = []
  @period= period

  @emas = [ TechnicalAnalysis::MovingAverage::ExpMA.new( period: period, strict: true ),
            TechnicalAnalysis::MovingAverage::ExpMA.new( period: period, strict: true  ) ]

  if !data.empty?
    data.map{|d| add_item d }
  end
end

Instance Method Details

#add_item(value) ⇒ Object

adds item, calculates the ema, puts value to the buffer and returns the result



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
# File 'lib/technical_analysis/momentum/rsi.rb', line 37

def add_item  value
  @queue << value.to_f

  up_or_down =  -> (previous, actual) do
    if actual >= previous
      [actual-previous,0]
    else
      [0,previous-actual]
    end
  end

  if @queue.size < 2
    @buffer << nil
  else
    # up-trend-data are added to @emas.first, downtrend-data to @emas.last
    # the lambda up_and_down always returns positve data (or "0")

    @emas.zip( up_or_down[ *@queue[-2,2] ] ).each { | exp_ma, item | exp_ma.add_item item }

    if @emas.first.current.present?
      @buffer <<  100 - ( 100 / (1 + ( @emas.first.current / @emas.last.current rescue 100 ) ) )
    end

    current   #  return the last buffer value
  end
end

#currentObject

returns the ema if the last computed item



70
71
72
# File 'lib/technical_analysis/momentum/rsi.rb', line 70

def current
  @buffer.last
end

#momentumObject

returns the ema-buffer



65
66
67
# File 'lib/technical_analysis/momentum/rsi.rb', line 65

def  momentum
  @buffer
end