R:在data.table中使用quantmod的Delt

时间:2014-02-21 00:55:32

标签: r data.table quantmod

关注R data.table Return calculation and set() 我想问一下如何使用Delt()中的library(quantmod)来查找data.table()中时间序列的返回值。 到目前为止,感谢Frank,我有:

set.seed(42)
DT <- data.table(
  ticker=rep(letters,each=5),
  priceA=runif(5*26^2),
  priceB=runif(5*26^2))

DT[,paste('returns',LETTERS[1:2],sep=''):={
  lapply(.SD,function(x){
    old <- head(x,-1)
    new <- tail(x,-1)
    c(NA,(new-old)/old)
  })
},by=ticker,.SDcols=grep('^price',names(DT))]

结果(对于此种子值)是:

      ticker    priceA    priceB    returnsA   returnsB
   1:      a 0.9148060 0.7956245          NA         NA
   2:      a 0.9370754 0.9314941  0.02434327  0.1707710
   3:      a 0.2861395 0.6269996 -0.69464620 -0.3268883
   4:      a 0.8304476 0.1666758  1.90224707 -0.7341691
   5:      a 0.6417455 0.6483800 -0.22722939  2.8900659
  ---                                                  
3376:      z 0.2887293 0.3473923 -0.54132570 -0.3514041
3377:      z 0.9013438 0.1788842  2.12176058 -0.4850656
3378:      z 0.3126429 0.7648157 -0.65313686  3.2754788
3379:      z 0.8791381 0.1300418  1.81195584 -0.8299698
3380:      z 0.8160158 0.8159330 -0.07180019  5.2743905

如何使用Delt()(或类似的%更改功能)代替function(x){ old <- head(x,-1) new <- tail(x,-1) c(NA,(new-old)/old) } ??

非常感谢!

1 个答案:

答案 0 :(得分:2)

您只需要将Delt的返回值转换为简单的向量:

DT[,
  paste('returns',LETTERS[1:2],sep=''):=lapply(.SD,function(x) c(Delt(x))),
  by=ticker,.SDcols=grep('^price',names(DT))
]

这会产生:

    ticker    priceA    priceB    returnsA   returnsB
 1:      a 0.9148060 0.7956245          NA         NA
 2:      a 0.9370754 0.9314941  0.02434327  0.1707710
 3:      a 0.2861395 0.6269996 -0.69464620 -0.3268883
 4:      a 0.8304476 0.1666758  1.90224707 -0.7341691
 5:      a 0.6417455 0.6483800 -0.22722939  2.8900659
---