peterc (owner)

Revisions

gist: 90661 Download_button fork
public
Public Clone URL: git://gist.github.com/90661.git
Embed All Files: show embed
5020weeks.rb #
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
# 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}"