PHP修改了Dietz返回函数给出了错误的结果

时间:2013-05-29 09:07:55

标签: php date finance

我编写了自己的modified dietz返回函数来计算外部现金流动的投资组合的回报。 与excel解决方案相比,它似乎工作正常,但我遇到的结果是错误的。当正确结果为0.30%时,我的函数返回0.23%。

这是功能:

//Calculates the Modified-Dietz return given arrays of MIMO.
//MIMO is an associative array of dates to values
function modDietz($startDate, $endDate, $BMV, $EMV, $MIMO){
    if( strtotime($startDate) !== false ){
    //Date was passed as a string; convert it to php date
    $startDate = strtotime($startDate);
    }
    if( strtotime($endDate) !== false ){
    //Date was passed as a string; convert it to php date
    $endDate = strtotime($endDate);
    }

    //Convert seconds to days
    $CD = ($startDate - $endDate)/(60*60*24); 

    $i = 0;
    $SumWiFi = 0;
    $F = 0;
    foreach ($MIMO as $date=>$Fi){
        if( strtotime($date) !== false ){
          //Date was passed as a string; convert it to php date
          $date = strtotime($date);
        }
        //Only take into account the MIMO if it falls between the start and end dates.
        if ($date >= $startDate && $date <= $endDate){
            $Di = ($date - $startDate) / (60*60*24);
            $Wi = ($CD - $Di) / $CD;
            $SumWiFi += $Wi * $Fi;
            $F += $Fi;
        }
    }
    if ($BMV + $SumWiFi != 0) {
        return ($EMV - $BMV - $F)/($BMV + $SumWiFi);
    } else {
        return 0;
    }
}

这是我提供的数据,它给出了错误的结果:

Dates:
Array
(
    [0] => 2013-04-30
    [1] => 2013-03-31
)

Values:
Array
(
    [2013-03-31] => 4990430.0
    [2013-04-30] => 5991710.1
)

MIMO:
Array
(
    [2013-04-19] => -600.0
    [2013-04-23] => 1000000.0
    [2013-04-29] => -13750
)

这是产生结果的行:

$mdReturn = modDietz($dates[1], $dates[0], $values[$dates[1]], $values[$dates[0]], $mimo);

我有一种感觉,29日的Money-Out可能是原因 - 我不太确定处理此功能中日期的最佳方式。目前我只是在以yyyy-mm-dd格式传递的字符串上使用字符串到日期,如上面的数组所示。

知道我哪里错了吗?

1 个答案:

答案 0 :(得分:1)

我认为Mark Baker是对的,试试这个:

function modDietz(DateTime $startDate, DateTime $endDate, $BMV, $EMV, $MIMO){
    $CD = $startDate->diff($endDate);
    $SumWiFi = 0;
    $F = 0;
    foreach ($MIMO as $date=>$Fi){
        $date = new DateTime($date);
        //Only take into account the MIMO if it falls between the start and end dates.
        if ($date >= $startDate && $date <= $endDate){
            $Di = $date->diff($startDate);
            $Wi = ($CD->d - $Di->d) / $CD->d;
            $SumWiFi += $Wi * $Fi;
            $F += $Fi;
        }
    }
    if ($BMV + $SumWiFi != 0) {
        return ($EMV - $BMV - $F)/($BMV + $SumWiFi);
    } else {
        return 0;
    }
}
$mimo = array(
    '2013-04-19' => -600.0,
    '2013-04-23' => 1000000.0,
    '2013-04-29' => -13750,
);
$startDate = new DateTime('2013-03-31');
$endDate = new DateTime('2013-04-30');
$result = modDietz($startDate, $endDate, 4990430.0, 5991710.1, $mimo);
// 0.0029925034725645