R:根据每日价格按组计算每月returns

R: Calculate monthly returns by group based on daily prices

我有一个大型数据框 crsp,其中包含几列每日股票数据。与这个问题相关的是以下列(小摘录给你一个想法):

PERMNO   date         monthyear  PRC       RET
10001    1990-01-02   199001     10.1250   0.0000
10001    1990-01-03   199001     10.0000  -0.0123
...
10001    1990-02-01   199002     10.0000   0.0000
10001    1990-02-02   199002     10.0625   0.0062
...
10002    1990-01-02   199001      6.1250   0.0000
10002    1990-01-03   199001      6.2000   0.0122
...
10002    1990-02-01   199002      6.2500   0.0000
10002    1990-02-02   199002      6.5000   0.0400
...

"PERMNO" 是股票编号,"date" 实际日期,"monthyear" 表示月份,"PRC" 是价格,"RET" 每日 return.

我正在尝试添加一个新列 "MonthlyReturn",它显示每只股票的每月 return。因此,应该为每个股票的每个月计算该值(按 PERMNO 分组)。

据我所知,有两种可能可以解决这个问题:

  1. 通过将每只股票的每个月的最后价格除以该月的第一个价格来计算每月return(注意:由于周末的原因,该月的第一个交易日不一定是实际的第一个每月的第几天)
  2. 将现有的每日 return 秒转换为每月 return 秒

无论如何,我的目标是以下输出:

PERMNO   date         monthyear  PRC       RET      MonthlyReturn
10001    1990-01-02   199001     10.1250   0.0000   0.1000
10001    1990-01-03   199001     10.0000  -0.0123   0.1000
...
10001    1990-02-01   199002     10.0000   0.0000   0.0987
10001    1990-02-02   199002     10.0625   0.0062   0.0987
...
10002    1990-01-02   199001      6.1250   0.0000  -0.0034
10002    1990-01-03   199001      6.2000   0.0122  -0.0034
...
10002    1990-02-01   199002      6.2500   0.0000   0.2340
10002    1990-02-02   199002      6.5000   0.0400   0.2340
...

通过研究,我发现了 quantmod 的 monthlyReturn 函数,这个函数有用吗?

任何帮助将不胜感激,因为我刚开始学习 R。也可以随意添加任何可以帮助我提高这个问题对 SO 的适用性的内容。

使用 Tidyverse,您可以这样计算每月 return:

library(tidyverse)
library(lubridate)

df <- left_join(df, df %>%
  arrange(PERMNO, date) %>% # order the data  by stock id and date
  filter(!wday(as.Date(date)) %in% c(1,7)) %>% # filter week end
  group_by(PERMNO, monthyear) %>% 
  mutate(MonthlyReturn = last(PRC) / first(PRC) - 1) %>% # calculate the monthly return per stock id and month
  select(PERMNO, monthyear, MonthlyReturn)) # Keep only these 3 columns

希望对您有所帮助。