R/post.R

#' Plot a descriptive histogram for a series
#'
#' @param vec num series
#' @param ticker,status,var strings for title
#' @param breaks,xlim histogram args
#' @return histogram plot with a proper title
#' @description
#'   For conditional distributions analysis in nonparametric section
#' @export
PlotDescHist <- function(vec, ticker, status, var, breaks, xlim) {
  title <- paste(ticker, ", Status:", status, ", Mean:", round(mean(vec), 3), ", Sd:", round(stats::sd(vec), 3), ", Skw:", round(moments::skewness(vec), 2), sep = "")
  hist(vec, breaks = breaks, main = title, xlab = var, density = TRUE, xlim = xlim) # TODO: curve?
  curve(dnorm(x, mean=mean(vec), sd=stats::sd(vec)), add=TRUE)
}


#' Plot hist and report stats for permutation resampling metrics matrix
#'
#' @param metrics dataframe perf metrics for reordered signals generated from PermMetrics
#' @param n int the order of metric in the metrics we want to explore
#' @param signal.name string of signal name appear on the title
#' @return plot a histogram and output the Empirical Quantile, Standard Deviationa and Mean
#'   from the empirical distribution of the nth performance metrics
#'   e.g. 1-Mean, 2-Stdev, 4-Sharpe, 7-MaxDD, 17-Avg Turnover
#' @export
PlotPermMetrics <- function(metrics, n, signal.name = "test") {
  metric <- rownames(metrics)[n]
  vec <- metrics[metric,] # pick the metric from the colnames we wanna report
  title <- paste("Signal: ", signal.name, ", Hist: ", metric, ", EQ: ", round(stats::ecdf(vec)(vec[1]), 2),
                 ", Stdev: ", round(stats::sd(vec), 2), ", Mean: ", round(mean(vec), 2), sep = "")
  hist(vec, breaks = 300, main = title, xlab = paste(metric, sep = "")); abline(v = vec[1], col = 'red')
  c('EQ' = stats::ecdf(vec)(vec[1]), 'Stdev' = stats::sd(vec), 'Mean' = mean(vec))
}


#' Heat Map from ggplot2 for signal pack
#'
#' @param signals signal pack/list used in main scripts
#' @export
PlotHeatMap <- function(signals, file = "./images/corr_heat.png",
                        width = 900, height = 800) {
  corr.mat.melted = round(100 * cor(do.call(cbind, signals[1:(length(signals))])), 2) %>% reshape2::melt()
  png(filename = file, width = width, height = height)
  ggplot2::ggplot(data = corr.mat.melted, ggplot2::aes(x = Var1, y = Var2, fill = value)) + ggplot2::geom_tile()
  invisible(dev.off())
}


#' Line Plot for PnL xts object using ggplot2::geom_line
#'
#' @param pnls xts object with columns being strategies, generated
#' from DRIVS::OutputWrapper(...)[[2]]
#' @return ggplot object
#' @examples
#'   png(filename = "./images/Signal_PnLs.png", width = 800, height = 500)
#'   DRIVS::PlotLinePnls(outputs.DRI[[2]])
#'   invisible(dev.off())
#' @export
PlotLinePnls <- function(pnls, title = "PnL") {
  pnls <- reshape2::melt(pnls)
  pnls$Var1 <- zoo::as.yearmon(pnls$Var1)
  colnames(pnls) <- c('Date', 'Strategy', 'PnL')
  p <- ggplot2::ggplot(data = pnls, ggplot2::aes(x = Date, y = PnL, color = Strategy))
  p + ggplot2::geom_line() + ggplot2::ggtitle(title)
}


#' Plot Multiple Grids for a lit of Perf Metrics
#'
#' @param metrics.list a list of perf metrics dataframe
#'   generated by DecompMetrics
#' @param file string of path of target file
#' @return none
#' @import grid
#' @import gridExtra
#' @import gtable
#' @export
PlotGridMetricsList <- function(metrics.list,
                                file,
                                round = 2,
                                width = 1400,
                                height = 1600,
                                ncol = 2) {
  table.list <- list()
  for (i in seq_along(metrics.list)) {
    df <- round(metrics.list[[i]], round)
    title <- textGrob(names(metrics.list)[i],
                      gp = gpar(fontsize = 15))

    table <- gtable_add_rows(tableGrob(df),
                             heights = grobHeight(title) + unit(10, "mm"),
                             pos = 0)

    table.list[[i]] <- gtable_add_grob(table, title, 1, 2, 1, ncol(table))
  }

  # save file
  png(filename = file, width = width, height = height)
  do.call(grid.arrange, c(table.list, ncol = ncol))
  invisible(dev.off())
}


#' Plot a Grid for Perf Metrics
#'
#' @param metrics dataframe perf metric, gened by OutputWrapper
#' @param path string of path for target image output
#' @param width,height int of sizes, default: 1800 x 480
#' @return save an image in ./images/metrics.png
#' @export
PlotGridMetrics <- function(metrics, file,
                            round = 2,
                            width = 1800,
                            height = 480) {
  png(filename = file, width = width, height = height)
  gridExtra::grid.table(round(metrics, round))
  invisible(dev.off())
}


#' Plot a Line Plot for Std Filter (for PE ratio filter)
#'
#' @param series xts object, original time series, monthly
#' @param idx vector of yearmon objects that can used for indexing series
#' @param title string main title of the plot
#' @return plot in the output stream
#' @export
PlotFilterCompLine <- function(series, idx, title = " ") {
  plot(cbind(series[idx], series), type='l', main=title)
}
hughshuwang/isocyanate documentation built on May 30, 2019, 7:17 a.m.