我沒有看到任何方式做到這一點沒有for循環,但下面的解決方案是相當快(我的2.2Ghz筆記本電腦每10,000行約1秒)。
請注意,我服用XTS的coredata
對象並丟棄dim
屬性(經由drop
),它返回一個矢量。我這樣做是因爲xts/zoo中的數學運算按索引對齊,所以您需要從分子中刪除索引,然後才能計算回報。
但是,由於分子爲numeric
類,分母爲xts
類,因此會導致分配調用NextMethod
。我通過在數值向量上執行除法來避免這種開銷。
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
你能提供一些數據的例子嗎?當我們不知道你的輸入數據是什麼樣的時候,試圖生成解決方案是非常困難的。 – thelatemail
使用'dput(head(data))'給我們一個子集,你可以更新你的答案。 – Maiasaura