I am I created a function that I need to find the zero of a function using the function fzero but when I try to use it it gives me error saying that I used too many arguments in input.
Could someone tell me where I am going wrong and how to fix it. I leave below a code sketch
clear variables; close all; clc
S0 = 100;
K = 80;
r = 0.05;
T = 1.0;
mkt_price = 101.32;
q = 0.0;
resu = impliedVola(S0,K,r,T,mkt_price,q)
function resu = impliedVola(S0,K,r,T,mkt_price,q)
options = optimset('fzero');
options = optimset(options,'TolX',1e-9,'Display','off');
[x,~,exitflag] = fzero(@difference, 0.5, options, ...
S0, K, r, T, mkt_price, q);
if(exitflag ~= 1)
disp('Did not find value')
resu = 0;
else
resu = x;
end
end
function resu = difference(sigma,S,K,r,T,mkt_price,q)
bs_price = blackScholes(sigma,S,K,r,T,r,q);
resu = mkt_price - bs_price;
end
function resu = blackScholes(sigma,S,K,r,T,q)
d1 = (log(S./K) + (r - q + 0.5*sigma^2).*T) ./ (sigma.*sqrt(T));
d2 = d1 - sigma*sqrt(T);
resu = S*exp(-r*T)*normal(d1,0,1) - K*exp(-r*T)*normal(d2,0,1);
end
function resu = normal(x,mu,sigma)
z = (x - mu) ./ sigma;
resu = 0.5 * erfc(-z ./ sqrt(2));
end
The syntax of fzero is:
x = fzero(fun,x0,options);
So adding arguments after variable options will produce an error. If those arguments are parameters for the difference function, you can use:
[x,~,exitflag] = fzero( @(y)difference(y,S0,K,r,T,mkt_price,q), 0.5, options);
I hope it helps.
Best