xts_merge_align_next: Merge 2 XTS Tables According to Next Non-Missing Value

View source: R/xts_merge_align_next.R

xts_merge_align_nextR Documentation

Merge 2 XTS Tables According to Next Non-Missing Value

Description

You will probably never need to call this function directly, but it's included just in case the need arises to perform a custom merge.

For two XTS objects xts1 and xts2, let A be any datetime index that appears in index(xts2), falls between min(index(xts1)) and max(index(xts1)), but does not appear in index(xts1). Let B be the earliest-occurring datetime index in index(xts1) that occurs after A.

xts_merge_align_next(xts1, xts2) will return the left-join merge of xts1 and xts2 with one additional operation: for any/all A and B that occur for the XTS pair, the values at at index B for the columns in the merged XTS coming from xts2 equal the aggregated value (as specified; e.g., sum) of the values of the columns in xts2 in the range A:B.

Usage

xts_merge_align_next(xts1, xts2, agg_function, na.fill)

Arguments

xts1

An XTS object

xts2

An XTS object that may or may not have indices that fall within the range of xts1, but do not appear in xts1

agg_function

Any function that accepts a numeric vector as input and returns a single number as output; e.g., sum

na.fill

Not all indices of xts2 may occur in xts1, therefore, the left join (xts1, xts2) will almost always result in missing values (NA) in xts2 columns of the merged xts. na.fill specifies what value to fill in for those NA values.

Examples

# Hurricane Sandy hit the Northeastern United States at the end of October in
# 2012, shutting down the stock exchange and most of New York on 29 October.
# Texas Instruments (TXN) had scheduled a dividend to go ex-div that day, but
# since the stock exchange wasn't open, there are no historical prices for
# TXN on 29 Oct 2012, when a seller of TXN would have received the dividend.
#
# xts_merge_align_next() handles this situation by correctly applying the
#' # dividend to the next trading day, which happened to be the 31st:
xts_merge_align_next(
  stock_data$TXN$prices$Close["2012-10-26/2012-11-02", drop = FALSE],
  stock_data$TXN$dividends$DividendAmount,
  base::sum,
  0
)

gothic-hedge-society/FinancieR documentation built on June 18, 2022, 4:55 a.m.