set.seed(1)
n <- 100
ret <- rnorm(n, 0, 0.02)
ret[1] <- 0
price <- cumprod(1+ret)*100
maxi <- 0
drawdown <- rep(0, n)
for (i in 1 : n){
maxi <- max(price[1 : i])
drawdown[i] <- price[i] / maxi - 1
}
您好,
是否可以加快此计算?也许删除for循环?
此致
答案 0 :(得分:6)
R具有矢量化cummax
函数,并且除法和加法运算也是矢量化的,因此您可以这样做:
price/cummax(price) - 1
比较n <- 10000
:
library(microbenchmark)
microbenchmark(
OP= {
drawdown <- rep(0, n)
for (i in 1 : n){
maxi <- max(price[1 : i])
drawdown[i] <- price[i] / maxi - 1
}
},
me={
drawdown2 <- price/cummax(price) - 1
}, times=10)
# Unit: microseconds
# expr min lq mean median uq max neval
# OP 456216.519 483387.361 536067.7521 550912.471 565453.555 663352.635 10
# me 98.075 102.067 107.5978 105.203 112.331 127.726 10
identical(drawdown, drawdown2)
# [1] TRUE