I am sure I am missing something simple, but how do I calculate daily returns using data.tables in R?
Let's say I have a data.table like:
DT <- data.table(ticker=rep(letters,each=5), priceA=runif(5*26^2), priceB=runif(5*26^2))
How to I form a new column with the respective returns of price for each ticker?
By returns I mean the normal percentage returns. That is, the second value of priceA for ticker a minus the previous one for the same ticker and this divided by the previous one.
Given the example with the columns ticker, priceA and priceB I should get the column returnsA as in:
ticker priceA priceB returnsA
1: a 0.63519775 0.04784728
2: a 0.01530738 0.34917328 -0.97590
3: a 0.28601406 0.12307475 17.68472
4: a 0.77851212 0.47829863 1.721937
5: a 0.84078779 0.23491432 0.079993
Also, how do I use set()
instead of :=
to make sth like
DT[, newprice := priceA * priceB]
?
Thank you! :)