Last active
December 17, 2020 04:44
-
-
Save ujihisa/c731e231776f7cc6d22fee30a05ba767 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' | |
# { date => dividends, ... } | |
dividends = CSV.parse(File.read('/tmp/Downloads/ZSP.TO (1).csv'))[1..].to_h {|date, dividend| [date, dividend.to_f] } | |
unit = nil | |
total_return_date_values = CSV.parse(File.read('/tmp/Downloads/^GSPC.csv'))[1..].map {|date, _, _, _, price| | |
price = price.to_f | |
unit ||= 1 / price | |
if dividends[date] | |
unit += (unit * dividends[date]) / price | |
end | |
{ date: date, total_return: price * unit } | |
} | |
total_return_date_values = total_return_date_values | |
dates = total_return_date_values.map { _1[:date] } | |
total_returns = total_return_date_values.map { _1[:total_return] } | |
pairs = (0...total_returns.size - 1).lazy.flat_map {|buy_i| | |
(buy_i + 1...total_returns.size).lazy.select {|sell_i| | |
total_returns[buy_i] >= total_returns[sell_i] | |
}.map {|sell_i| | |
[buy_i, sell_i] | |
} | |
} | |
(worst_buy_i, worst_sell_i) = pairs.max_by {|buy_i, sell_i| | |
sell_i - buy_i | |
} | |
puts <<EOS | |
Minimal n: #{worst_sell_i - worst_buy_i + 1}. | |
Purchased on #{dates[worst_buy_i]} and sold on #{dates[worst_sell_i + 1]}" | |
(Source data: #{dates[0]}..#{dates[-1]}) | |
EOS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ZSP
ZST
ZAG
ZCN (TSX S&P 500 Composite Index)
^GSPC (S&P 500 Index)