How to calculate returns from a vector of prices?

前端 未结 7 781
醉梦人生
醉梦人生 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
    
    0 讨论(0)
  • 2020-12-09 22:11

    You can do this:

    (PRICE / lag(PRICE)-1) * 100
    
    0 讨论(0)
  • 2020-12-09 22:13

    Using your sample data, I think you mean the following:

    a <- c(10.25, 11.26, 14, 13.56) 
    > diff(a)/a[-length(a)]
    [1]  0.09853659  0.24333925 -0.03142857
    

    diff returns the vector of lagged differences and a[-length(a)] drops the last element of a.

    0 讨论(0)
  • 2020-12-09 22:17

    You may find the functions in quantmod relevant for your work:

    > require(quantmod)
    > Delt(a)
         Delt.1.arithmetic
    [1,]                NA
    [2,]        0.09853659
    [3,]        0.24333925
    [4,]       -0.03142857
    
    0 讨论(0)
  • 2020-12-09 22:22

    You can also use the exact relationship that returns are equal to the exponent of log returns minus one. Thus, if Prices contains your prices, the following will give you your returns:

    Returns = exp(diff(log(Prices))) - 1
    

    Note that this is an exact relationship, rather than the approximate relationship given in the answer by @PBS.

    0 讨论(0)
  • 2020-12-09 22:22

    Another possibility is the ROC function of the TTR package:

    library(TTR)
    a <- c(10.25, 11.26, 14, 13.56)
    ROC(a, type = "discrete")
    ## [1]          NA  0.09853659  0.24333925 -0.03142857
    

    type = continuous (which is also the default) gives log-returns:

    ROC(a)
    ## [1]          NA  0.09397892  0.21780071 -0.03193305
    
    0 讨论(0)
提交回复
热议问题