【问题标题】:R: Calculate monthly returns by group based on daily pricesR:根据每日价格按组计算每月回报
【发布时间】:2019-10-13 00:45:18
【问题描述】:

我有一个大型数据框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"是股票ID,"date"是实际日期,"monthyear"是月份,"PRC"是价格,"RET"是日收益率。

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

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

  1. 每个股票每个月的最后一个价格除以当月的第一个价格来计算月收益(注意:由于周末,当月的第一个交易日不一定是实际的第一个交易日)
  2. 将现有的每日收益转换为每月收益

无论哪种方式,我的目标是以下输出:

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 的每月返回函数,这有用吗?

在我刚开始学习 R 时,我们将不胜感激任何帮助。还可以随时添加任何可以帮助我提高此问题对 SO 的适用性的内容。

【问题讨论】:

  • 有几种方法可以做到这一点。看看这个线程:stackoverflow.com/questions/29599538/…
  • @cyrilb38:我看过这些帖子。不幸的是,我的情况略有不同,因为我必须将此方法应用于每日数据,同时最佳地使用monthlyReturn() 并按PERMNO 对其进行分组。

标签: r return time-series quantmod stock


【解决方案1】:

使用 Tidyverse,您可以这样计算您的每月回报:

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多