I want to create an xts objects with indices from other xts objects, but enhanced , i.e. longer : before start and after end. E.g. for adding 5 periods after the corresponding index, I'll use:
data(sample_matrix)
xts_object <- as.xts(sample_matrix, descr='my new xts object')
add_right <- 5
seq(as.Date(end(xts_object)), by = unclass(periodicity(xts_object))$label, length = (add_right+1))[-1]
2 Questions:
Thanks in advance!
1. Does this always work (I'll use it inside functions)
Yes.
2. How do I add periods before the corresponding start?
Here is an example of expanding the index on both the start and end boundaries, using NA values by default to fill. You can also easily add actual xts data at the start or end using rbind(xts1, xts2) provided the columns of the data match.
# add dateFormat = "Date" to avoid misaligned timestamps
# in relation to time component HH:MM:SS when `rbind`ing with
# Date type indexes (as opposed to POSIXct type indexes):
xts_object <- as.xts(sample_matrix, descr='my new xts object', dateFormat="Date")
my_periodicity <- unclass(periodicity(xts_object))$label
add_right <- 5
v_dates_end <- seq(as.Date(end(xts_object)),
by = my_periodicity,
length.out = (add_right+1))[-1]
st_date <- as.Date(start(xts_object))
v_dates_start <- seq(from = st_date - 5,
to = st_date - 1,
by = my_periodicity)
x_expand_time_index <- xts(, order.by = c(v_dates_start, v_dates_end))
# Note the fill argument could be replaced by say 0, 1, NaN, etc
x <- merge(xts_object, x_expand_time_index, fill = NA)
head(x)
# Open High Low Close
# 2006-12-28 NA NA NA NA
# 2006-12-29 NA NA NA NA
# 2006-12-30 NA NA NA NA
# 2006-12-31 NA NA NA NA
# 2007-01-01 NA NA NA NA
# 2007-01-02 50.03978 50.11778 49.95041 50.11778
tail(x)
# Open High Low Close
# 2007-06-30 47.67468 47.94127 47.67468 47.76719
# 2007-07-01 NA NA NA NA
# 2007-07-02 NA NA NA NA
# 2007-07-03 NA NA NA NA
# 2007-07-04 NA NA NA NA
# 2007-07-05 NA NA NA NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With