Reputation: 47
I have the following dataframe,
FECHA Pxlast
1 2010-12-31 332.636
2 2011-01-07 334.327
3 2011-01-14 341.771
4 2011-01-21 331.241
5 2011-01-28 333.252
I have to calculate a new column called "Rolling 4 weeks", the values are based on the following idea, for example for index 5, it will be pxlast[5]/pxlast[5-number of weeks]-1.
Then I get the performance for 4 weeks, in this example it should be pxlast[5] = 333.252 , pxlast[5-4] = 332.636, then I divide it and I subtract - 1 , so the result is -0,384.
Ok, I can do it using "for" loop ; but reading about some functions that could do it properly I find the function chart.rollingPerformance, from the PerformanceAnalytics.
It applied the rolling over a parameter called FUN, for example "mean", it will calculate the mean between width space, but I don't know how to calculate Performance correctly.
Here is the output dataframe for example.
FECHA Pxlast Rolling4W
1 2010-12-31 332.636 NA
2 2011-01-07 334.327 NA
3 2011-01-14 341.771 NA
4 2011-01-21 331.241 NA
5 2011-01-28 333.252 -0,384
The NA values are because we are calculating performance from a width of 4 spaces ( weeks ).
Is there any function to do it without loops?
Upvotes: 0
Views: 429
Reputation: 3650
require(data.table)
d <- data.table(x = 1:5, y=c(1, 2, 4, 7, 11))
d[, z := shift(y, 4)]
d[, z := y/z - 1]
d
# x y z
# 1: 1 1 NA
# 2: 2 2 NA
# 3: 3 4 NA
# 4: 4 7 NA
# 5: 5 11 10
Upvotes: 1