#' Calculate returns from a list of xts prices
#'
#' @param price_list list of xts asset prices
#' @param type type of daily returns; "opop" open to opne, "clcl" close to close
#' @param trim numeric value indicating limit for positive daily returns
#'
#' @return xts matrix of asset returns
#' @import xts
#' @import quantmod
#' @export
#'
#'
#' @examples calc_returns(stock_prices, type = "opop", trim = 0.055)
calc_returns <- function (price_list, type = c("clcl"), trim = NULL) {
type <- match.arg(type, c("opop", "clcl"), several.ok = FALSE)
if (type == "opop") {
R <- lapply(price_list,
function (x) dailyReturn(Op(x))) %>%
do.call(cbind.xts, .) %>%
lag.xts(., k=-1) %>%
`colnames<-`(names(stock_prices)) %>%
na.fill(fill=0)
}
if (type == "clcl") {
R <- lapply(price_list,
function (x) dailyReturn(Cl(x))) %>%
do.call(cbind.xts, .) %>%
`colnames<-`(names(stock_prices)) %>%
na.fill(fill=0)
}
if (!is.null(trim)) {
R %<>% apply(., 2, function(x) ifelse(x > trim, trim, x)) %>%
xts(., order.by = index(R), dateFormat = "Date")
}
R
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.