Skip to content

Instantly share code, notes, and snippets.

@peterc
Created April 6, 2009 07:48
Show Gist options
  • Save peterc/90661 to your computer and use it in GitHub Desktop.
Save peterc/90661 to your computer and use it in GitHub Desktop.
# Get the 50/20 week means of markets
# Sloppy ass coding that was a quick hack one night many moons ago..
# Easily changed to do 50/20 days instead, not posting that one :)
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
index = case ARGV.first
when "dow": "DJI"
when "sp500": "GSPC"
when "ftse": "FTSE"
when "nasdaq": "IXIC"
when "nikkei": "N225"
else "GSPC"
end
cache_file = "#{index}-#{Time.now.year}-#{sprintf("%0.2d", Time.now.month)}-#{sprintf("%0.2d", Time.now.day)}.csv"
raw_data = ''
if File.exist?(cache_file) && (File.size(cache_file) > 256)
raw_data = File.read(cache_file)
else
File.open(cache_file, 'w+') do |f|
url = %Q{http://ichart.finance.yahoo.com/table.csv?s=%5E#{index}&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}
raw_data = open(url).read
f.puts raw_data
end
end
data = FasterCSV.parse(raw_data)
fifty = data[1..-1].first(50).collect { |r| r[4].to_f }
twenty = fifty.first(20)
fifty_mean = fifty.mean
twenty_mean = twenty.mean
puts "#{index} #{fifty.size}WK MEAN: #{fifty_mean}"
puts "#{index} #{twenty.size}WK MEAN: #{twenty_mean}"
puts "20/50 ratio: #{twenty_mean / fifty_mean}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment