UNPKG

@railpath/finance-toolkit

Version:

Production-ready finance library for portfolio construction, risk analytics, quantitative metrics, and ML-based regime detection

40 lines (39 loc) 1.97 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calculateIRR = calculateIRR; const calculateInitialGuess_1 = require("./calculateInitialGuess"); const calculateIRRWithNewtonRaphson_1 = require("./calculateIRRWithNewtonRaphson"); const calculateIRRWithBisection_1 = require("./calculateIRRWithBisection"); /** * Calculate Internal Rate of Return (IRR) using improved Newton-Raphson with Bisection fallback * * This function attempts to use the fast Newton-Raphson method first, and automatically * falls back to the robust Bisection method if Newton-Raphson encounters problems * (e.g., small derivatives, divergence, or repeated worsening). * * @param cashFlows - Array of cash flows (positive for inflows, negative for outflows) * @param timePeriods - Array of time periods in years corresponding to each cash flow * @param maxIterations - Maximum number of iterations for convergence * @param tolerance - Convergence tolerance (default: 1e-6) * @returns IRR result with rate, iterations, and method used */ function calculateIRR(cashFlows, timePeriods, maxIterations, tolerance) { if (cashFlows.length !== timePeriods.length) { throw new Error('Cash flows and time periods must have same length'); } if (cashFlows.length < 2) { throw new Error('At least 2 cash flows required for IRR calculation'); } // Improved initial guess const initialRate = (0, calculateInitialGuess_1.calculateInitialGuess)(cashFlows); // Try Newton-Raphson first try { const result = (0, calculateIRRWithNewtonRaphson_1.calculateIRRWithNewtonRaphson)(cashFlows, timePeriods, initialRate, maxIterations, tolerance); return result; } catch (error) { // Fallback to Bisection if Newton-Raphson fails const result = (0, calculateIRRWithBisection_1.calculateIRRWithBisection)(cashFlows, timePeriods, maxIterations, tolerance); return result; } }