Calculate annualized returns from quarterly observations

后端 未结 2 842
清酒与你
清酒与你 2021-01-21 00:08

I am trying to calculate annualized quarterly returns from two returns series.

Given a vector r_a, it is fairly easy:

r_a <- c(.05, .02, .03, .08, .1,         


        
相关标签:
2条回答
  • 2021-01-21 00:48

    We can use

    apply(mat_ab, 2, function(col_j){
    col_j <- as.matrix(col_j)
    (prod(1+col_j)^(4/nrow(col_j)))-1
    })
    #       r_a       r_b 
      0.2491168 0.4773500 
    

    Further, as you can see your code uses a matrix object:

    r_a <- c(.05, .02, .03, .08, .1, .04, .06, .08)
    r_a <- t(t(r_a))
    class(r_a)
    # [1] "matrix"
    
    0 讨论(0)
  • 2021-01-21 00:52

    Though there is an accepted answer, I think the following can be of use. nrow is replaced by NROW so as to work both with quarterly returns vectors and matrices.

    To see the difference:

    nrow(1:10)
    #NULL
    NROW(1:10)
    #[1] 10
    

    And the function becomes

    annualized <- function(x, MARGIN = 2){
      f <- function(y) (prod(1 + y)^(4/NROW(y))) - 1
      if(is.null(dim(x)))
        f(x)
      else
        apply(x, MARGIN = MARGIN, f)
    }
    
    
    r_a <- c(.05, .02, .03, .08, .1, .04, .06, .08)
    r_b <- c(.1, .1, .1, .1, .1, .1, .1, .12)
    mat_ab <- cbind(r_a, r_b)
    
    
    annualized(r_a)
    #[1] 0.2491168
    
    annualized(mat_ab)
    #      r_a       r_b 
    #0.2491168 0.4773500
    
    0 讨论(0)
提交回复
热议问题