Created
September 27, 2020 22:35
-
-
Save ujihisa/28ac7bf71a8a55c37c1abfa7360b88e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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