peliot / XIRR-and-XNPV

python implementation of Microsoft Excel's XNPV and XIRR
54 stars 23 forks source link

negative XIRR is not calculated #4

Closed lucas03 closed 9 years ago

lucas03 commented 9 years ago

Hi, I was testing your code for XIRR. But few times when I was trying to get negative XIRR it raised error (python 2.7). Example data:

[(datetime.date(2014, 2, 27), -4000.0), (datetime.date(2015, 3, 6), 2050.2)]

Error:

Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    calculate_xiir_by_portfolio(Portfolio.objects.get(pk=23))
  File "/var/www/django/digrin27/wsgi/digrin/portfolio/utils.py", line 227, in calculate_xiir_by_portfolio
    print xirr(cashflows)
  File "/var/www/django/digrin27/wsgi/digrin/lib/financial.py", line 78, in xirr
    return optimize.newton(lambda r: xnpv(r,cashflows),guess)
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/zeros.py", line 159, in newton
    q1 = func(*((p1,) + args))
  File "/var/www/django/digrin27/wsgi/digrin/lib/financial.py", line 78, in <lambda>
    return optimize.newton(lambda r: xnpv(r,cashflows),guess)
  File "/var/www/django/digrin27/wsgi/digrin/lib/financial.py", line 54, in xnpv
    return sum([cf/(1+rate)**((t-t0).days/365.0) for (t,cf) in chron_order])
ValueError: negative number cannot be raised to a fractional power

Not sure about excell, but google spreadsheet calculates XIRR = -0.4809631525. LibreOffice returns error 502. Is it normal behaviour and your code works properly? What is the issue and what would it take to get same results as google docs (support more input values)?

lucas03 commented 9 years ago

sorry, I should have read closed issues already :) Thanks for the code.