Skip to content

Commit c81a2b5

Browse files
committed
ENH: IRR: Add quick exit if all values are of same sign
If all values are of the same sign then no solution exists and performing Newton's method is redundant. Instead, return `nan`.
1 parent e47c5d9 commit c81a2b5

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

numpy_financial/_financial.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,12 @@ def irr(values, guess=0.1):
741741
if values.ndim != 1:
742742
raise ValueError("Cashflows must be a rank-1 array")
743743

744+
# If all values are of the same sign no solution exists
745+
# we don't perform any further calculations and exit early
746+
same_sign = np.all(values > 0) if values[0] > 0 else np.all(values < 0)
747+
if same_sign:
748+
return np.nan
749+
744750
# We aim to solve eirr such that NPV is exactly zero. This can be framed as
745751
# simply finding the closest root of a polynomial to a given initial guess
746752
# as follows:

numpy_financial/tests/test_financial.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -580,9 +580,12 @@ def test_trailing_zeros(self):
580580
decimal=2,
581581
)
582582

583-
def test_numpy_gh_6744(self):
583+
@pytest.mark.parametrize('v', [
584+
(1, 2, 3),
585+
(-1, -2, -3),
586+
])
587+
def test_numpy_gh_6744(self, v):
584588
# Test that if there is no solution then npf.irr returns nan.
585-
v = [-1, -2, -3]
586589
assert numpy.isnan(npf.irr(v))
587590

588591
def test_gh_15(self):

0 commit comments

Comments
 (0)