How to calculate returns from a vector of prices?

前端 未结 7 845
醉梦人生
醉梦人生 2020-12-09 22:05

I have to calculate the return of a vector that gives a historical price series of a stock. The vector is of a form:

a <- c(10.25, 11.26, 14, 13.56) 
         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 22:11

    A more detailed example with multiple time series:

    ############ Vector  ############
    
    vPrice <- (10.25, 11.26, 14, 13.56) 
    n = length(vPrice)
    
    #Log returns
    
    log_ret <- diff(log(vPrice)) # or = log(vPrice[-1]/vPrice[-n]) because "..[-i]" removes the i'th item of the vector
    log_ret
    
    #Simple returns
    
    simple_ret <- diff(vPrice)/vPrice[1:(n-1)] # or = diff(vPrice)/vPrice[-n]
    simple_ret
    
    
    ############ Multiple Time series ############
    
    head(EuStockMarkets)
    
    mPrice <-  EuStockMarkets
    n = dim(mPrice)[1] #Nb rows
    
    log_ret <- diff(log(mPrice))
    head(log_ret)
    
    simple_ret <- diff(mPrice)/mPrice[1:(n-1),]
    head(simple_ret)
    
    
    #Total Returns
    
    total_log_ret <- colSums(log_ret,2) #just a sum for log-returns
    total_log_ret
    total_Simple_ret <- apply(1+simple_ret, 2, prod)-1 # product of simple returns
    total_Simple_ret
    
    ##################
    
    #From simple to log returns 
    all.equal(log(1+total_Simple_ret),total_log_ret) #should be true
    
    #From Log to simple returns 
    all.equal( total_Simple_ret,exp(total_log_ret)-1) #should be true
    

提交回复
热议问题