Error in fzero usage
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Simone Perotti
am 21 Okt. 2023
Kommentiert: Torsten
am 21 Okt. 2023
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 Kommentare
Akzeptierte Antwort
Torsten
am 21 Okt. 2023
Bearbeitet: Torsten
am 21 Okt. 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 Kommentare
Torsten
am 21 Okt. 2023
If I had to apologize for all my stupid programming errors, there would be quite a long list -:)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
