Search code examples
matlabmontecarloconfidence-interval

Monte Carlo simulation for approximating delta in Matlab


I need to code the Monte Carlo algorithm for approximating delta to Matlab and calculate confidence intervals: algorithm

but for some reason my code doesn't work, any ideas why?

randn('state', 100)

%Problem and method parameters
S=10; E=9; sigma=0.1; r=0.06; T=1;
Dt=1e-3; N=T/Dt; M=2^17;h=10^(-4);

 delta = zeros(M,1);
  for i = 1:M
  Sfinal = S*exp((r-0.5*sigma^2)*T+sigma*sqrt(T).*randn(M,1));
  S_h = (S+h)*exp((r-0.5*sigma^2)*T+sigma*sqrt(T).*randn(M,1));
  delta(i) = exp(-r*T).*(max(Sfinal-E,0)-max(S_h-E,0))/h;
end
aM=mean(delta); 
bM=std(delta);
conf=[aM-1.96*bM/sqrt(M),aM+1.96*bM/sqrt(M)]

The error message is

"Unable to perform assignment because the left and right sides have a different number of elements."

Any help is appreciated!


Solution

  • You do not need to explicitly write the for loop since you have already vectorized it. In other words, Sfinal and S_h are vectors of length M, and their i-th entries correspond to S_i and S^h_i in the image. Since the right hand side of the delta expression evaluates to a vector of length M, which contains all the values of delta, you should assign that vector directly to delta, not delta(i).

    One more thing: the pseudo-code in the image seems to suggest that the same random number should be used for calculating both S_i and S^h_i. This is not the case in your code, since you call randn separately for calculating Sfinal and S_h. I think you should generate the random samples once, save them, and then use it for both calculations.

    Here's the code:

    randn('state', 100)
    
    %Problem and method parameters
    S=10; E=9; sigma=0.1; r=0.06; T=1;
    Dt=1e-3; N=T/Dt; M=2^17;h=10^(-4);
    
    xi = randn(M,1);
    Sfinal = S*exp((r-0.5*sigma^2)*T+sigma*sqrt(T).*xi);
    S_h = (S+h)*exp((r-0.5*sigma^2)*T+sigma*sqrt(T).*xi);
    delta = exp(-r*T).*(max(Sfinal-E,0)-max(S_h-E,0))/h;
    
    aM=mean(delta); 
    bM=std(delta);
    conf=[aM-1.96*bM/sqrt(M),aM+1.96*bM/sqrt(M)]