Class: TechnicalAnalysis::MovingAverage::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/technical_analysis/moving-average/base.rb

Direct Known Subclasses

ExpMA, SimpleMA, Wma

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Base.



7
8
9
10
11
12
13
14
15
16
# File 'lib/technical_analysis/moving-average/base.rb', line 7

def initialize period: 15,  data: [], strict: true

  raise "Period must be greater then one" if  period <= 1
  @period = period
  @strict= strict
  # queue for relevant data to process the calculation
  @queue =  []
  # buffer contains the calculated indicator values
  @buffer = []
end

Instance Method Details

#add_item(value) ⇒ Object

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



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/technical_analysis/moving-average/base.rb', line 19

def add_item  value
  @queue << value
  @queue.shift if @queue.size > @period
  if @buffer.empty?
    @buffer=[value.to_f]
  else
    prev_ema = @buffer.last
    current_value = value.to_f
    @buffer << (current_value - prev_ema) * @smooth_constant + prev_ema
  end
 current  #  return the last buffer value
end

#currentObject

returns the ema of the last computed item



43
44
45
46
47
48
49
# File 'lib/technical_analysis/moving-average/base.rb', line 43

def current 
   if @strict && warmup?
     nil
   else
     @buffer.last
   end
end

#maObject

returns the moving-average-buffer



33
34
35
36
37
38
39
# File 'lib/technical_analysis/moving-average/base.rb', line 33

def ma 
  if @strict
    @buffer.drop @period-1
  else
    @buffer
  end
end