Question

Following R data.table Return calculation and set() I would like to ask how I can use Delt() from library(quantmod) to find returns for a time-series in a data.table(). So far, thanks to Frank, I have:

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))]

The result (for this seed value) is:

      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

How can I use Delt() (or a similar %change function) instead of function(x){ old <- head(x,-1) new <- tail(x,-1) c(NA,(new-old)/old) } ??

Many many thanks!

Was it helpful?

Solution

You just need to convert the return value of Delt to a simple vector:

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

This produces:

    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
---                                                   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top