3
$\begingroup$

when trying to implement the Black-Scholes formula in Delphi, I've found this: http://www.espenhaug.com/black_scholes.html

I've checked the results against option-price.com and found they are different. Can anyone share the code for the B&S formula in Delphi/FreePascal (from a different source than espenhaug.com?.

{Black and Scholes (1973) Stock options}

function BlackScholes(CallPutFlag : string; S, X, T, r, v : Double): Double;
var
  d1, d2 : Double;

begin
  Result := 0;
  d1 := (LN(S / X) + (r + Power(v, 2) / 2) * T) / (v * SqRt(T));
  d2 := d1 - v * SqRt(T);
  if CallPutFlag = 'c' then
    Result := S * CND(d1) - X * Exp(-r * T) * CND(d2)
  else
    if CallPutFlag = 'p' then
      Result := X * Exp(-r * T) * CND(-d2) - S * CND(-d1);
end;

{The cumulative normal distribution function}
function CND(X : Double) : Double;
var
  L, K : Double;

const
  a1 = 0.31938153;   a2 = -0.356563782;  a3 = 1.781477937;
  a4 = -1.821255978; a5 = 1.330274429;

begin
  L := Abs(X);
  K := 1 / (1 + 0.2316419 * L);
  Result := 1 - 1 / SqRt(2 * Pi) * Exp(-Power(L, 2) / 2)
            * (a1 * K + a2 * Power(K, 2) + a3 * Power(K, 3)
            + a4 * Power(K, 4) + a5 * Power(K, 5));
  if X < 0 then
    Result := (1 - Result)
end;
$\endgroup$
9
  • $\begingroup$ BS is BS is BS, regardless of implementation language used. I venture to say, given you have double checked the formulae that you probably calculate the cdf incorrectly. $\endgroup$
    – Matt Wolf
    Commented Aug 4, 2013 at 5:13
  • 1
    $\begingroup$ @MattWolf, sorry, what's the "cdf"?. $\endgroup$ Commented Aug 4, 2013 at 13:29
  • 1
    $\begingroup$ @MattWolf, thanks. I've replaced my CND function by this one: johndcook.com/cpp_phi.html, but the result is the same. $\endgroup$ Commented Aug 4, 2013 at 13:56
  • 1
    $\begingroup$ @MattWolf, sorry, the BS value is correct now. What I'm getting wrong is the Implied Volatility. I'll open a new question asking for it. $\endgroup$ Commented Aug 4, 2013 at 14:09
  • 2
    $\begingroup$ This question appears to be off-topic because it is too localized, since the issue was an incorrect function input. $\endgroup$ Commented Aug 6, 2013 at 21:28

0

Browse other questions tagged or ask your own question.