Error in fzero usage
13 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Torsten
le 21 Oct 2023
Modifié(e) : Torsten
le 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 commentaires
Torsten
le 21 Oct 2023
If I had to apologize for all my stupid programming errors, there would be quite a long list -:)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
