Over a million developers have joined DZone.

S&P 500 50-week And 20-week Average Checker Code

·
50 week and 20 week averages are useful in certain financial signals, such as buying when the 20 is 1% above the 50 and selling when the 20 is 1% below the 50.


require 'fastercsv'
require 'open-uri'

class Array; def sum; inject( nil ) { |sum,x| sum ? sum+x : x }; end; def mean; sum.to_f / size; end; end

fifty_weeks_ago = Time.now - 30240000
url = %Q{http://ichart.finance.yahoo.com/table.csv?s=%5EGSPC&d=#{Time.now.month - 1}&e=#{Time.now.day}&f=#{Time.now.year}&g=w&a=#{fifty_weeks_ago.month - 1}&b=#{fifty_weeks_ago.day}&c=#{fifty_weeks_ago.year}&ignore=.csv}

data = FasterCSV.parse(open(url).read)
fifty = data[1..-1].first(50).collect { |r| r[4].to_f }
twenty = fifty.first(20)

puts "#{fifty.size} week mean: #{fifty.mean}"
puts "#{twenty.size} week mean: #{twenty.mean}"
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}