module StockCruncher::Stats

this is a module with various statistic calculation methods

Constants

RANGES

Public Instance Methods

list_ema(values) click to toggle source

Calculate multiple range of exponential moving average

# File lib/stockcruncher/stats.rb, line 12
def list_ema(values)
  h = {}
  RANGES.each do |n|
    next if values.size < n + 1

    h["ema#{n}"] = ema(values[0, n + 1])
  end
  h
end
list_lwma(values) click to toggle source

Calculate multiple range of linearly weighted moving average

# File lib/stockcruncher/stats.rb, line 23
def list_lwma(values)
  h = {}
  RANGES.each do |n|
    next if values.size < n

    weights = (1..n).to_a.reverse
    h["lwma#{n}"] = sma(values[0, n], weights)
  end
  h
end
list_sma(values) click to toggle source

Calculate multiple range of simple moving average

# File lib/stockcruncher/stats.rb, line 35
def list_sma(values)
  h = {}
  RANGES.each do |n|
    next if values.size < n

    h["sma#{n}"] = sma(values[0, n])
  end
  h
end
list_vwma(values, volumes) click to toggle source

Calculate multiple range of volume weighted moving average

# File lib/stockcruncher/stats.rb, line 46
def list_vwma(values, volumes)
  h = {}
  RANGES.each do |n|
    next if values.size < n

    h["vwma#{n}"] = sma(values[0, n], volumes[0, n])
  end
  h
end

Private Instance Methods

ema(array, factor = 2, weights = nil) click to toggle source

Calculate exponential moving average

# File lib/stockcruncher/stats.rb, line 59
def ema(array, factor = 2, weights = nil)
  f = factor.to_f / array.size
  n = array.size - 1
  tsma = sma(array[0, n], weights)
  ysma = sma(array[1, n], weights)
  (tsma * f + ysma * (1 - f)).round(4)
end
sma(array, weights = nil) click to toggle source

Calculate simple moving average

# File lib/stockcruncher/stats.rb, line 68
def sma(array, weights = nil)
  factor = weights.nil? ? Array.new(array.size, 1) : weights
  dividend = array.each_with_index.map { |v, i| v * factor[i] }
  (dividend.sum.to_f / factor.sum).round(4)
end