Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ujihisa/28ac7bf71a8a55c37c1abfa7360b88e3 to your computer and use it in GitHub Desktop.
Save ujihisa/28ac7bf71a8a55c37c1abfa7360b88e3 to your computer and use it in GitHub Desktop.
require 'csv'
def least_square(ys)
ave_x = ys.size / 2.0
ave_y = ys.sum / ys.size.to_f
a = ys.zip(0..).sum {|y, i| (i - ave_x) * (y - ave_y) } / ys.zip(0..).sum {|_, i| (i - ave_x) ** 2 }
b = ave_y - a * ave_x
[a, b]
end
# Download manually from https://finance.yahoo.com/quote/%5EGSPC/history?p=%5EGSPC
tuples = CSV.parse(File.read('/tmp/Downloads/^GSPC.csv'))[-251*30..] {|date, open, high, low, close, adj_close, volume|
[date, close]
}
tuples = tuples.map {|date, close|
[date, Math.log(close.to_f)]
}
(a, b) = least_square(tuples.map(&:last))
tuples = tuples.map.with_index {|(date, log_close), i|
[date, log_close, a * i + b]
}
tuples.each do |date, log_close, log_ls|
puts [date, Math.exp(log_close), Math.exp(log_ls)].join("\t")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment