Skip to content

Instantly share code, notes, and snippets.

@bpsagar
Created December 3, 2021 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bpsagar/9f9f530cd8005ba470375e80717ccdb3 to your computer and use it in GitHub Desktop.
Save bpsagar/9f9f530cd8005ba470375e80717ccdb3 to your computer and use it in GitHub Desktop.
Python function to calculate XIRR
"""
This file is copied from https://github.com/dkensinger/python/blob/master/XIRR.py
which doesn't exist anymore!
"""
from datetime import date
def xirr(transactions):
"""
Calculates the Internal Rate of Return (IRR) for an irregular series of cash flows (XIRR)
Takes a list of tuples [(date,cash-flow),(date,cash-flow),...]
Returns a rate of return as a percentage
"""
years = [(ta[0] - transactions[0][0]).days / 365. for ta in transactions]
residual = 1.0
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, trans in enumerate(transactions):
residual += trans[1] / pow(guess, years[i])
if abs(residual) > epsilon:
if residual > 0:
guess += step
else:
guess -= step
step /= 2.0
return (guess - 1) * 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment