Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating XIRR in Python

I need to calculate XIRR of financial investments made over a period of time. Is there any function to do this in numpy, pandas or plain python?

Reference: What is XIRR?

The accepted answer in the original question is not correct and can be improved.

like image 675
DaSarfyCode Avatar asked Oct 10 '17 13:10

DaSarfyCode


2 Answers

Created a package for fast XIRR calculation, PyXIRR

It doesn't have external dependencies and works faster than any existing implementation.

from datetime import date
from pyxirr import xirr

dates = [date(2020, 1, 1), date(2021, 1, 1), date(2022, 1, 1)]
amounts = [-1000, 1000, 1000]

# feed columnar data
xirr(dates, amounts)

# feed tuples
xirr(zip(dates, amounts))

# feed DataFrame
import pandas as pd
xirr(pd.DataFrame({"dates": dates, "amounts": amounts}))
like image 112
Alexander Volkovsky Avatar answered Oct 17 '22 21:10

Alexander Volkovsky


Here's an implementation taken from here.

import datetime
from scipy import optimize

def xnpv(rate,cashflows):
    chron_order = sorted(cashflows, key = lambda x: x[0])
    t0 = chron_order[0][0]
    return sum([cf/(1+rate)**((t-t0).days/365.0) for (t,cf) in chron_order])

def xirr(cashflows,guess=0.1):
    return optimize.newton(lambda r: xnpv(r,cashflows),guess)
like image 3
pyCthon Avatar answered Oct 17 '22 21:10

pyCthon