2

My data is currently an xts or zoo object of daily stock prices per row and each column is a different company.

library(quantmod)
getSymbols("AAPL;MSFT;YHOO")
closePrices <- merge(Cl(AAPL),Cl(MSFT),Cl(YHOO))

I am still new to R and need some assistance reproducing this Excel function. My first thought was to split the function into numerator and denominator, and then compute the index:

dailyDiff <- abs(diff(closePrices,1))
numerJ <- diff(closePrices,10)
denomJ <- as.xts(rollapply(dailyDiff,11, sum))
idx <- abs(numerJ/denomJ)

This was great because the values for each portion were accurate, but are aligned by incorrect dates for denomJ. For example, the tail of numerJ goes to 6/21/2012, while the tail of denomJ goes to 6/14/2012.

The output that I am looking for is:

  • 6/21/2012 = .11
  • 6/20/2012 = .27
  • 6/19/2012 = .46
  • 6/18/2012 = .39
  • 6/15/2012 = .22
4

2 回答 2

2

您可以使用 和 的组合diffrunSum或者rollapplyr

#Get the data
library(quantmod)
getSymbols("AAPL")

我认为这就是你想要做的(注意使用lag参数 todiff.xtsn参数 to 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不是您正在寻找的答案。如果我按原样获取您的代码,除了我更改rollapplyrollapplyr,它看起来就像您正在寻找的输出一样。

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

另外,请注意,如果您使用,两者numerJdenomJ在同一日期结束rollapplyr(这与使用rollapplywith相同align="right"

end(numerJ); end(denomJ)
#[1] "2012-07-20"
#[1] "2012-07-20"

雅虎错误

也许您看到的问题是雅虎错误,有时——例如,现在——雅虎复制最后(按时间顺序)数据行。如果是这样,请在尝试使用数据进行计算之前尝试删除重复的行。

tidx <- tail(index(closePrices), 2)
if(tidx[1] == tidx[2]) {
  closePrices <- closePrices[-NROW(closePrices), ]
}
于 2012-07-21T19:42:54.207 回答
2

如果没有确切的数据,很难准确判断您的问题是什么,但问题似乎与rollapply. 除非参数设置为 ,rollapply否则只会将该函数应用于整个间隔。考虑以下示例partialTRUE

require(zoo)
#make up some data
mat <- matrix(1:100,ncol=2)
colnames(mat) <- c("x1","x2")
dates <- seq.Date(from=as.Date("2010-01-01"),length.out=50,by="1 day")
zoo.obj <- zoo(mat,dates)
#apply the funcitons
numerJ <- diff(zoo.obj,10)  #dates okay
denomJ <- rollapply(zoo.obj,11, sum,partial=TRUE)  #right dates
denomJ2 <- rollapply(zoo.obj,11,sum) #wrong dates
index <- abs(numerJ/denomJ)  #right dates
于 2012-07-21T12:01:19.577 回答