How do I code this formula:
Simple returns = [(Pt / Pt-1) - 1]
I have tried the below, but keep getting the wrong numbers.
stockindices = read.csv('https://raw.githubusercontent.com/bandcar/Examples/main/stockInd.csv')
library(tidyverse)
simple_returns <- stockindices %>%
mutate(across(3:ncol(.), ~ ((.x / lag(.x-1))-1)))
CodePudding user response:
You had too many -1's in your expression:
simple_returns <- stockindices %>%
mutate(across( 3:ncol(.), ~ .x / lag(.x)-1))
str(simple_returns)
'data.frame': 3978 obs. of 8 variables:
$ X : int 1 2 3 4 5 6 7 8 9 10 ...
$ Date: chr "1999-04-01" "1999-05-01" "1999-06-01" "1999-07-01" ...
$ DJX : num NA 0.01382 0.025107 -0.000755 0.011068 ...
$ SPX : num NA 0.01358 0.02214 -0.00205 0.00422 ...
$ HKX : num NA 0.00835 0.03465 0.04493 0.00272 ...
$ NKX : num NA -0.01365 0.01781 0.00506 -0.01069 ...
$ DAX : num NA 0.000295 0.036108 -0.022119 0.01308 ...
$ UKX : num NA 0.0134 0.03199 -0.00774 0.00754 ...
You could have bracketed the .x/lag(.x) but it's not necessary here because of operator precedence and R's order of operations rules. The default lag-interval is 1 so it doesn't need to be inside the argument to lag. If you had wanted the semi-monthly returns it would have been
~ .x/lag(.x, 2) - 1
And as always it will pay to make sure that you have masked the stats::lag
function, which is quite different and doesn't play nicely with the tidyverse.