PHP IRR(return 的内部利率)财务功能

PHP IRR (Internal rate of return) financial function

如何在 PHP 中实现 MS Excel 的 "IRR()" 公式?

我尝试了this page中提到的算法,但结果不准确,而且速度很慢。

经过一段时间的调查,我最终复制了下面的函数。

它基于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;
}

这是根据 Tomas 的回答修改的。它通过在开始时检查以确保现金流量大于投资来停止无限循环。我还提高了精度,运行 最多提高了 20 倍。

private function IRR($investment, $flow, $precision = 0.000001) {

    if (array_sum($flow) < $investment):
        return 0;
    endif;
    $maxIterations = 20;
    $i =0;
    if (is_array($flow)):
        $min = 0;
        $max = 1;
        $net_present_value = 1;
        while ((abs($net_present_value - $investment) > $precision)&& ($i < $maxIterations)) {
            $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;
            }
            $i++;
        }
        return $guess * 100;
    else:
        return 0;
    endif;
}