Matt
Matt

Reputation: 95

Newton Raphson method PHP

Trying to calculate implied volatility for an option using PHP. The BlackScholes function calculates the price of an option, $OptionValue is the price of the option and $guess is an estimation.

I've based my attempt on similar applications but my version times out. Stepping thru the loop on paper I think makes sense to me. What did I do wrong?

function ImpliedVolatility($type, $S, $X, $T, $r, $D, $OptionValue, $guess) {

$x1 = 0.01;         //lower approx
$x2 = $guess * 2;   //upper approx
$epsilon = 0.01;

$ValueGuess = BlackScholes($type, $S, $X, $T, $r, $D, $x2); //Initialize

while ( abs($OptionValue - $ValueGuess ) > $epsilon ) {
    $xMid = ($x1 + $x2)/2;  //new approx
    $F1 =  BlackScholes($type, $S, $X, $T, $r, $D, $x1);
    $FMid =  BlackScholes($type, $S, $X, $T, $r, $D, $xMid);

    if  ($FMid > $F1 ) {
      $x1 = $xMid;
    } else {
      $x2 = $xMid;
    }

    $ValueGuess = BlackScholes($type, $S, $X, $T, $r, $D, $xMid);
}

return $xMid;

}

Upvotes: 0

Views: 634

Answers (0)

Related Questions