3

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;
leonardorame
  • 139
  • 2
  • 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. – Matt Wolf Aug 04 '13 at 05:13
  • 1
    @MattWolf, sorry, what's the "cdf"?. – leonardorame Aug 04 '13 at 13:29
  • http://en.wikipedia.org/wiki/Cumulative_distribution_function – Matt Wolf Aug 04 '13 at 13:31
  • 1
    @MattWolf, thanks. I've replaced my CND function by this one: http://www.johndcook.com/cpp_phi.html, but the result is the same. – leonardorame Aug 04 '13 at 13:56
  • I do not see anything wrong with the BS formula itself. Did you verify matching parameter inputs, or, and I did not check in your solution, are you sure you assigned the values to the right value types, as wrong types may result in rounding errors or worse. By how much are you off? – Matt Wolf Aug 04 '13 at 14:05
  • 1
    @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. – leonardorame Aug 04 '13 at 14:09
  • so you posted code where there was no error? – Matt Wolf Aug 04 '13 at 14:10
  • @MattWolf, well, aparently yes. – leonardorame Aug 04 '13 at 14:15
  • 2
    This question appears to be off-topic because it is too localized, since the issue was an incorrect function input. – Joshua Ulrich Aug 06 '13 at 21:28

0 Answers0