0

I'm simulating a one-dimensional and symmetric random walk procedure:

$$y_t=y_{t-1}+\varepsilon_t$$

where white noise is denoted by $\varepsilon_t \sim N(0,1)$ in time period $t$. There is no drift in this procedure.

Also, RW is symmetric, because $Pr(y_i=+1)=Pr(y_i=-1)=0.5$.

Here's my code in R:

set.seed(1)
t=1000
epsilon=sample(c(-1,1), t, replace = 1)

y<-c()
y[1]<-0
for (i in 2:t) {
  y[i]<-y[i-1]+epsilon[i]
}
par(mfrow=c(1,2))
plot(1:t, y, type="l", main="Random walk")
outcomes <- sapply(1:1000, function(i) cumsum(y[i]))
hist(outcomes)

I would like to simulate 1000 different $y_{it}$ series (i=1,...,1000;t=1,...,1000). (After that, I will check the probability of getting back to the origin ($y_1=0$) at $t=3$, $t=5$ and $t=10$.

Which function does allow me to do this kind of repetition with $y_t$ random walk time-series?

CuriousBeing
  • 1,592
  • 14
  • 34
Übel Yildmar
  • 491
  • 1
  • 9
  • 24

1 Answers1

1

Try the following:

length_of_time_series <- 1000
num_replications <- 1000

errors <- matrix(rnorm(length_of_time_series*num_replications),ncol=num_replications)
rw <- apply(errors, 2, cumsum)

This creates 1000 random walks simultaneously by first defining a matrix filled with white noise error terms drawn from a standard normal distribution, and in the second step I calculate the cumulative sums, which should correspond to your random walk, assuming that y_0=0.

Note that I have ignored that your errors are either -1 or 1, since I am not sure that this is what you intended. Having said that, you can adjust the above code easily with the following line to create errors that are either 1 or -1:

 errors2 <- ifelse(errors > 0, 1, -1)

If you really want to go the way of doing it repeatedly as opposed to doing it simultaneously, you can define a function that returns the random walk, and use replicate. Note that you should not hardcode the seed inside the function to avoid replicating the same random walk all the time.

coffeinjunky
  • 11,254
  • 39
  • 57