Calculate the monthly returns with data.frames in R

大城市里の小女人 提交于 2019-12-08 09:50:46

问题


I want to calculate the monthly returns for a list of securities over a period of time. The data I have has the following structure:

date   name  value
"2014-01-31"   a    10.0
"2014-02-28"   a    11.1
"2014-03-31"   a    12.1
"2014-04-30"   a    11.9
"2014-05-31"   a    11.5
"2014-06-30"   a    11.88
"2014-01-31"   b    6.0
"2014-02-28"   b    8.5
"2014-03-31"   b    8.2
"2014-04-30"   b    8.8
"2014-05-31"   b    8.3
"2014-06-30"   b    8.9 

The code I tried:

database$date=as.Date(database$date)
monthlyReturn<- function(df) { (df$value[2] - df$value[1])/(df$value[1]) }
mon.returns <- ddply(database, .(name,date), monthlyReturn)

However the output of "monthlyReturn" column is coming with zeros.

Any thoughts?


回答1:


Depends on the use, but I would convert it to a proper time-series object, like xts, and then work with the price-series:

library(reshape2)
library(xts)
myTs <- dcast(database, date~name)
myTs <- xts(myTs[,2:3], myTs[,1])
diff(myTs)/lag(myTs)
                     a           b
2014-01-31          NA          NA
2014-02-28  0.11000000  0.41666667
2014-03-31  0.09009009 -0.03529412
2014-04-30 -0.01652893  0.07317073
2014-05-31 -0.03361345 -0.05681818
2014-06-30  0.03304348  0.07228916

Another way is to use dplyr:

library(dplyr)
database %>% 
group_by(name) %>%
mutate(mReturn = value/lag(value) - 1)

         date name value monthReturn  
1  2014-01-31    a 10.00          NA
2  2014-02-28    a 11.10  0.11000000
3  2014-03-31    a 12.10  0.09009009
4  2014-04-30    a 11.90 -0.01652893
5  2014-05-31    a 11.50 -0.03361345
6  2014-06-30    a 11.88  0.03304348
7  2014-01-31    b  6.00          NA
8  2014-02-28    b  8.50  0.41666667
9  2014-03-31    b  8.20 -0.03529412
10 2014-04-30    b  8.80  0.07317073
11 2014-05-31    b  8.30 -0.05681818
12 2014-06-30    b  8.90  0.07228916

or data.table:

library(data.table)
DT <- setDT(database)
DT[, mReturn := value/shift(value) - 1, by = name]
DT

          date name value     mReturn
 1: 2014-01-31    a 10.00          NA
 2: 2014-02-28    a 11.10  0.11000000
 3: 2014-03-31    a 12.10  0.09009009
 4: 2014-04-30    a 11.90 -0.01652893
 5: 2014-05-31    a 11.50 -0.03361345
 6: 2014-06-30    a 11.88  0.03304348
 7: 2014-01-31    b  6.00          NA
 8: 2014-02-28    b  8.50  0.41666667
 9: 2014-03-31    b  8.20 -0.03529412
10: 2014-04-30    b  8.80  0.07317073
11: 2014-05-31    b  8.30 -0.05681818
12: 2014-06-30    b  8.90  0.07228916


来源:https://stackoverflow.com/questions/29599538/calculate-the-monthly-returns-with-data-frames-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!