Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
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
# 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)
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
Something went wrong with that request. Please try again.