Last active
August 29, 2015 13:57
-
-
Save ig10/9418346 to your computer and use it in GitHub Desktop.
Excel IRR function in Ruby
This file contains hidden or 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
module I10 | |
# Returns Internal Rate of Return (TIR Spanish) for a cash | |
# flow in numbers, with the payments as values. | |
# @param transactions : Array which contains initial project cost, | |
# and the payments over the time. | |
def I10.irr(transactions, max_iterations = 20) | |
min = 0.0 | |
max = 1.0 | |
npv = 0 | |
iterations = 0 | |
accuracy = 0.000001 | |
while npv.abs < accuracy || iterations != max_iterations do | |
closest = (min + max)/2 | |
npv = transactions.each_with_index.map{|v,i| (v/(1+closest)**i) }.inject(:+) | |
(npv > 0 ? min = closest : max = closest) | |
iterations += 1 | |
end | |
closest | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment