irr.py

Created by matt-numworks

Created on December 04, 2025

1.1 KB

Calculate the Internal Rate of Return


def npv(rate, cash_flows):
    total = 0
    for t, cf in enumerate(cash_flows):
        total += cf / ((1 + rate) ** t)
    return total

def irr(cash_flows, guess=0.1, tol=1e-6, max_iter=1000):
    rate = guess
    for i in range(max_iter):
        # Calculate NPV and derivative (for Newton-Raphson)
        npv_val = 0
        d_npv = 0
        for t, cf in enumerate(cash_flows):
            npv_val += cf / ((1 + rate) ** t)
            if t > 0:
                d_npv -= t * cf / ((1 + rate) ** (t + 1))
        
        # Update rate
        new_rate = rate - npv_val / d_npv
        
        if abs(new_rate - rate) < tol:
            return new_rate
        rate = new_rate
    return None

# Example usage
C0 = float(input("Enter initial investment \n(C0): "))
T = int(input("Enter number of periods \n(T): "))

cash_flows = [-C0]
for t in range(1, T + 1):
    Ct = float(input("Enter cash inflow for period {}: ".format(t)))
    cash_flows.append(Ct)

result = irr(cash_flows)
if result is not None:
    print("IRR: {:.2f}%".format(result * 100))
else:
    print("IRR calculation did not converge.")

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.