for ループなしでこれを行う方法はわかりませんが、以下のソリューションはかなり高速です (2.2Ghz ラップトップで 10,000 行あたり約 1 秒)。
coredata
xts オブジェクトの を取得し、dim
属性を ( 経由で) ドロップしていることに注意してくださいdrop
。これはベクトルを返します。これを行うのは、xts/zoo の数学演算がインデックスで整列するためです。そのため、収益を計算する前に分子からインデックスを削除する必要があります。
ただし、これにより、分子がクラスでNextMethod
分母がクラスであるため、除算ディスパッチが呼び出されます。数値ベクトルで除算を実行することにより、そのオーバーヘッドを回避します。numeric
xts
library(quantmod)
getSymbols("^GSPC",from="1900-01-01")
x <- Ad(GSPC)
lookback <- function(x, p) {
# lookback() assumes x is xts
# select first column, take coredata, drop dims
dcx <- drop(coredata(x[,1]))
# initialize result object
f <- dcx*NA
# loop over all rows in 'x'
for(i in 1:nrow(x)) {
# Calculate cumulative return through today
r <- dcx[i]/dcx-1 # or log(dcx[i]/dcx)
# This really slows things down:
# r <- dcx[i]/x-1
#
# Find which returns are greater than 'p'
w <- which(abs(r[1:i]) > p)
# If any returns are greater than 'p', then
# record the closest location to 'p'
if(length(w)!=0)
f[i] <- max(w)-i
}
# return an xts object
xts(f, index(x))
}
nrow(x)
# [1] 15791
system.time(lookback(x,0.02))
# user system elapsed
# 15.761 0.152 16.040