Skip to content

Instantly share code, notes, and snippets.

@thomasklemm
Created October 30, 2012 11:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasklemm/3979626 to your computer and use it in GitHub Desktop.
Save thomasklemm/3979626 to your computer and use it in GitHub Desktop.
Calculation of Simple Moving Average 9
# 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}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment