matlab计算期权隐含波动率的代码并画出波动率微笑图
时间: 2023-08-04 12:04:29 浏览: 422
计算期权隐含波动率的代码:
```matlab
function [iv, K] = implied_volatility(S, K, r, T, C, type)
% S: underlying asset price
% K: strike price
% r: risk-free interest rate
% T: time to maturity (in years)
% C: call option price
% type: 'call' or 'put'
tol = 1e-6;
max_iter = 100;
% Define the objective function
if strcmp(type, 'call')
obj_fun = @(sigma) (bsprice(S, K, r, T, sigma, type) - C)^2;
elseif strcmp(type, 'put')
obj_fun = @(sigma) (bsprice(S, K, r, T, sigma, type) - C)^2;
end
% Use fminbnd to find the implied volatility
[iv, ~, exitflag] = fminbnd(obj_fun, tol, 1, optimset('MaxIter', max_iter));
if exitflag ~= 1
warning('Implied volatility not found');
end
end
function [price, delta, gamma, vega, theta] = bsprice(S, K, r, T, sigma, type)
% S: underlying asset price
% K: strike price
% r: risk-free interest rate
% T: time to maturity (in years)
% sigma: volatility
% type: 'call' or 'put'
d1 = (log(S/K) + (r + 0.5*sigma^2)*T) / (sigma*sqrt(T));
d2 = d1 - sigma*sqrt(T);
if strcmp(type, 'call')
price = normcdf(d1)*S - normcdf(d2)*K*exp(-r*T);
delta = normcdf(d1);
gamma = normpdf(d1) / (S*sigma*sqrt(T));
vega = S*normpdf(d1)*sqrt(T);
theta = (-S*normpdf(d1)*sigma/(2*sqrt(T)) - r*K*exp(-r*T)*normcdf(d2)) / 365;
elseif strcmp(type, 'put')
price = normcdf(-d2)*K*exp(-r*T) - normcdf(-d1)*S;
delta = normcdf(d1) - 1;
gamma = normpdf(d1) / (S*sigma*sqrt(T));
vega = S*normpdf(d1)*sqrt(T);
theta = (-S*normpdf(d1)*sigma/(2*sqrt(T)) + r*K*exp(-r*T)*normcdf(-d2)) / 365;
end
end
```
其中,bsprice函数计算了Black-Scholes期权定价公式中的期权价格、希腊字母(delta、gamma、vega和theta),implied_volatility函数使用fminbnd函数寻找隐含波动率。
绘制波动率微笑图的代码:
```matlab
S = 100; % underlying asset price
K = [80:5:120]; % strike prices
r = 0.05; % risk-free interest rate
T = 1; % time to maturity (in years)
C = [20.54 16.06 12.36 9.36 7.05 5.30 4.03 3.11 2.46 1.99 1.68]; % call option prices
P = [1.39 3.10 5.15 7.13 9.08 10.98 12.76 14.34 15.68 16.78 17.63]; % put option prices
% Calculate implied volatilities for call options
iv_call = zeros(size(K));
for i = 1:length(K)
iv_call(i) = implied_volatility(S, K(i), r, T, C(i), 'call');
end
% Calculate implied volatilities for put options
iv_put = zeros(size(K));
for i = 1:length(K)
iv_put(i) = implied_volatility(S, K(i), r, T, P(i), 'put');
end
% Plot implied volatilities as a function of strike price
plot(K, iv_call, 'b-', K, iv_put, 'r-');
xlabel('Strike price');
ylabel('Implied volatility');
title('Volatility smile');
legend('Call options', 'Put options');
```
其中,我们假设有11个不同的行权价,对应的看涨期权和看跌期权的价格分别为C和P。我们使用implied_volatility函数计算每个行权价对应的隐含波动率,并绘制出波动率微笑图。
阅读全文