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.")