#' Produces a plot of cumulative performance, returns, and
#' drawdown over time given a history of returns.
#' @param r.xts an XTS object with period returns for each column;
#' function will compute cumulative return and drawdowns for each item.
#' @param ptitle a plot title string, default empty string
#' @param geometric whether cumulative returns should use geometric method
#' @return \code{ggplot2} object for further manipulation
#' @seealso PerformanceAnalytics::charts.PerformanceSummary,
#' directlabels, dplyr, tidyr, magrittr, ggplot2
#' @examples
#' \dontrun{
#' pr <- blotter::PortfReturns(acct_name)
#' colnames(pr) <- gsub(".DailyEndEq", "", colnames(pr))
#' pr$Theoretical <- rowSums(pr)
#' p <-gg_charts_summary_3(pr$Theoretical,
#' ptitle = "Theoretical Returns")
#' p
#' }
gg_charts_summary_3 <- function(r.xts,
ptitle = "",
geometric = TRUE) {
require(magrittr,quietly = TRUE)
# dodges command check complaints
Series <- Value <- Date <- Plot <- NULL
# cumulative return
c.xts <- if ( geometric ) {
cumprod(1 + r.xts)
} else {
1 + cumsum(r.xts)
}
# drawdowns
d.xts <- do.call(cbind, lapply(1:ncol(c.xts), function(j) {
cx <- cummax(c.xts[, j])
c.xts[, j] / cx # removed dd assignment
}))
# tagged dataframes to facilitate facet grid subsetting
pc <- data.frame(Date = zoo::index(c.xts),
Plot = "Cumulative",
c.xts,
stringsAsFactors = FALSE)
pr <- data.frame(Date = zoo::index(r.xts),
Plot = "Returns",
r.xts,
stringsAsFactors = FALSE)
pd <- data.frame(Date = zoo::index(d.xts),
Plot = "Drawdowns",
d.xts,
stringsAsFactors = FALSE)
pf <- dplyr::bind_rows(pc, pr, pd) %>%
tidyr::gather(Series, Value, 3:ncol(pr)) %>%
na.omit
# facet plot
p <- ggplot2::ggplot(pf,
ggplot2::aes(x = Date,
y = Value,
color = Series,
fill = Series)) +
ggplot2::geom_line(data = subset(pf, Plot == "Cumulative")) +
ggplot2::geom_bar(data = subset(pf, Plot == "Returns"),
stat = "identity",
position = "dodge") +
ggplot2::geom_smooth(data = subset(pf, Plot == "Returns"),
method = "lm") +
ggplot2::geom_line(data = subset(pf, Plot == "Drawdowns")) +
ggplot2::facet_grid(Plot~., scales = "free_y", space = "free_y") +
ggplot2::ggtitle(ptitle) +
ggplot2::xlab(NULL) +
ggplot2::ylab(NULL) +
ggplot2::theme(strip.text.y = ggplot2::element_text(size = 8))
return(p)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.