在 R 中模拟一个过程 n 次

问题描述

我编写了一个 R 脚本(源自 here)来模拟股票价格的几何布朗运动路径,我需要模拟运行 1000 次,以便生成 1000 条过程路径Ut = Ste^-mu*t,通过对从 Ut 导出的运动定律进行离散化,Ut 是解决问题 here 的底线。

该过程还有 n = 252 步和离散化步长 = 1/252,还有 sigma = 0.4 和瞬时漂移 mu 的风险,我将其视为零,尽管我对此不确定。我正在努力模拟过程的 1000 条路径,但能够生成一条路径,我不确定我需要更改哪些变量,或者我的 for 循环中是否存在限制我生成所有 1000 条路径的问题。也可能是脚本模拟了每个单独的点进行 252 实现,而不是模拟整个过程?如果是这样,这会限制我生成所有 1000 条路径吗?是否也有可能我生成的数组定义为 U 没有被我正确生成? U[0] 必须等于 1,因此第一个实现 U(1) = 1 也必须如此。代码如下,我很难弄清楚这一点,因此感谢任何帮助。

#Simulating  Geometric brownian motion (GMB)
tau <- 1 #time to expiry
N <- 253 #number of sub intervals
dt <- tau/N #length of each time sub interval
time <- seq(from=0,to=N,by=dt) #time moments in which we simulate the process
length(time) #it should be N+1

mu <- 0 #GBM parameter 1
sigma <- 0.4 #GBM parameter 2
s0 <- 1 #GBM parameter 3

#simulate Geometric brownian motion path
dwt <- rnorm(N,mean = 0,sd = 1) #standard normal sample of N elements
dW <- dwt*sqrt(dt) #brownian motion increments
W <- c(0,cumsum(dW)) #brownian motion at each time instant N+1 elements


#Define U Array and set initial values of U
U <- array(0,c(N,1)) #array of U
U[0] = 1
U[1] <- s0 #first element of U is s0. with the for loop we find the other N elements

for(i in 2:length(U)){
  U[i] <- (U[1]*exp(mu - 0.5*sigma^2*i*dt + sigma*W[i-1]))*exp(-mu*i)
}

#Plot 
plot(ts(U),main = expression(paste("Simulation of Ut")))

解决方法

这个问题很难回答,因为有很多不清楚的东西,至少对我来说是这样。

首先,length(time) 等于 64010,而不是 N + 1,后者为 254。

如果我理解正确,布朗运动函数会返回给定时间的一维位置。因此,要计算每次的位置,以下内容就足够了:

s0*exp((mu - 0.5*sigma^2)*time + sigma*rnorm(length(time),time))

然而,这计算的是 64010 点,而不是 253。如果你复制 1000 次,它给出 64010000 点,这是相当多的。

> B <- 1000
> res <- replicate(B,{
+   s0*exp((mu - 0.5*sigma^2)*time + sigma*rnorm(length(time),time))
+ })
> length(res)
[1] 64010000
> dim(res)
[1] 64010  1000

我知道我错过了第二部分,其中解释了 here,但实际上我并不完全了解您在那里需要什么。如果你能画出公式,也许我可以帮你。

一般来说,避免在 R 中使用 for 循环来迭代向量进行编程。 R 是一种矢量化语言,没有必要这样做。如果您想运行相同的代码 B 次,replicate(B,{ your code }) 函数就是您的目标。