[英]Using R for loop to create a time series
I'm forecasting a stock price 'St1' starting at 'Stt = 10' at time t.我预测股票价格 'St1' 从时间 t 的 'Stt = 10' 开始。 Dates are not important.日期并不重要。 I want to find the next 100 prices using the following formula:我想使用以下公式找到接下来的 100 个价格:
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.所以我从 10 开始,然后需要接下来的 100 个值并将其放入 data.frame 或任何简单的东西。 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))
}
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
循环,并且为了对E
使用rnorm
,此代码可以工作:
# 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))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.