2012-07-21 88 views
2

我的数据当前是每行每日股票价格的xts或动物园对象,每一列都是不同的公司。适用于xts的功能

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

我还是新的R和需要一些帮助重现此Excel function。我首先想到的是功能分成分子和分母,然后计算指数:

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

这是伟大的,因为每个部分的值是准确的,但不正确的日期denomJ对齐。例如,numerJ的尾部到2012年6月21日,而denomJ的尾部到2012年6月14日。

,我寻找的输出是:

  • 2012/6/21 = 0.11
  • 2012/6/20 = 0.27
  • 2012年6月19日= 0.46
  • 2012年6月18日= 0.39
  • 2012年6月15日= 0.22
+1

既然我已经使您的示例具有可重现性,请您重新访问您的问题并提供一些预期的输出结果?另外,请描述“日期错误”和“idx包含错误值”的含义。 – 2012-07-21 12:53:53

+0

谢谢!编辑。希望它澄清我的两个xts/zoo对象numerJ和denomJ正在生成准确的数字(numerJ @ 6/21 = 5.95和denomJ @ 6/21 = 53.25)。但是作为rollapply函数的结果,它与我不想要的日期值对齐。 – jonnie 2012-07-21 18:21:00

+0

我完全不理解你的问题。你的Excel功能让我更加困惑,因为它的标签很差。 Re:你最近的评论,我没有看到任何地方的53.25号码。也就是说,根据您对日期对齐的抱怨,我几乎可以肯定,答案是您需要在'rollapply'调用中使用'align = right'(或使用'rollapplyr'包装器)。见'?rollapply' – GSee 2012-07-21 18:34:46

回答

2

很难告诉你到底是什么问题没有确切的DAT a,但问题似乎与rollapply。除非将参数partial设置为TRUE,否则rollapply将仅将该函数应用于整个间隔。请看下面的例子

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 
+0

谢谢!我认为这个问题也是可能的。我认为最合适的解决方案将以接受(x,y)的函数的形式出现,但我仍然不确定... – jonnie 2012-07-21 19:08:01

2

您可以使用diff,要么runSumrollapplyr

#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 

另外,还要注意两个numerJdenomJ,如果使用rollapplyr(这是与使用rollapplyalign="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), ] 
}