按照Wikipedia 的定义,Ornstein–Uhlenbeck 过程由以下随机微分方程定义:
其中 是一个维纳过程,它的一个属性是它具有高斯增量,即
上述方程可以用以下方式离散化:
在哪里
由于维纳过程的高斯增量属性,我们有。这意味着可以使用sqrt(dt)*rnorm(1)生成增量值
我在 R 中编写了以下函数,它采用时间向量、过程平均值、标准差和 theta 值。
simulate <- function(t, mean=0, std=1, x0=mean, theta=1, number.of.points=length(t)){
# calculate time differences
dt <- diff(t)
X <- vector("numeric", length=number.of.points)
X[1] <- x0
for(i in 1:(number.of.points-1)){
X[i+1] <- X[i] + theta * (mean-X[i])*dt[i] + std * sqrt(dt[i])* rnorm(1)
}
data.frame(x=t, y=X)
}
simulate(t=1:200) %>% ggplot(aes(x,y)) + geom_line()
另一个使用purrr的实现
simulate <- function(t, mean=0, sd=1, theta=1, number.of.points=length(t)){
stopifnot(!missing(t) | !missing(number.of.points))
if(missing(t)){
t <- 1:number.of.points
}
unlist(purrr::accumulate2(vector("numeric", length=number.of.points-1), diff(t), function(x, o, y) {
x + theta*(mean - x)* y + sqrt(y)*rnorm(1)
}, .init=x0), use.names=F) -> X
data.frame(x=t, y=X)
}
simulate(number.of.points=200) %>% ggplot(aes(x,y)) + geom_line()