public
Created

Calculation of Simple Moving Average 9

  • Download Gist
sma9.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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 60 61 62
# Require the json library to parse json into Ruby objects
require 'json'
require 'simple_statistics'
 
# The input
json = '[
{
"Low": 8.63,
"Volume": 14211900,
"Date": "2012-10-26",
"High": 8.79,
"Close": 8.65,
"Adj Close": 8.65,
"Open": 8.7
},
{
"Low": 8.65,
"Volume": 12167500,
"Date": "2012-10-25",
"High": 8.81,
"Close": 8.73,
"Adj Close": 8.73,
"Open": 8.76
},
{
"Low": 8.68,
"Volume": 20239700,
"Date": "2012-10-24",
"High": 8.92,
"Close": 8.7,
"Adj Close": 8.7,
"Open": 8.85
}
]'
 
# The function to do the actual calculation of the SMA9
def sma9(array, i)
# Extract the relevant days from the array
days = array[i..i+8]
# Extract all the relevant closing values into an array
closing = days.each_with_object([]) { |day, ary| ary << day['Close'] if day['Close']}
# Calculate the average of the closing values
# sma9 = closing.inject(:+).to_f / closing.length
# This should do the same except you have the extra dependency
sma9 = closing.mean
# Round the result
sma9.round(2)
end
 
# Here the program begins
# Parse json into Ruby objects, here an array consisting of hashes
array = JSON.parse(json)
 
# Iterate over every day...
array = array.each_with_index do |day, i|
# ... to calculate the SMA9 for this day
# and write it to this day's hash
day['SMA9'] = sma9(array, i)
end
 
p array
# => [{"Low"=>8.63, "Volume"=>14211900, "Date"=>"2012-10-26", "High"=>8.79, "Close"=>8.65, "Adj Close"=>8.65, "Open"=>8.7, "SMA9"=>8.69}, {"Low"=>8.65, "Volume"=>12167500, "Date"=>"2012-10-25", "High"=>8.81, "Close"=>8.73, "Adj Close"=>8.73, "Open"=>8.76, "SMA9"=>8.72}, {"Low"=>8.68, "Volume"=>20239700, "Date"=>"2012-10-24", "High"=>8.92, "Close"=>8.7, "Adj Close"=>8.7, "Open"=>8.85, "SMA9"=>8.7}]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.