Module: MovingAverages

Included in:
Array
Defined in:
lib/ruby-technical-analysis/moving_averages.rb

Overview

module MovingAverages contains some common moving averages and those used in other technical functions it is built upon the array class and all methods assume the use of an array

Instance Method Summary collapse

Instance Method Details

#ema(period) ⇒ Object

Exponential Moving Average



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
# File 'lib/ruby-technical-analysis/moving_averages.rb', line 22

def ema(period)
  if period < 1
    raise ArgumentError,
          "The period parameter cannot be less than 1."
  end
  if size < period
    raise ArgumentError,
          "The array size is less than the period size for the exponential moving average."
  end

  if period == 1
    last
  else
    case period
    when 12
      last_obs_pct = 0.846154
      ma_pct = 0.153846
    when 26
      last_obs_pct = 0.925926
      ma_pct = 0.074074
    else
      last_obs_pct = 2.0 / (period + 1)
      ma_pct = 1.0 - last_obs_pct
    end

    ma_array = []

    last(period).each_with_index do |num, i|
      ma_array << if i.zero?
                    num
                  else
                    (num * last_obs_pct) + (ma_array[i - 1] * ma_pct)
                  end
    end

    ma_array.last
  end
end

#sma(period) ⇒ Object

Simple Moving Average



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/ruby-technical-analysis/moving_averages.rb', line 7

def sma(period)
  if period <= 0
    raise ArgumentError,
          "The period parameter cannot be less than 1."
  end

  if size < period
    raise ArgumentError,
          "The array size is less than the period size for the simple moving average."
  end

  (last(period).reduce(:+).to_f / period)
end

#wma(period) ⇒ Object

Weighted Moving Average



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/ruby-technical-analysis/moving_averages.rb', line 62

def wma(period)
  if period <= 0 || size < period
    raise ArgumentError,
          "The period of the weighted moving average supplied must be greater than 0 and less than or equal to the
          size of the array."
  end

  true_periods = 0
  (1..period).each do |i|
    true_periods += i
  end

  sigma_periods = 0.0
  last(period).each_with_index do |num, i|
    sigma_periods += ((i + 1) * num)
  end

  (sigma_periods.to_f / true_periods)
end