Created
December 3, 2021 14:56
-
-
Save bpsagar/9f9f530cd8005ba470375e80717ccdb3 to your computer and use it in GitHub Desktop.
Python function to calculate XIRR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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