Financial Calculations & Valuation
Intermediate
Calculate NPV, IRR & XIRR for Irregular Cash Flows in Python
Compute Net Present Value (NPV), Internal Rate of Return (IRR), and exact date-adjusted XIRR in Python using SciPy root-finding without Excel.
#numpy#scipy#pandas
Problem Statement
Standard IRR assumes cash flows occur at exact 1-year intervals, whereas real-world SIPs, loan disbursements, and private equity cash flows happen on irregular calendar dates (requiring XIRR).
Formula / Core Logic
XIRR solves for rate r where: Sum [ CF_i / (1 + r)^((Date_i - Date_0) / 365) ] = 0
Installation
pip install numpy scipy pandas
irr-npv-calculation-python-financial-script.py
import numpy as np
import pandas as pd
from scipy.optimize import newton
def calculate_xirr(dates, cashflows, guess=0.10):
dates = pd.to_datetime(dates)
days = (dates - dates[0]).days / 365.0
def xnpv(rate):
return sum(cf / ((1 + rate) ** d) for cf, d in zip(cashflows, days))
return round(newton(xnpv, guess) * 100, 2)
if __name__ == '__main__':
dts = ['2024-01-01', '2024-06-15', '2025-02-10', '2026-01-01']
cfs = [-100000, -50000, 25000, 165000]
print(f'Portfolio XIRR: {calculate_xirr(dts, cfs)}%')
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: Why does XIRR fail to converge sometimes?
Ensure your cashflow list contains at least one negative outflow and one positive inflow.