写一段python代码实现:根据S0,u,d,T,N,K,r计算出BSM期权定价模型的波动率参数,并运用BSM期权定价模型计算欧式看涨期权和欧式看跌期权的价格
时间: 2024-05-15 15:13:09 浏览: 223
这里是一份实现:
```python
from math import log, sqrt, exp
from scipy.stats import norm
def bsm_call_price(S0, K, T, r, sigma):
d1 = (log(S0/K)+(r+0.5*sigma**2)*T)/(sigma*sqrt(T))
d2 = d1 - sigma * sqrt(T)
return S0 * norm.cdf(d1) - K * exp(-r*T) * norm.cdf(d2)
def bsm_put_price(S0, K, T, r, sigma):
d1 = (log(S0/K)+(r+0.5*sigma**2)*T)/(sigma*sqrt(T))
d2 = d1 - sigma * sqrt(T)
return K * exp(-r*T) * norm.cdf(-d2) - S0 * norm.cdf(-d1)
def calculate_volatility(S0, u, d, T, N, K, r, option_price, option_type):
tol = 0.0001
sigma = 0.5
for i in range(100):
price = 0
for j in range(N+1):
price += (u**j)*(d**(N-j))*bsm_call_price(S0*(u**j)*(d**(N-j)), K, T, r, sigma)
price /= (N+1)
if option_type == 'call':
vega = S0*norm.pdf((log(S0/K)+(r+0.5*sigma**2)*T)/(sigma*sqrt(T)))*sqrt(T)
else:
vega = S0*norm.pdf((log(S0/K)+(r+0.5*sigma**2)*T)/(sigma*sqrt(T)))*sqrt(T)
diff = price - option_price
if abs(diff) < tol:
return sigma
else:
sigma -= diff/vega
return sigma
S0 = 100
u = 1.2
d = 0.8
T = 1
N = 200
K = 105
r = 0.05
call_option_price = bsm_call_price(S0, K, T, r, 0.2)
put_option_price = bsm_put_price(S0, K, T, r, 0.2)
call_volatility = calculate_volatility(S0, u, d, T, N, K, r, call_option_price, 'call')
put_volatility = calculate_volatility(S0, u, d, T, N, K, r, put_option_price, 'put')
print('Call option price: ', round(call_option_price, 2))
print('Put option price: ', round(put_option_price, 2))
print('Call volatility: ', round(call_volatility, 2))
print('Put volatility: ', round(put_volatility, 2))
```
这段代码首先定义了两个函数,`bsm_call_price()` 和 `bsm_put_price()`,用于计算BSM模型中欧式看涨期权和欧式看跌期权的价格。然后定义了一个 `calculate_volatility()` 函数,用于计算波动率参数。
在主程序中,首先给定一些参数,如股票当前价格 `S0`,上涨和下跌的比例 `u` 和 `d`,到期时间 `T`,节点数 `N`,执行价格 `K` 和无风险利率 `r`。然后分别使用 `bsm_call_price()` 和 `bsm_put_price()` 计算了欧式看涨期权和欧式看跌期权的价格,再将这些价格传递给 `calculate_volatility()` 函数进行波动率参数计算。
最后,打印出计算得到的欧式看涨期权和欧式看跌期权的价格以及波动率参数。
阅读全文