1

I need to use 'PerformanceAnalytics' package of R and to use this package, I understand that I need to convert the data into xts data, which is actually a panel data. Following this forum's suggestion I have done the following:

library(foreign)
RNOM <- read.dta("Return Panel without missing.dta")
RNOM_list<-split(RNOM,RNOM$gvkey)
xts_list<-lapply(RNOM_list,function(x)
{out<-xts(x[,-1],order.by=as.Date(x$datadate,format="%d/%m/%Y")) })

It gives me RNOM_list and xts_list.

After this, can some please help me to estimate the monthly returns using the function Return.calculate and lapply and save the output generated as an addition variable in my original data-set for regression analysis? Subsequently, I also need to estimate VaR, ES and semi-sd.

The data can be downloaded here. Note, prccm is the monthly closing price in the data and gvkey is the firm ID.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jairaj Gupta
  • 347
  • 4
  • 16
  • 1
    You'll probably get a better response if you show what you tried and why it didn't work, rather than asking someone to write the code for you from scratch. – Joshua Ulrich Jan 31 '14 at 16:12
  • Sorry, if I couldn't make myself clear. This is what I tried: – Jairaj Gupta Jan 31 '14 at 19:40
  • I want to calculate the monthly return of each firms for respective time periods. This is what I tried:> lapply(xts_ListReturn.calculate(RNOM$prccm, method = c("discrete", "log")))Error in UseMethod("xtsAttributes<-") : no applicable method for 'xtsAttributes<-' applied to an object of class "zoo" ........... Since, its an xts data, the transform function of creating new variable is not compatible. Hence if you can please show me codes to calculate the return and save the variable in the dataframe, it will be really helpful? – Jairaj Gupta Jan 31 '14 at 19:49

1 Answers1

0

An efficient way to achieve this goal is to covert the Panel Data (long format) into wide format using 'reshape2' package. After performing the estimations, convert it back to long format or panel data format. Here is an example:

library(foreign)
library(reshape2)
dd <- read.dta("DDA.dta") // DDA.dta is Stata data; keep only date, id and variable of interest (i.e. three columns in total)
wdd<-dcast(dd, datadate~gvkey) // gvkey is the id
require(PerformanceAnalytics)
wddxts <- xts(wdd[,-1],order.by=as.Date(wdd$datadate,format= "%Y-%m-%d"))

ssd60A<-rollapply(wddxts,width=60,SemiDeviation,by.column=TRUE,fill=NA) // e.g of rolling window calculation
ssd60A.df<-as.data.frame(ssd60A.xts) // convert dataframe to xts
ssd60A.df$datadate=rownames(ssd60A.df) // insert time index
lssd60A.df<-melt(ssd60A.df, id.vars=c('datadate'),var='gvkey') // convert back to panel format
write.dta(lssd60A.df,"ssd60A.dta",convert.factors = "string") // export as Stata file

Then simply merge it with the master database to perform some regression.

Jairaj Gupta
  • 347
  • 4
  • 16