Skip to content

Commit e15e809

Browse files
committed
ENH: Add changes from code review
1 parent 90b6297 commit e15e809

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

numpy_financial/_financial.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ def irr(values, guess=0.1):
700700
Notes
701701
-----
702702
The IRR is perhaps best understood through an example (illustrated
703-
using np.irr in the Examples section below). Suppose one invests 100
703+
using np.irr in the Examples section below). Suppose one invests 100
704704
units and then makes the following withdrawals at regular (fixed)
705705
intervals: 39, 59, 55, 20. Assuming the ending value is 0, one's 100
706706
unit investment yields 173 units; however, due to the combination of
@@ -741,23 +741,20 @@ def irr(values, guess=0.1):
741741
if values.ndim != 1:
742742
raise ValueError("Cashflows must be a rank-1 array")
743743

744-
solution_found = False
745-
p = np.polynomial.Polynomial(values)
746-
pp = p.deriv()
744+
# NPV = V0 * (1+eirr)^0 + V1 * (1+eirr)^-1 + ...
745+
# let x = 1 / (1+eirr)
746+
# NPV = V0 * x^0 + V1 * x^1 + ...
747+
npv_ = np.polynomial.Polynomial(values)
748+
d_npv = npv_.deriv()
747749
x = 1 / (1 + guess)
748750

749-
for i in range(100):
750-
x_new = x - (p(x) / pp(x))
751+
for _ in range(100):
752+
x_new = x - (npv_(x) / d_npv(x))
751753
if abs(x_new - x) < 1e-12:
752-
solution_found = True
753-
break
754+
return 1 / x_new - 1
754755
x = x_new
755756

756-
if solution_found:
757-
return 1 / x - 1
758-
else:
759-
return np.nan
760-
757+
return np.nan
761758

762759

763760
def npv(rate, values):

0 commit comments

Comments
 (0)