Black-Scholes formula and greeks: Python implementation

  • Black-Scholes formula and greeks;
  • implementation of option strategies;
  • Examples of study of portfolio greeks;

Hello, all!
In this post, I´ll share with you a plug and play implementation in Python for the Black-Scholes formula in addition to the greeks for vanilla European calls and puts. The implementation is simple, given that all results are obtained directly from the implementation of closed analytical formulas.
Let´s first remind the Black-Scholes formula, for calls:
$C(S,t)=SN(d_1) - Ke^{-r(T-t)}N(d_2)$
and for puts:
$P(S,t)= Ke^{-r(T-t)}N(-d_2) - SN(-d_1)$
with:
$d_1=\frac{ln(S/K) + (r + \sigma^2 /2)(T-t)}{\sigma \sqrt{T-t}}$
$d_2 = d_1-\sigma \sqrt{T-t}$
and: $N(x)=\frac{1}{\sqrt{2 \pi}} \int_{- \infty}^{x} exp(\frac{z^2}{2})dz$
where $(T-t)$ is the time to maturity, $K$ is the strike price, $S$ is the asset price at time $t$, $r$ is the risk free interest rate, and $\sigma$ is the volatility.
The greeks (discussed in this post) are:
Delta:
$\Delta = \frac{\partial C}{\partial S}$
Call:
$\Delta = N(d_1)$
Put:
$\Delta = -N(-d_1)$
Gamma:
$\Gamma = \frac{\partial^2 C}{\partial S^2}$
Call & Put:
$\Gamma = \frac{N'(d_1)}{S \sigma \sqrt{T-t} }$
Vega:
$Vega = \frac{\partial C}{\partial \sigma}$
Call & Put:
$Vega = S N'(d_1) \sqrt{T-t}$
Rho:
$\rho = \frac{\partial C}{\partial r}$
Call:
$\rho = K(T-t)e^{-r(T-t)}N(d_2)$
Put:
$\rho = -K(T-t)e^{-r(T-t)}N(-d_2)$
Theta:
$\theta = \frac{\partial C}{\partial t}$
Call:
$\theta = \frac{S \sigma N'(d_1)}{\sigma \sqrt{T-t} } - rKe^{-r(T-t)} N(d_2)$
Put:
$\theta = \frac{S \sigma N'(d_1)}{\sigma \sqrt{T-t} } + rKe^{-r(T-t)} N(-d_2)$

Implementation:

First, we load the packages needed for this implementation:
the values of $d_1$ and $d_2$ are common for both calls and puts, so we define:
Now, we define a class for Calls including functions for the prices and the greeks:
another class for the puts and corresponding greeks:
The next function simply receives information of the option type (call/put), the parameter to calculate (price, delta, gamma, and so on) in addition to the numerical input data:
OK, now we can test the implementation by using, for instance:
which produces, for example:

By using this implementation, one can easily study strategies, such as butterflies and strangles:
which produces:



I hope you enjoyed this post! Good calculations for everyone!
May the Force be with you.

#=================================
Diogo de Moura Pedroso

Comments

  1. I should say only that its awesome! The blog is informational and always produce amazing things. Composite Frac Plugs

    ReplyDelete
  2. Nice blog. If you're in need of professional financial expertise for your business in Surat but don't require a full-time commitment, consider the option to hire a part-time accountant in Surat. Part-time accountants provide a valuable and flexible solution to meet your accounting and financial needs.

    ReplyDelete

Post a Comment