How can I implement MS Excel's "IRR()" formula in PHP?
I tried the algorithm mentioned in this page but the results were not accurate and it was really slow.
After investigating a while, I ended up with the function copied below.
It is based on this question.
function IRR($investment, $flow, $precision = 0.001) {
$min = 0;
$max = 1;
$net_present_value = 1;
while(abs($net_present_value - $investment) > $precision) {
$net_present_value = 0;
$guess = ($min + $max) / 2;
foreach ($flow as $period => $cashflow) {
$net_present_value += $cashflow / (1 + $guess) ** ($period + 1);
}
if ($net_present_value - $investment > 0) {
$min = $guess;
} else {
$max = $guess;
}
}
return $guess * 100;
}