Fill missing values by trading day
The previous exercise carried the last observation of the prior day forward into the first observation of the following day. This exercise will show you how to fill missing values by trading day, without using the prior day's final value.
You will use the same split-lapply-rbind paradigm from the Introduction to xts and zoo course. For reference, the pattern is below.
x_split <- split(x, f = "months")
x_list <- lapply(x_split, cummax)
x_list_rbind <- do.call(rbind, x_list)
Recall that the do.call(rbind, ...)
syntax allows you to pass a list of objects to rbind()
instead of having to type all their names.
Your workspace has a trade_day
object that contains the regular series from the previous exercise, but without any NA
filled in.
This exercise is part of the course
Importing and Managing Financial Data in R
Exercise instructions
- Create a
daily_list
object by usingsplit()
to put thetrade_day
data into a list of data for each day. - Now use
lapply()
to fill theNA
for each day's data in thedaily_list
list. - Finally, use
do.call()
andrbind()
to convertdaily_filled
to a single xts object namedfilled_by_trade_day
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Split trade_day into days
daily_list <- split(___ , f = "___")
# Use lapply to call na.locf for each day in daily_list
daily_filled <- lapply(___, FUN = ___)
# Use do.call to rbind the results
filled_by_trade_day <- do.call(rbind, ___)