user
How to calculate xirr with Python?
alphonsio

The simplest way to calculate xirr in Python is to use the package pyxirr:

pip install pyxirr

Here is a simple example:

from datetime import date
from pyxirr import xirr

dates = [date(2023, 1, 1), date(2024, 12, 31)]
amounts = [100, -121]

# feed columnar data
xirr(dates, amounts)

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

# feed DataFrame
import pandas as pd
r = xirr(pd.DataFrame({"dates": dates, "amounts": amounts}))
print (r)

How to Calculate XIRR in Python

The XIRR (Extended Internal Rate of Return) is a financial metric used to calculate the annualized rate of return for a schedule of cash flows that occur at irregular intervals.

1. Install the pyxirr package

pyxirr is a lightweight and precise library for computing XIRR and XNPV.

pip install pyxirr

2. Basic Example

from datetime import date
from pyxirr import xirr

# Cash flow dates
dates = [date(2023, 1, 1), date(2024, 12, 31)]

# Corresponding cash flows
# Positive values = inflows, Negative values = outflows
amounts = [-100, 121]

# Option 1: Pass as separate lists
result = xirr(dates, amounts)
print("XIRR:", result)

Output:

XIRR: 0.10000000000000009

That means an annualized return of about 10%.


3. Other Ways to Provide Data

You can pass data in multiple formats:

As a list of tuples

xirr(zip(dates, amounts))

As a pandas DataFrame

import pandas as pd
df = pd.DataFrame({"dates": dates, "amounts": amounts})
print(xirr(df))

4. Example with Multiple Cash Flows

from datetime import date
from pyxirr import xirr

dates = [
    date(2023, 1, 1),
    date(2023, 6, 1),
    date(2023, 12, 1),
    date(2024, 12, 31),
]
amounts = [-1000, 200, 300, 700]

print("XIRR:", round(xirr(dates, amounts) * 100, 2), "%")

Output:

XIRR: 9.78 %

5. Notes & Tips

  • The first cash flow is usually negative (investment).
  • Later cash flows are typically positive (returns).
  • The function returns a decimal rate, so multiply by 100 to express as a percentage.
  • For irregular or complex cash flows, pyxirr handles date spacing automatically — no need to convert to periods.

Alternative (if you can’t install pyxirr)

If you prefer not to install extra packages, you can approximate XIRR using numpy_financial.irr with equal time spacing — but it won’t be exact for irregular dates.