如何计算数据中NA的年化回报?

时间:2018-04-27 15:47:26

标签: r

我需要从季度回报数据系列中计算年化回报。如下创建样本数据

df <- data.frame(v1 = c(0.01, 0.03, 0.02,0.05, 0.06,0.03,0.01, NA), V2 = c(NA, 0.1, 0.02,NA,0.03,0.05,0.11, 0.2))

我的代码是:

df_annual <- rollapply(df, width = 4, Return.annualized, scale =4, align = "right", fill = NA)

我得到的结果是

v1        V2

NA         NA
NA         NA
NA         NA
0.114161    0.258884
0.169318    0.212756
0.169318    0.139818
0.157854    0.275849
0.139251    0.440558

我希望得到以下结果:

V1         V2

NA          NA
NA          NA
NA          NA
0.114161    NA
0.169318    NA
0.169318    NA
0.157854    NA
NA          0.440558

换句话说,我只希望R用至少四个连续数字来计算年化回报。我也想知道我是如何得到第一个结果的。谢谢!

1 个答案:

答案 0 :(得分:1)

1) Return.annualized省略NA值,然后计算剩余的年化回报。如果你想在任何输入为NA时输出NA,那么检查输入中的NA和输出NA(如果遇到);否则,请运行Return.annualized

library(PerformanceAnalytics)
library(zoo)

Return.annualizedNA <- function(x, ...) if (anyNA(x)) NA else Return.annualized(x, ...)
rollapplyr(df, width = 4, Return.annualizedNA, scale = 4, fill = NA)

2)另一种可能性就是直接使用prod

library(zoo)

rollapplyr(df + 1, 4, prod, fill = NA) - 1