2
$\begingroup$

I am doing some work with black-scholes. As commented within my code, I need my while loop to run 100 times. I am not sure if the best way to do this is with a nested argument or placing a for loop or another while within the while already.

dt = .0001;
mu = 0;
gamma = .005;
t = .0833;
i = t/dt;
random = RandomVariate[NormalDistribution[0, dt^.5], 10^2];
Z = Table[0, 10^2 + 1];
Z[[1]] = .0158;
i = 2;
While[i <= 834,
Z[[i]] = Z[[i - 1]] + mu*dt + (gamma)*random[[i - 1]];
i++
];
(*have to make this loop 100 times*) 
ListPlot[Z, DataRange -> {0, 100*dt}, PlotRange -> All];
Print[Z];
$\endgroup$
6
$\begingroup$

Define random using SetDelayed so that each time it is used it gives a different random vector:

lngth = 834;
rndm := RandomVariate[NormalDistribution[0, dt^.5], lngth - 1]

Instead of using a loop you can use

Prepend[Accumulate[rndm] gamma + mu dt + .0158, .0158]

to get a random vector of length 834.

You can use the above with Table to generate as many random vectors as you like:

k = 20;
SeedRandom[1]
W = Table[Prepend[Accumulate[rndm] gamma + mu dt + .0158, .0158], k];

Visualize:

ListLinePlot[W, 
 DataRange -> {0, lngth  dt}, 
 ImageSize -> Large, 
 PlotLegends -> Range[20]]

enter image description here

SeedRandom[1]
k = 200;
W = Table[Prepend[Accumulate[rndm] gamma + mu dt + .0158, .0158], k];
ListLinePlot[W, DataRange -> {0,  lngth dt}, ImageSize -> Large, 
 PlotStyle -> Opacity[.25]]

enter image description here

| improve this answer | |
$\endgroup$
  • $\begingroup$ The graph is really beautiful but the the outputted W is not correct. It is supposed to give a list of 100X834. I am assuming K is influencing the list length, but even when I change K I do not get the correct dimensions. How do I fix this? $\endgroup$ – subrinarafiq Dec 20 '19 at 17:41
  • $\begingroup$ @sabrina, updated with a correction; now W is a 100X834 random matrix. $\endgroup$ – kglr Dec 24 '19 at 0:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.