Permalink
Browse files

Test for valid sequence of cash flows before computing xirr.

  • Loading branch information...
1 parent 62fc1db commit 7904d7cb1b8796da5fa3bf64f709b7602e914abc @wkranec wkranec committed Jun 16, 2012
Showing with 7 additions and 0 deletions.
  1. +6 −0 lib/finance/cashflows.rb
  2. +1 −0 test/test_cashflows.rb
@@ -89,6 +89,12 @@ def npv(rate)
# @transactions.xirr(0.6) #=> Rate("0.024851", :apr, :compounds => :annually)
# @api public
def xirr(iterations=100)
+ # Make sure we have a valid sequence of cash flows.
+ positives, negatives = self.partition{ |t| t.amount >= 0 }
+ if positives.empty? || negatives.empty?
+ raise ArgumentError, "Calculation does not converge."
+ end
+
func = Function.new(self, :xnpv)
rate = [ func.one ]
n = nlsolve( func, rate )
@@ -28,6 +28,7 @@ class TestCashflows < Test::Unit::TestCase
should "have an Internal Rate of Return" do
assert_equal D("0.024851"), @xactions.xirr.effective.round(6)
+ assert_raises(ArgumentError) { @xactions[1,2].xirr }
end
should "have a Net Present Value" do

0 comments on commit 7904d7c

Please sign in to comment.