# [Numpy-discussion] add xirr to numpy financial functions?

josef.pktd@gmai... josef.pktd@gmai...
Mon May 25 19:55:04 CDT 2009

```On Mon, May 25, 2009 at 7:27 PM,  <josef.pktd@gmail.com> wrote:
>> just an array of numbers is that it is possible to directly calculate
>> the annual irr, since the time units are well specified. The only
>> problem is the need for an equation solver in numpy. Just using a date
>> tuple would remove the problem of string parsing, and it might be
>> possible to extend it later to a date array.
>>
>> So, I think it would be possible to include Skippers solution, with
>> some cleanup and testing, if an equation solver can be found or if
>> np.roots can handle high order (sparse) polynomials.
>>
>
> I looked a bit more: the current implementation of ``rate`` uses it's
> own iterative (Newton) solver, and in a similar way this could be done
> for a more general xirr.
>
> So with a bit of work this doesn't seem to be a problem and the only
> question that remains is the specification of the dates.

Here is a solver using the polynomial class, or is there something

Josef
'''
Newton solver for value of a polynomial equal to zero
works also for negative rate of return
'''

import numpy as np

nper = 30 #Number of periods
freq = 5  #frequency of payment
val = np.zeros(nper)
val[1:nper+1:freq] = 1  # periodic payment
val[0]=-4   # initial investment

p = np.poly1d(val[::-1])
#print p.roots  # very slow for array with 1000 periods
pd1 = np.polyder(p)
#print p(0.95)  # net present value
#print pd1(0.95) # derivative of polynomial
rv = np.linspace(0.9,1.05,16)
for v,i in zip(rv, p(rv)):print v,i
for v,i in zip(rv, pd1(rv)):print v,i

# Newton iteration
r = 0.95  # starting value, find polynomial root in neighborhood
for i in range(10):
r = r - p(r)/pd1(r)
print r, p(r)

print 'interest rate irr is', 1/r - 1
```