2013-05-07 70 views
1

我在使用dailyReturn函數時遇到困難,因爲它帶有多個返回序列的xts對象。每日返回xts對象

a<-Cl(getSymbols("INTC",auto.assign=FALSE)) 
b<-Cl(getSymbols("IBM",auto.assign=FALSE)) 
a<-merge(a,b) 
dailyReturn(a[,1]) #This works! 
dailyReturn(a) #Only return the result for first series 
apply(a,2, dailyReturn) 
#Error in array(ans, c(len.a%/%d2, d.ans), if (!all(vapply(dn.ans, is.null, : 
length of 'dimnames' [1] not equal to array extent 

我該如何獲得dailyReturn以返回xts對象中多個系列的每日回報?

回答

2

我喜歡ROC還可以,但如果必須使用dailyReturn,可以lapply在列,cbind他們重新走到一起。

> head(do.call(cbind, lapply(a, dailyReturn))) 
      daily.returns daily.returns.1 
2007-01-03 0.0000000000  0.000000000 
2007-01-04 0.0402948403  0.010691889 
2007-01-05 -0.0033065659 -0.009052996 
2007-01-08 -0.0042654028  0.015191952 
2007-01-09 0.0009519277  0.011830131 
2007-01-10 0.0233000476 -0.011791746 

我使用do.call,以便它可以處理任意數量的列。

2

我只想用TTR::ROC代替。

> head(r <- ROC(a, type="discrete")) 
       INTC.Close IBM.Close 
2007-01-03   NA   NA 
2007-01-04 0.0402948403 0.010691889 
2007-01-05 -0.0033065659 -0.009052996 
2007-01-08 -0.0042654028 0.015191952 
2007-01-09 0.0009519277 0.011830131 
2007-01-10 0.0233000476 -0.011791746