请将下面代码中的两张波动率微笑的图绘制到一张图中# -- coding: utf-8 -- """ Created on Sun May 28 18:08:36 2023 @author: lll """ import numpy as np import matplotlib.pyplot as plt from scipy.optimize import brentq from scipy.stats import norm # 定义BS模型计算期权价格的函数 def bs_price(S, K, r, T, sigma, option='call'): d1 = (np.log(S/K) + (r + 0.5sigma**2)T) / (sigmanp.sqrt(T)) d2 = d1 - sigmanp.sqrt(T) if option == 'call': price = Snorm.cdf(d1) - Knp.exp(-rT)norm.cdf(d2) else: price = Knp.exp(-rT)norm.cdf(-d2) - Snorm.cdf(-d1) return price # 定义计算隐含波动率的函数 def implied_vol(S, K, r, T, price, option='call'): def f(sigma): return bs_price(S, K, r, T, sigma, option) - price return brentq(f, 0.001, 10) # 定义计算波动率微笑图形的函数 def smile_vol(S, r, T, vol_list, K_list, option='call'): if len(vol_list) != len(K_list): raise ValueError("Lengths of vol_list and K_list must be equal.") implied_vol_list = [] for K, vol in zip(K_list, vol_list): price = bs_price(S, K, r, T, vol, option) implied_vol_list.append(implied_vol(S, K, r, T, price, option)) plt.plot(K_list, implied_vol_list) plt.xlabel('Strike') plt.ylabel('Implied Volatility') plt.title('Volatility Smile') plt.show() # 示例代码 S = 100 r = 0.05 T = 1 K_list = np.arange(80, 121, 9) vol_call_list = [0.2, 0.3, 0.4, 0.5, 0.6] vol_put_list = [0.6, 0.5, 0.4, 0.3, 0.2] smile_vol(S, r, T, vol_call_list, K_list, option='call') smile_vol(S, r, T, vol_put_list, K_list, option='put')
时间: 2024-02-15 13:03:16 浏览: 199
php-coding-standard:将各种代码质量工具组合到一个具有共享输出的命令中,以简化CI集成
以下是将两张波动率微笑的图绘制到一张图中的代码:
```python
# 示例代码
S = 100
r = 0.05
T = 1
K_list = np.arange(80, 121, 9)
vol_call_list = [0.2, 0.3, 0.4, 0.5, 0.6]
vol_put_list = [0.6, 0.5, 0.4, 0.3, 0.2]
# 绘制波动率微笑图形
implied_vol_call_list = []
implied_vol_put_list = []
for K, vol_call, vol_put in zip(K_list, vol_call_list, vol_put_list):
price_call = bs_price(S, K, r, T, vol_call, option='call')
implied_vol_call_list.append(implied_vol(S, K, r, T, price_call, option='call'))
price_put = bs_price(S, K, r, T, vol_put, option='put')
implied_vol_put_list.append(implied_vol(S, K, r, T, price_put, option='put'))
plt.plot(K_list, implied_vol_call_list, label='Call')
plt.plot(K_list, implied_vol_put_list, label='Put')
plt.xlabel('Strike')
plt.ylabel('Implied Volatility')
plt.title('Volatility Smile')
plt.legend()
plt.show()
```
在这个代码中,我们首先计算出每个期权的隐含波动率,然后分别将call和put的隐含波动率绘制在同一张图上。我们使用 `label` 和 `legend` 来标记每个曲线。注意,这里我们需要同时计算call和put的隐含波动率,因为它们的波动率微笑图形通常是不对称的。
阅读全文