Skip to content

Commit

Permalink
Test for valid sequence of cash flows before computing irr.
Browse files Browse the repository at this point in the history
  • Loading branch information
wkranec committed Jun 16, 2012
1 parent 3682754 commit 62fc1db
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/finance/cashflows.rb
Expand Up @@ -44,6 +44,12 @@ def values(x)
# @see http://en.wikipedia.org/wiki/Internal_rate_of_return
# @api public
def irr
# Make sure we have a valid sequence of cash flows.
positives, negatives = self.partition{ |i| i >= 0 }
if positives.empty? || negatives.empty?
raise ArgumentError, "Calculation does not converge."
end

func = Function.new(self, :npv)
rate = [ func.one ]
n = nlsolve( func, rate )
Expand Down
2 changes: 2 additions & 0 deletions test/test_cashflows.rb
Expand Up @@ -11,7 +11,9 @@ class TestCashflows < Test::Unit::TestCase
context "an array of numeric cashflows" do
should "have an Internal Rate of Return" do
assert_equal D("0.143"), [-4000,1200,1410,1875,1050].irr.round(3)
assert_raises(ArgumentError) { [10,20,30].irr }
end

should "have a Net Present Value" do
assert_equal D("49.211"), [-100.0, 60, 60, 60].npv(0.1).round(3)
end
Expand Down

0 comments on commit 62fc1db

Please sign in to comment.