I understand that there is an error with dimensions in line dr=(r-v*v/2)*dT . But I have little knowledge of Matlab. Help to fix it, please. The code is small and simple. Maybe someone will find time to look
function [optionPrice] = upAndOutCallOption(S,r,v,x,b,T,dT)
t = 0;
dr=[];
pert=[];
while (t < T) & (S < b)
t = t + dT;
dr = (r - v.*v./2).*dT;
pert = v.*sqrt( dT ).*randn();
S = S.*exp(dr + pert);
end
if S<b
% Within barrier, so price as for a European option.
optionPrice = exp(-r.*T).* max(0, S - x);
else
% Hit the barrier, so the option is withdrawn.
optionPrice = 0;
end
end
Call from another function of this kind:
for k=1:amountOfOptions
[optionPrices(k)] = upAndOutCallOption(stockPrice(k)*o,riskFreeRate(k)*o,... volatility(k)*o, strike(k)*o, barrier(k)*o, timeToExpiry(k)*o, sampleRate(k)*o);
result(k) = mean(optionPrices(k));
end
Therefore, any difficulties.
It's good that you know the problem is within dr = (r - v.*v./2).*dT;
. The command itself has many possible problems which also related to dimensions
:
Here you are doing element-wise multiplication (because of the .*
) with matrices, which requires (in the case of your command) that r
has the same number of rows AND columns as v
(since because of element-wise, v.*v/2
has the same size as v
).
Moreover, it is unnecessary to do element-wise division with scalar number, that means there is no need to have ./2
in Matlab.
And, finally, since it's element-wise multiplication again, the matrix (r - v.*v./2)
must also have the same number of rows and columns as matrix dT
.
Check here for more information about Matlab's matrix operations.