Prats
Prats

Reputation: 53

Calculate XIRR for mutual fund transactions in Python

I knew that my question is answered here ..financial python library that has xirr and xnpv function?..

def xirr(transactions):
    years = [(ta[0] - transactions[0][0]).days / 365.0 for ta in transactions]
    residual = 1
    step = 0.05
    guess = 0.05
    epsilon = 0.0001
    limit = 10000
    while abs(residual) > epsilon and limit > 0:
        limit -= 1
        residual = 0.0
        for i, ta in enumerate(transactions):
            residual += ta[1] / pow(guess, years[i])
        if abs(residual) > epsilon:
            if residual > 0:
                guess += step
            else:
                guess -= step
                step /= 2.0
    return guess-1

when i execute above code for fund transactions, i am getting negative residual in 1st iteration. guess=0.5-0.5=0 Due to this,I am getting zerodivisionerror in next iteration. Why am i getting negative residual ..how to deal with this?/ thanks in advance

Upvotes: 1

Views: 385

Answers (1)

Alexander Volkovsky
Alexander Volkovsky

Reputation: 2918

I fixed this in the following way: used guess+1 in the pow function, and removed the -1 part from the result:

def xirr(...):
    while ...:
        for ...:
            residual += ta[1] / pow(guess+1, years[i])
    ...
    return guess

I also ran into performance issues since this code is written in the pure python. So I created the faster version using the rust under the hood. It works more than 100 times faster than python implementation.

Upvotes: 0

Related Questions