-1

I have a panel data set in R with daily stock returns. The data looks like:

company code  company name          date   daily return
           1             A    1990-09-01            0.1
           1             A    1990-09-02           0.05
           2             B    1990-09-01           0.01
           2             B    1990-09-02           0.05

How can I convert this data into annual stock returns for each company for each year? I tried converting the data into an xts object and tried to use Return.annualized function but it did not work.

Nan
  • 1
  • 2
  • 2
    What do you mean by "it did not work" when you tried to use `xts` package? –  Apr 03 '15 at 04:32
  • i get the error: Error in periodicity(R) : can not calculate periodicity of 1 observation – Nan Apr 03 '15 at 04:36

1 Answers1

0

This will give you annual returns for each company for each year (where I've called your sample data frame dat):

library(lubridate) 
library(dplyr)

dat$date = as.Date(dat$date)
dat$year = year(dat$date)

dat %>% group_by(company_name, year) %>%
  summarise(annual_return = prod(1 + daily_return, na.rm=TRUE) - 1)

  company_name year annual_return
1            A 1990        0.1550
2            B 1990        0.0605
eipi10
  • 91,525
  • 24
  • 209
  • 285
  • I am getting NA values for some companies for some years although the daily return data exists, what could be the reason? Thanks so much again. – Nan Apr 03 '15 at 05:25
  • Are there any NA values in `daily_return`? This would cause `prod` to return `NA`. See my updated answer for a fix. – eipi10 Apr 03 '15 at 05:48
  • Note that missing data will bias the annual returns unless the data are missing because the market was closed on that day or the stock's value was unchanged for some other reason. – eipi10 Apr 03 '15 at 06:10
  • Yes it was the missing data. When I removed the missing values and ran it it worked fine. Thanks again! – Nan Apr 03 '15 at 15:36