Search code examples
rfinance

compute log return in R


I keep getting the same error when I try to compute the log return. What am I doing wrong?

prices = stockindices[,-c(1,2)]
n <- length(prices)
logReturn <- log(prices/prices[n-1])

Error in Ops.data.frame(prices, prices[n - 1]) : ‘/’ only defined for equally-sized data frames


Solution

  • library(tidyverse)
    
    stockindices %>%  
      mutate(across(3:ncol(.), ~ (log(.x / lag(.x)))))
    
    # A tibble: 3,978 x 8
           X Date             DJX      SPX      HKX       NKX       DAX      UKX
       <int> <chr>          <dbl>    <dbl>    <dbl>     <dbl>     <dbl>    <dbl>
     1     1 1999-04-01 NA        NA       NA       NA        NA        NA      
     2     2 1999-05-01  0.0137    0.0135   0.00831 -0.0137    0.000295  0.0133 
     3     3 1999-06-01  0.0248    0.0219   0.0341   0.0177    0.0355    0.0315 
     4     4 1999-07-01 -0.000756 -0.00205  0.0439   0.00504  -0.0224   -0.00777
     5     5 1999-08-01  0.0110    0.00421  0.00272 -0.0108    0.0130    0.00751
     6     6 1999-11-01 -0.00243  -0.00883 -0.00828 -0.00174  -0.0229   -0.0102 
     7     7 1999-12-01 -0.0152   -0.0195   0.00724 -0.000562 -0.0135   -0.00848
     8     8 1999-01-13 -0.0133   -0.00413 -0.0417   0.00319  -0.0530   -0.0309 
     9     9 1999-01-14 -0.0248   -0.0182  -0.00886  0.0247   -0.00387  -0.00512
    10    10 1999-01-15  0.0238    0.0253  -0.00351  0         0.00962   0.0205 
    # ... with 3,968 more rows