简体   繁体   中英

Creating a matrix from using a nested for loop in R

An overview of what I'm trying to do: I am currently simulating stock prices using a specific function which I have managed to code in R:

for(i in 2:252){
  X[1]<- 83.26
  X[i] <- X[i-1]*(1+mu*dt)+sigma*X[i-1]*sqrt(dt)*rnorm(1)}

I am simulating this for 252 days to generate one trajectory. The above works perfectly.

I now need to generate 100 trajectories using the above code and have been told to add an additional for loop around the above in order to generate 100 trajectories and save the results in a matrix.

So far I have:

Y<- matrix(NA, nrow=100, ncol=252)
for(j in 1:dim(X)[1]){

  for(i in 2:dim(X)[2]){
    X[1]<- 83.26
    X[i] <- X[i-1]*(1+mu*dt)+sigma*X[i-1]*sqrt(dt)*rnorm(1)}
}

which does not work nor do anything.

Basically what I want to do is create a matrix with 252 columns (representing days of different stock prices) with 100 rows (representing 100 differently generated paths)

Any help on how to do this would be greatly appreciated.

mu=0.0009646
sigma=0.0001471
dt=0.00796813

EDIT:

I now need to be able to plot each row of the matrix created as individual lines on a graph. Ie plot each trajectory against time, t.

mu <- 0.0009646
sigma <- 0.0001471
dt <- 0.00796813

X <- matrix(NA, nrow = 100, ncol = 252)

for (j in 1:dim(X)[2]) {
  X[1, j] <- 83.26
  for (i in 2:dim(X)[1]) {
    X[i, j] <-
      X[i - 1, j] * (1 + mu * dt) + sigma * X[i - 1, j] * sqrt(dt) * rnorm(1)
  }
}

i are the seperate days and j the seperate trajectories, so every column is a trajectory where the rows are the different days.

a way to plot your data:

library(ggplot2)
library(reshape2)

X <- data.frame(X)
X$day <- 1:NROW(X)

X_melt <- melt(X, id.vars = "day")

ggplot(data = X_melt, aes(x = day, y = value, group = variable)) +
  geom_line()

every line is a different trajectory

在此处输入图片说明

Riffing on Brett's solution,

Y<- matrix(NA, nrow=100, ncol=252)
for(j in 1:dim(Y)[1]){
  for(i in 2:dim(Y)[2]){
  X[1]<- 83.26
  X[i] <- X[i-1]*(1+mu*dt)+sigma*X[i-1]*sqrt(dt)*rnorm(1)}
Y[j, ] <- X
}

One issue you're having is asking R to compute dim(X) , which seems, given your first code chunk, like it should be a vector and thus have a length() but not a dim() .

So this solution uses your matrix Y to generate the dimensions you use to iterate.

The other issue is after you iterate each X 252 times, you're not storing those values. Hence, when you put Y[j, ] <- X , you take all of the values you creates for X and store them in the j -th row of Y .

I'm sure others will chime in with slicker solutions, but this one uses most of the code you've already written.

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM