Error in fzero usage
12 views (last 30 days)
Show older comments
Hi, 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
0 Comments
Accepted Answer
Torsten
on 21 Oct 2023
Edited: Torsten
on 21 Oct 2023
bs_price = blackScholes(sigma,S,K,r,T,r,q);
function resu = blackScholes(sigma,S,K,r,T,q)
Do you see the different number of input arguments in the function call and the function definition ?
And if you plot your function, you will see that it has no zeros:
S0 = 100;
K = 80;
r = 0.05;
T = 1.0;
mkt_price = 101.32;
q = 0.0;
sigma = 0.01:0.01:10;
resu = arrayfun(@(sigma)difference(sigma,S0,K,r,T,mkt_price,q),sigma);
plot(sigma,resu)
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,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
2 Comments
Torsten
on 21 Oct 2023
If I had to apologize for all my stupid programming errors, there would be quite a long list -:)
More Answers (0)
See Also
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!