Class: RubyTechnicalAnalysis::MovingAverages

Inherits:
Indicator
  • Object
show all
Defined in:
lib/ruby_technical_analysis/indicators/moving_averages.rb

Overview

Instance Attribute Summary collapse

Attributes inherited from Indicator

#series

Instance Method Summary collapse

Methods inherited from Indicator

call

Constructor Details

#initialize(series: [], period: 20) ⇒ MovingAverages

Returns a new instance of MovingAverages.

Parameters:

  • series (Array) (defaults to: [])

    An array of prices, typically closing prices

  • period (Integer) (defaults to: 20)

    The number of periods to use in the calculation



16
17
18
19
20
# File 'lib/ruby_technical_analysis/indicators/moving_averages.rb', line 16

def initialize(series: [], period: 20)
  @period = period

  super(series: series)
end

Instance Attribute Details

#periodObject (readonly)

Returns the value of attribute period.



12
13
14
# File 'lib/ruby_technical_analysis/indicators/moving_averages.rb', line 12

def period
  @period
end

Instance Method Details

#emaFloat

Exponential Moving Average

Returns:

  • (Float)

    The current EMA value



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ruby_technical_analysis/indicators/moving_averages.rb', line 30

def ema
  return series.last if period == 1

  series.last(period).each_with_object([]) do |num, result|
    result << if result.empty?
      num
    else
      (num * _ema_percentages.first) + (result.last * _ema_percentages.last)
    end
  end.last
end

#smaFloat

Simple Moving Average

Returns:

  • (Float)

    The current SMA value



24
25
26
# File 'lib/ruby_technical_analysis/indicators/moving_averages.rb', line 24

def sma
  series.last(period).sum.to_f / period
end

#valid?Boolean

Returns Whether or not the object is valid.

Returns:

  • (Boolean)

    Whether or not the object is valid



53
54
55
# File 'lib/ruby_technical_analysis/indicators/moving_averages.rb', line 53

def valid?
  period <= series.length
end

#wmaFloat

Weighted Moving Average

Returns:

  • (Float)

    The current WMA value



44
45
46
47
48
49
50
# File 'lib/ruby_technical_analysis/indicators/moving_averages.rb', line 44

def wma
  true_periods = (1..period).sum

  sigma_periods = series.last(period).each_with_index.sum { |num, index| (index + 1) * num }

  sigma_periods.to_f / true_periods
end