Module: Philiprehberger::MathKit::MovingAverage

Defined in:
lib/philiprehberger/math_kit/moving_average.rb

Class Method Summary collapse

Class Method Details

.exponential(values, alpha:) ⇒ Array<Float>

Exponential moving average

Parameters:

  • values (Array<Numeric>)

    the input values

  • alpha (Float)

    the smoothing factor (0 < alpha <= 1)

Returns:

  • (Array<Float>)

    the EMA values (same size as input)

Raises:

  • (ArgumentError)

    if alpha is out of range or values is empty



28
29
30
31
32
33
34
35
36
37
# File 'lib/philiprehberger/math_kit/moving_average.rb', line 28

def exponential(values, alpha:)
  raise ArgumentError, 'values must not be empty' if values.empty?
  raise ArgumentError, 'alpha must be between 0 (exclusive) and 1 (inclusive)' if alpha <= 0 || alpha > 1

  result = [values.first.to_f]
  values[1..].each do |v|
    result << ((alpha * v) + ((1 - alpha) * result.last))
  end
  result
end

.simple(values, window:) ⇒ Array<Float>

Simple moving average

Parameters:

  • values (Array<Numeric>)

    the input values

  • window (Integer)

    the window size

Returns:

  • (Array<Float>)

    the SMA values (size = values.size - window + 1)

Raises:

  • (ArgumentError)

    if window is larger than values or less than 1



13
14
15
16
17
18
19
20
# File 'lib/philiprehberger/math_kit/moving_average.rb', line 13

def simple(values, window:)
  raise ArgumentError, 'window must be at least 1' if window < 1
  raise ArgumentError, 'window must not exceed values size' if window > values.size

  (0..(values.size - window)).map do |i|
    values[i, window].sum.to_f / window
  end
end