为xts应用函数

我的数据当前是每行每日股价的xt或zoo对象,每一列是不同的公司。

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

我还是R新手,需要一些帮助来重现这个Excelfunction 。 我的第一个想法是将函数分解为分子和分母,然后计算索引:

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

这很棒,因为每个部分的值都是准确的,但是denomJ的date不一致。 例如,numerJ的尾部到2012年6月21日,而denomJ的尾部到2012年6月14日。

我正在寻找的输出是:

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

如果没有确切的数据,很难确切地说出你的问题是什么,但是问题似乎rollapplyrollapply将只应用整个时间间隔的函数,除非参数partial设置为TRUE 。 考虑下面的例子

 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 

您可以使用diffrunSumrollapplyr

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

我认为这是你正在做的事情(注意diff.xts参数使用lag参数, diff.xts使用n参数)

 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 

另外,请注意,如果使用rollapplyr (与使用align="right" rollapply相同),则numerJdenomJ都将在同一date结束。

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

雅虎Bug

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

 tidx <- tail(index(closePrices), 2) if(tidx[1] == tidx[2]) { closePrices <- closePrices[-NROW(closePrices), ] }