【问题标题】:How do I calculate overlapping three-day log returns in the same dataframe in R?如何在 R 中的同一数据框中计算重叠的三天日志返回?
【发布时间】:2019-10-03 23:25:52
【问题描述】:

我刚刚开始学习 R。至于现在,我在数据框 test 中包含价格 PRC 以及日期和其他几个变量。

我的目标是在相同数据框中计算以下内容,以便我可以保持与日期的连接。
1. 重叠的三天日志返回
2. 一日日志返回

通过其他帖子,我分别为三天滞后回报和一日滞后回报提出了以下代码,但我仍然不确定如何将其合并到我的数据框中:

test$logR3 <- diff(log(test$PRC)), lag=3)

由于行数不同,此代码目前不起作用。我如何考虑到这一点?我可以以某种方式输入零或 NA 来填充缺失的行吗?

提前谢谢你。

【问题讨论】:

    标签: r return time-series finance


    【解决方案1】:

    可能是这样的:

    days=c()
    for(i in seq(3,nrow(test),3)){  #loop through it in steps of 3
        one_day_ago_diff=log(test$PRC[i])-log(test$PRC[i-1]) #difference between today and yesterday
        three_days_ago_diff=log(test$PRC[i])-log(test$PRC[i-3]) #difference between today and three days ago
        days=c(days,c(three_days_ago_diff,NA,one_day_ago_diff)) # fills empty vector with diff from 3 days ago- followed by NA to skip 2 days ago and then one day ago
    }
    
    if(length(days)<nrow(test)){days=c(days, rep(NA,nrow(test)-length(days)))} #check they're the same length
    test$lags=days #add column to test
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多