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/c731e231776f7cc6d22fee30a05ba767 to your computer and use it in GitHub Desktop.
Save ujihisa/c731e231776f7cc6d22fee30a05ba767 to your computer and use it in GitHub Desktop.
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
@ujihisa
Copy link
Author

ujihisa commented Dec 17, 2020

ZSP

Minimal n: 579.
  Purchased on 2017-11-30 and sold on 2020-03-24"
  (Source data: 2012-11-27..2020-12-15)


ZST

Minimal n: 262.
  Purchased on 2014-11-24 and sold on 2015-12-09"
  (Source data: 2011-02-03..2020-12-15)

ZAG

Minimal n: 1291.
  Purchased on 2015-01-27 and sold on 2020-03-19"
  (Source data: 2010-01-25..2020-12-15)

ZCN (TSX S&P 500 Composite Index)

Minimal n: 1565.
  Purchased on 2013-12-27 and sold on 2020-03-24"
  (Source data: 2009-06-04..2020-12-15)

^GSPC (S&P 500 Index)

Minimal n: 6287.
  Purchased on 1929-08-30 and sold on 1954-11-01"
  (Source data: 1927-12-30..2020-12-15)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment