根据面板数据 R 每月计算 returns

Calculating monthly returns based on Panel Data R

不幸的是,我有一个大数据集,VBA 处理起来有很多问题。因此,我希望R能帮助我。

我有以下数据:

ID month Price      
1   1    0,1   
1   2    0,2  
1   3    0,3  

2   1    0,1   
2   2    0,2  
2   3    0,2   

我想添加标记为 "returns" 的第四列,其中显示每月 returns。我用循环尝试了它,但不幸的是它没有产生我想要的结果。

returns的期望结果和计算:returnt = Pt / Pt-1 -1

ID month Price   return   
1   1    0,1   
1   2    0,2     1
1   3    0,3     0,5

2   1    0,1   
2   2    0,2     1
2   3    0,2     0,5


In VBA my code looks like this:

Dim i as integer
dim j as integer

for i= 1 to 10
j= i + 1

If cells(i,1) = cells (j,1) then
cells(j, 4) = cells(j,3) / cells(i,3) - 1 
Else cells(j, 4)  = 0
End if
next i

使用最后注释中的数据创建一个 return 函数,returnfun,然后将其分别应用于每个 IDPrice 向量,使用ave。没有使用包。

returnfun <- function(x) c(NA, diff(x) / head(x, -1))
transform(DF, Returns = ave(Price, ID, FUN = returnfun))

给予:

  ID month Price Returns
1  1     1   0.1      NA
2  1     2   0.2     1.0
3  1     3   0.3     0.5
4  2     1   0.1      NA
5  2     2   0.2     1.0
6  2     3   0.2     0.0

或者像这样使用 zoo 定义 returnfun

library(zoo)
returnfun <- function(x) diff(zoo(x), arithmetic = FALSE, na.pad = TRUE) - 1

备注

Lines <- "
ID month Price      
1   1    0.1   
1   2    0.2  
1   3    0.3  
2   1    0.1   
2   2    0.2  
2   3    0.2"

DF <- read.table(text = Lines, header = TRUE)

R 包 TTR 非常适合财务计算:https://cran.r-project.org/web/packages/TTR/TTR.pdf

这是来自 ROC(变化率)命令的代码: 描述 计算一个序列在 n 个时期内的(变化率)。 用法 ROC(x, n = 1, 类型 = c("continuous", "discrete"), na.pad = TRUE)

动量(x, n = 1, na.pad = TRUE)

对于您的情况,只需针对您选择的时间段修改 n。