I have a dataset like the following which contains 46 products price history from 2014-5-1 to 2014-11-30:
prodid price date
19119665 27.89999962 11/25/2014
19119665 27.89999962 11/25/2014
19119665 26.89999962 11/27/2014
19119665 26.89999962 11/28/2014
19119665 26.89999962 11/30/2014
19141710 19.89999962 5/1/2014
19141710 19.89999962 5/1/2014
19141710 19.89999962 5/1/2014
And I want to treat each product as a stock and calculate the daily price changes of these products across time.
I have thought of the following code using quantmod:
periodReturn(data,period='daily',subset='prodid')
but it seems that this code is not doing what it should be doing. I am getting the following error:
Error in try.xts(x) :
Error in as.POSIXlt.character(x, tz, ...):character string is not in standard unambiguous format
Would appreciate any help!
I don't think that there is one way to achieve what you are asking. Here is my approach with dplyr
.
dat %>% mutate(perx = price / lag(dat$price) - 1)
prodid price date perx
1 19119665 27.9 11/25/2014 NA
2 19119665 27.9 11/25/2014 0.00000000
3 19119665 26.9 11/27/2014 -0.03584229
4 19119665 26.9 11/28/2014 0.00000000
5 19119665 26.9 11/30/2014 0.00000000
6 19141710 19.9 5/1/2014 -0.26022305
7 19141710 19.9 5/1/2014 0.00000000
8 19141710 19.9 5/1/2014 0.00000000