简体   繁体   中英

Discrepancies between Javascript and Python

I have an exam question where I have to find the delta of a put and a call option using the Black and Schole formula.

I found a website http://www.deltaquants.com/calc-test that does that for me, so I went in the code and found this function:

getDelta: function(spot, strike, volatility, riskfree, dividendy) {
    var self = this;
    var d1 = self.getD1(spot, strike, volatility, riskfree, dividendy);
    var Nd1 = phi(d1);
    // Interesting line
    var result = Math.exp( - dividendy * self.expiry) * (self.type !== 'put') ? Nd1 : (Nd1 - 1); 
    return result.toFixed(6);
}

I replicated that in Python:

def delta(q, t, nd1, put: bool):
    return np.exp(- q * t) * (nd1 - 1 * put)

print(delta(.02, .25, .5279031701805211, True)) # -0.46974223705768553
print(delta(.02, .25, .5279031701805211, False)) # 0.5252702421349968

With the same inputs (Nd1 = nd1, dividendy = q, self.expiry = t), the JS code returns -0.472097 for the put and 0.527903 for the call.

I rewrote their JS code to be testable in the console:

const delta = (q, t, nd1, type) => Math.exp(-q * t) * (type !== "put") ? nd1 : (nd1 - 1);

If you rewrite the JS the same way I did in python:

const delta2 = (q, t, nd1, put) => Math.exp(-q * t) * (nd1 - 1 * put);
// Where put is a boolean

You get the same results as my python code, it seems that the Mat.exp part is always disregarded in their code. Do you know why?

The problem is that the ternary operator ( ... ? ... : ... ) has lower operator precedence than multiplication, so if you have an expression A * B? C: D A * B? C: D it gets parsed as if it were (A * B)? C: D (A * B)? C: D rather than A * (B? C: D) .

If you add parentheses to emphasise the way the expression gets parsed, you end up with this:

    var result = (Math.exp( - dividendy * self.expiry) * (self.type !== 'put')) ? Nd1 : (Nd1 - 1);
    //           ^-------------------- added parentheses ---------------------^

Here you can see that the expression involving Math.exp is in the condition of the ternary operator, and so the value of result will be either Nd1 or Nd1 - 1 .

I suspect the intended calculation is

    var result = Math.exp( - dividendy * self.expiry) * ((self.type !== 'put') ? Nd1 : (Nd1 - 1));
    //                                                  ^---------- added parentheses ----------^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM