How to compute the Black Scholes model in Python
• 1 minThe Black-Scholes model is a widely used model for pricing European call and put options. In Python, you can compute the Black-Scholes model by using the following formula:
import math
def black_scholes(S, K, T, r, sigma, option_type):
d1 = (math.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * math.sqrt(T))
d2 = d1 - sigma * math.sqrt(T)
if option_type == "call":
return S * math.norm.cdf(d1) - K * math.exp(-r * T) * math.norm.cdf(d2)
else: # option_type == "put"
return K * math.exp(-r * T) * math.norm.cdf(-d2) - S * math.norm.cdf(-d1)
The black_scholes
function takes the following parameters:
S
: the current price of the underlying assetK
: the strike price of the optionT
: the time to expiration of the option in yearsr
: the risk-free interest ratesigma
: the volatility of the underlying assetoption_type
: the type of option, either "call" or "put"
The function returns the price of the European call or put option based on the Black-Scholes model. The cumulative normal distribution function math.norm.cdf
is used to calculate the probabilities associated with the standard normal distribution.