Skip to content

Instantly share code, notes, and snippets.

@iogakos
Created November 22, 2012 09:40
Show Gist options
  • Save iogakos/4130251 to your computer and use it in GitHub Desktop.
Save iogakos/4130251 to your computer and use it in GitHub Desktop.
Weighted Moving Average - Ruby Implementation
# Weighted Moving Average (WMA)
# http://en.wikipedia.org/wiki/Moving_average#Weighted_moving_average
#
# Given a hash, calculates the weighted moving averages of its values within
# a window size given. Modifies the original hash values.
#
# @param hash [Hash] the hash for whom values calculate the weighted moving
# averages.
# @param maws [Fixnum] the Moving Average Window Size. The greatest this
# number is the smoothest the calculated averages will be.
#
# @return [Hash] hash the modified hash containing the weighted moving
# averages in its values.
def wma_hash(hash, maws = MAWS)
sum = maws * (maws + 1) / 2
values = hash.to_a.reverse # recent averages are the most important ones
values_size = values.size
values.each_with_index do |kv, pos|
weighted_sum = 0
0.upto(maws - 1) do |i|
weighted_sum += values[i + pos].last * (i + 1)
end
hash[values[pos+1].first] = weighted_sum.to_f / sum
return hash if pos + maws == values_size
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment