Class: AdvancedMath::SimpleMovingAverage

Inherits:
Object
  • Object
show all
Defined in:
lib/advanced_math/sma.rb

Overview

Simple Moving Average (SMA) calculator Created: 2011-06-24 Author: G Nagel Company: Mercury Wireless Software LLC

Direct Known Subclasses

SMA

Instance Method Summary collapse

Constructor Details

#initialize(range) ⇒ SimpleMovingAverage

Initialize the members: range:

number of values to average

sum:

current sum of all values in the array

values:

array of values used as temporary storage

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
# File 'lib/advanced_math/sma.rb', line 16

def initialize(range)
  raise ArgumentError, "Range is nil" unless (range);
  raise ArgumentError, "Range must be >= 1" unless range.to_i >= 1;
  @range = range.to_i;
  @sum = 0;
  @values = Array.new();
end

Instance Method Details

#add(value) ⇒ Object

Add a value to the list. If the list is < @range, then return nil. Otherwise compute the SMA and return the value.

Raises:

  • (ArgumentError)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/advanced_math/sma.rb', line 29

def add(value)
  raise ArgumentError, "Value is nil" unless (value);

  # add the value to the end of the array.
  @values.push(value);

  # Calculate the sum of the array
  @sum += value.to_f;

  # Is the array less than the range?
  return nil if (@values.length() < @range)

  # Is the array larger than the range?
  @sum -= @values.shift.to_f() if (@values.length() > @range)

  # Compute the average
  return @sum.to_f / @range.to_f;
end

#add_array(values) ⇒ Object

Compute the SMA values for an array Return an array with the SMA values

Raises:

  • (ArgumentError)


52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/advanced_math/sma.rb', line 52

def add_array(values)
  raise ArgumentError, "Value is nil" unless (values);
  raise ArgumentError, "Value is not an array" unless values.kind_of?(Array);

  output = []

  # Calculate the sum of the array
  values.each() { |value| output << add(value) }

  # Return the SMA array
  return output
end