Reputation: 1830
I want to run the following .m file in matlab:
function [relativeErrors] = plotRelativeErrors()
initialPrice = 115.47;
sigma = 1.34*10^(-2);
tau = 0;
days = 40;
Strike = 114;
Time = days/365;
[callSol, ~] = blsprice(initialPrice, Strike, tau, Time, sigma);
termOne = (tau - (sigma^2)/2)*days;
termTwo = sigma * sqrt(days);
relativeErrors = [];
for i = 1:8
max = 0;
N = 10^i;
for n = 1:50
v = intern_eurValue(Strike, initialPrice, days, N, termOne, termTwo);
difference = abs(v-callSol);
if difference > max
max = difference;
end
end
relativeErrors(end+1) = max;
end
end
function [value] = intern_eurValue(strike, price, days, N, termOne, termTwo)
prices = intern_simulateEndPrice(price, termOne, termTwo, days, N);
theMean = mean(prices);
value = theMean - strike;
if value < 0
value = 0;
end
end
function [prices] = intern_simPrice(initialPrice, termOne, termTwo, days, N)
prices = [];
for i = 1:N
termTwo = termTwo * normrnd(0,1);
exponential = exp(termOne + termTwo);
prices(end+1,1) = initialPrice * exponential;
end
end
The problem is that running this will take over a day, if not more to complete calculating. I had to call it quits after it was running for 14 hours and wasn't halfway done. I have already tried to optimize runtime by delegating most of the computations that are static from intern_simPrice
to plotRelativeErrors
and passing the results through termOne
and termTwo
, but I barely notice any progression.
I don't think this can be reduced in terms of less computations, but perhaps it can be switched to something that would calculate faster.
Upvotes: 0
Views: 93
Reputation: 6084
Disclaimer: The following approaches will help you reach usable speeds, but will not reduce the time complexity, per se.
If your computation is slow, first thing to do is to use the profiler to find out what's slowing you down. In your case its intern_simPrice
and especially millions of calls to normrnd
.
It's usually a lot faster to let a function compute multiple values in one call. So, first thing you should replace:
for i = 1:N
termTwo = termTwo * normrnd(0,1);
....
end
with
X_norm = normrnd(0,1,1,N); % Generate N random values simultaneously
for i = 1:N
termTwo = termTwo * X_norm(i);
....
end
If you know how long your arrays are going to be, it's also smarter to allocate them in advance. So you should replace:
prices = []
for i = 1:N
prices(end+1) = ...
with
prices = zeros(N,1);
for i = 1:N
prices(i) = ...
Sometimes for
loops can be replaced by a vectorized version.
In your case this would be:
Replacing the function intern_simPrice
altogether and just using:
prices = initialPrice*exp(termOne + termTwo*cumprod(normrnd(0,1,N,1)));
Upvotes: 2