I have the following python code:
stats.norm.cdf((log((H ** 2) / (S * X))) / (sigma * sqrt(T)) + (1 + mu) * sigma * sqrt(T))
I am trying to get the derivative w.r.t. S, X, sigma, and T of the cdf. In other words, I am trying to find $ d/dX (stats.norm.cdf((log((H ** 2) / (S * X))) / (sigma * sqrt(T)) + (1 + mu) * sigma * sqrt(T)))$
(and the same for d/dS, d/d sigma, d/dT).
Is this possible? If so, how do I find the derivatives?
I tried to do so using the chain rule. However, I fail to succeed. Can anyone show me how it is done or share a link where they show the steps?
Here you've got the composition of two functions so use the chain rule to get
stats.norm.pdf
as the derivative of the outer functionF
, which here isstats.norm.cdf
.You can get the derivatives of the inner function (let's call the inner one
g
) either numerically or symbolically. For speed I would guess that calculatingg
's derivatives symbolically and then defining the function is faster but you could try both options if time permits you to do so.You could try https://www.wolframalpha.com/ online derivative calculator to get the closed form of the derivatives that you need and then code the three derivative functions for
g
.Edit/Update: For numeric derivatives one easy thing you can use if the function is analytic in the variable is the complex step method for derivative approximation.
Here are some references on that one when, why, and how it works:
https://nhigham.com/2020/10/06/what-is-the-complex-step-approximation/
example python code:
https://mdolab.engin.umich.edu/misc/complex-step-guide-python
This is a trick that is sometimes used inside scipy for derivative approximations. Given how easy and useful it is, the method is likely used in other places too.