I have some stock return daily data need to turn into weekly format. As you know stock trade only on Monday to Friday, I need to add up each days return to get cumulative weekly return.
I have thought about using lubridate's week function but how does lubridate knows when is the start of the week? How do I make lubridate to recognize the week using weekday function i.e. "Monday" to "Friday" is one week?
I have thought about writing a loop for example: If "Monday" to "Friday" is in the data, then I will call this one week. But for the second week, what shall I use for R to know we are entering second week? Then when we reach year end and we have 52 weeks, how to reset the week count so we are entering the next year?
Here is the dput:
dat = structure(list(date = structure(c(4019, 4022, 4023, 4024, 4025,
4026, 4029, 4030, 4031, 4032, 4033, 4036, 4037, 4038, 4039, 4040,
4043, 4044, 4045, 4046, 4047, 4050, 4051, 4052, 4053, 4054, 4057,
4058, 4059, 4060, 4061, 4065, 4066, 4067, 4068, 4071, 4072, 4073,
4074, 4075), class = "Date"), weekday = c("Friday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday"), COMP = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), week = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4,
4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8,
9, 9), RET = c(-0.005435, 0.040984, -0.015748, -0.021333, 0.002725,
0.01087, 0.024194, -0.002625, 0.013158, 0.033766, 0, -0.007538,
-0.005063, 0, -0.002545, 0.015306, 0.017588, -0.007407, 0.024876,
-0.009709, 0, -0.029412, 0.010101, 0.0075, -0.004963, 0.027431,
-0.002427, 0.007299, -0.009662, -0.004878, 0.014706, -0.004831,
0.004854, -0.009662, -0.021951, -0.014963, 0.005063, -0.005038,
0.010127, 0)), .Names = c("date", "weekday", "COMP", "week",
"RET"), row.names = c(NA, -40L), class = c("data.table", "data.frame"
))
library(data.table)
setDT(dat)
Here are two month worth of data from 1981-01-02 to 1981-02-27 of company 1's daily return. Lets ignore to calculate the return at the moment and focus on the time first.
week column is generated by weeks() function. As you can see week is not what I wanted, it starts from wednesday and end in wednesday.
weekday is generated by weekdays() function.
I want to make e.g. 1981-01-02 as week 1 (since we have friday here only), 1981-01-05 to 1981-01-09 as week 2 vice versa.