#' Calculate Portfolio Returns function
#'
#' Calculate log-returns of given asset prices, then multiply by vector of portfolio weights.
#' @param prices Data frame of asset prices
#' @param weights Numeric vector of portfolio weights
#'
#' @return Numeric vector of portfolio log-returns.
#' @export
#'
#' @examples
#' files <- list.files('datasets\\')
#' close_prices <- df_prices(files = files
#' ,source = 'datasets\\')
#' weights <- c(0.40, 0.40, 0.20)
#' portfolio_returns(close_prices, weights)
portfolio_returns <- function(prices
,weights){
returns <- as.data.frame(
sapply(
as.data.frame(
sapply(dplyr::select(prices, where(is.numeric))
,log))
,diff
)
)
if(dim(as.matrix(returns))[2] != length(weights)) {
stop('Incorrect dimensions of prices and weights')
}
result <- as.numeric(
as.matrix(returns) %*% weights
)
return(result)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.