Skip to content

Instantly share code, notes, and snippets.

@ig10
Last active August 29, 2015 13:57
Show Gist options
  • Save ig10/9418346 to your computer and use it in GitHub Desktop.
Save ig10/9418346 to your computer and use it in GitHub Desktop.
Excel IRR function in Ruby
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