迭代不同长度的计算

时间:2015-01-14 15:40:21

标签: r loops

我有一个n * 2 df,第一列中的起始月份和第二列中的月份返回值(下面的示例)。使用动物园套餐的日期为年份。

我想计算从每个起始月份返回开始的1到12个月的返回,并使用它们创建一个n * 13数据帧,复合返回组成最后12列(Col 2:1m返回,Col 3:2m返回,...... Col 13:12m返回)。

为了计算回报,我使用的是一个简单的cumprod:

allreturns= function (x) {
  cumprod(1+x/100)-1 }

我的问题是:是否有一种聪明的方法来使用apply和lapply来迭代这个函数,无论是通过返回列(每次都是1:12的cumprod)和开始月份的长度?看起来这会涉及所有返回值的for循环(类似{for(i in length(sample $ monthlyreturns)),但我更喜欢以更好的方式进行。

感谢您的帮助!

structure(list(startmonth = structure(c(2005, 2005.08333333333, 
2005.16666666667, 2005.25, 2005.33333333333, 2005.41666666667, 
2005.5, 2005.58333333333, 2005.66666666667, 2005.75, 2005.83333333333, 
2005.91666666667, 2006, 2006.08333333333, 2006.16666666667, 2006.25, 
2006.33333333333, 2006.41666666667, 2006.5, 2006.58333333333, 
2006.66666666667, 2006.75, 2006.83333333333, 2006.91666666667
), class = "yearmon"), monthlyreturns = c(7.60884596500546, 4.31712970370427, 
1.7181678651832, 4.86275367671624, 8.06177110411227, 8.07952171890065, 
7.45263583026826, 9.86292108893394, 4.06634262995794, 2.36454397207126, 
9.12716506049037, 3.72667369898409, 1.2204843852669, 7.80610600719228, 
0.640116988215595, 6.94793848553672, 1.73743493855, 2.57189674302936, 
4.7653386532329, 1.79362375289202, 7.56623527035117, 2.70907687023282, 
4.45359382545575, 5.50409059040248)), .Names = c("startmonth", 
"monthlyreturns"), row.names = c(NA, 24L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

我不确定我到底知道你要求的是什么,但是会有类似下面的内容吗?您的数据位于退货矩阵中。

cum_ret <- rollapply(returns[,2], width=12, FUN = function(x) cumprod(1+x/100)-1 )
cum_ret <- data.frame(Date=returns[1:nrow(cum_ret),1], cum_mon_ret=cum_ret)
dates <- seq(as.Date(cum_ret$Date[1]), by = "month", length.out=nrow(returns))
col_lines <- rainbow(nrow(cum_ret))
plot(dates[1:12], cum_ret[1,-1], xlim=c(dates[1], tail(dates,1)), col=col_lines[1], type="b", pch=19, , ylab="Cummulative Returns", xaxt="n")
for( i_plot in 2:nrow(cum_ret)) lines(dates[i_plot:(11 +i_plot)], cum_ret[i_plot,-1], col=col_lines[i_plot], type="b", pch=19 )
axis.Date(1, at=dates, format="%b-%y")
grid( length(dates) + 1 )

每个起始月份的累计12个月回报将是

enter image description here