股票价格模拟R代码-慢-蒙特卡洛 [英] Stock Price Simulation R code - Slow - Monte Carlo
问题描述
我需要使用R代码执行股价模拟.问题是代码有点慢. 基本上,我需要模拟每个时间步(每天)的股价并将其存储在矩阵中.
I need to perform a stock price simulation using R code. The problem is that the code is a little bit slow. Basically I need to simulate the stock price for each time step (daily) and store it in a matrix.
假设库存过程为几何布朗运动"的示例
An example assuming the stock process is Geometric Brownian Motion
for(j in 1:100000){
for(i in 1:252){
S[i] <- S[i-1]*exp((r-v^2/2)*dt+v*sqrt(dt)*rnorm(1))
}
U[j,] <- S
}
是否有任何改进和加快代码速度的建议?
Any suggestion to improve and speed up the code?
推荐答案
假设S[0] = 1
,您可以按照以下步骤构建U:
Assuming S[0] = 1
, you can build U as a follows:
Ncols <- 252
Nrows <- 100000
U <- matrix(exp((r-v^2/2)*dt+v*sqrt(dt)*rnorm(Ncols*Nrows)), ncol=Ncols, nrow=Nrows)
U <- do.call(rbind, lapply(1:Nrows, function(j)cumprod(U[j,])))
使用约书亚和本的建议:
using Joshua's and Ben's suggestions:
产品版本:
U <- matrix(exp((r-v^2/2)*dt+v*sqrt(dt)*rnorm(Ncols*Nrows)), ncol=Ncols, nrow=Nrows)
U <- t(apply(U, 1, cumprod))
总和版本:
V <- matrix((r-v^2/2)*dt+v*sqrt(dt)*rnorm(Ncols*Nrows), ncol=Ncols, nrow=Nrows)
V <- exp( t(apply(V, 1, cumsum)) )
由@Paul建议:
每个提案的执行时间(使用10000行而不是10 ^ 5):
Execution time for each proposal (using 10000 rows instead of 10^5):
使用apply + cumprod
user system elapsed
0.61 0.01 0.62
使用apply + cumsum
user system elapsed
0.61 0.02 0.63
使用OP的原始代码
user system elapsed
67.38 0.00 67.52
注意:上面显示的时间是system.time
的第三小节.每个代码的前两个度量均被丢弃.我用过r <- sqrt(2)
,v <- sqrt(3)
和dt <- pi
.在他的原始代码中,我还用S[i-1]
替换了ifelse(i==1,1,S[i-1])
,并预先分配了U
.
Notes: The times shown above are the third measures of system.time
. The first two measures for each code were discarded. I've used r <- sqrt(2)
, v <- sqrt(3)
and dt <- pi
. In his original code, I've also replaced S[i-1]
for ifelse(i==1,1,S[i-1])
, and preallocated U
.
这篇关于股票价格模拟R代码-慢-蒙特卡洛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!