您可以使用diff
,要麼runSum
或rollapplyr
#Get the data
library(quantmod)
getSymbols("AAPL")
我認爲這是一個組合你想要做什麼(請注意使用的lag
說法來diff.xts
,並且n
參數runSum
)
out <- diff(Cl(AAPL), lag=10)/runSum(abs(diff(Cl(AAPL))), n=11)
tail(out['/2012-06-21'])
# AAPL.Close
#2012-06-14 -0.1047297
#2012-06-15 0.2176938
#2012-06-18 0.3888185
#2012-06-19 0.4585821
#2012-06-20 0.2653782
#2012-06-21 0.1117371
編輯
在你的問題的進一步的審查,我不明白爲什麼rollapplyr
是不是你要找的答案。如果我把你的代碼完全一樣,除了我將rollapply
更改爲rollapplyr
,它在我看來就像是你正在尋找的輸出。
dailyDiff <- abs(diff(closePrices,1))
numerJ <- diff(closePrices,10)
denomJ <- as.xts(rollapplyr(dailyDiff,11, sum))
idx <- abs(numerJ/denomJ)
# AAPL.Close MSFT.Close YHOO.Close
#2012-06-14 0.1047297 0.03826531 0.06936416
#2012-06-15 0.2176938 0.35280899 0.25581395
#2012-06-18 0.3888185 0.33161954 0.31372549
#2012-06-19 0.4585821 0.47096774 0.34375000
#2012-06-20 0.2653782 0.32644628 0.23750000
#2012-06-21 0.1117371 0.18997912 0.10256410
另外,還要注意兩個numerJ
和denomJ
,如果使用rollapplyr
(這是與使用rollapply
與align="right"
)同日兩端
end(numerJ); end(denomJ)
#[1] "2012-07-20"
#[1] "2012-07-20"
雅虎錯誤
也許你看到的問題是有時候的雅虎錯誤 - 例如,現在 - 雅虎重複了最後一個(chron數據的一行)。如果是這樣,請在嘗試使用數據進行計算之前嘗試刪除重複的行。
tidx <- tail(index(closePrices), 2)
if(tidx[1] == tidx[2]) {
closePrices <- closePrices[-NROW(closePrices), ]
}
既然我已經使您的示例具有可重現性,請您重新訪問您的問題並提供一些預期的輸出結果?另外,請描述「日期錯誤」和「idx包含錯誤值」的含義。 – 2012-07-21 12:53:53
謝謝!編輯。希望它澄清我的兩個xts/zoo對象numerJ和denomJ正在生成準確的數字(numerJ @ 6/21 = 5.95和denomJ @ 6/21 = 53.25)。但是作爲rollapply函數的結果,它與我不想要的日期值對齊。 – jonnie 2012-07-21 18:21:00
我完全不理解你的問題。你的Excel功能讓我更加困惑,因爲它的標籤很差。 Re:你最近的評論,我沒有看到任何地方的53.25號碼。也就是說,根據您對日期對齊的抱怨,我幾乎可以肯定,答案是您需要在'rollapply'調用中使用'align = right'(或使用'rollapplyr'包裝器)。見'?rollapply' – GSee 2012-07-21 18:34:46