cJc
cJc

Reputation: 863

Using R for loop to create a time series

I'm forecasting a stock price 'St1' starting at 'Stt = 10' at time t. Dates are not important. I want to find the next 100 prices using the following formula:

St1 <- Stt*exp((r-0.5*sigma^2)*T/n+sigma*E*sqrt(T/n))

So I'm starting with 10 and then need the next 100 values and put it in a data.frame or whatever is easy. How do I do this? I'm stuck trying this...

Stt = 10
r = 0.15
sigma = 0.2
T = 1
n = 100
E = 0.15

St1 = Stt
for (i in 1:100)
{
    St1[i] <- Stt*exp((r-0.5*sigma^2)*T/n+sigma*E*sqrt(T/n))
}

Upvotes: 1

Views: 1103

Answers (1)

Karsten W.
Karsten W.

Reputation: 18420

One way is this

r = 0.15
sigma = 0.2
T = 1
n = 100
E = 0.15

Stt<- rep(NA,n) # preallocate
Stt[1] <- 10
for (i in 2:100)
{
    Stt[i] <- Stt[i-1]*exp((r-0.5*sigma^2)*T/n+sigma*E*sqrt(T/n))
}

Without for loop, and in order to use rnorm for E, this code could work:

# for fixed E of length one
Stt <- cumprod(c(10,rep(exp((r-0.5*sigma^2)*T/n+sigma*E*sqrt(T/n)), n-1)))

# for random vector E 
E <- rnorm(n-1, mean=0.15, sd=0.01)
Stt <- cumprod(c(10, exp((r-0.5*sigma^2)*T/n+sigma*E*sqrt(T/n))))

Upvotes: 1

Related Questions