Iterate calculations of different length

前端 未结 1 2036
说谎
说谎 2021-01-26 01:59

I have an n*2 df, with starting month in the first column and monthly returns in the second (sample below). The dates are in year-mon form using the zoo package.

I\'d l

相关标签:
1条回答
  • 2021-01-26 02:14

    I'm not sure I understand exactly what you're asking for but would something like the following do it? Your data are in the returns matrix.

    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 )
    

    Cummulative 12 month returns from each starting month would be

    enter image description here

    0 讨论(0)
提交回复
热议问题