R/selectStrategyParameter.R

#' Select Best Strategy Parameters from a Backtest Result File
#'
#' @param backtest_results backtest results
#' @param wrow rows of window for detection of maxima in a backest results matrix
#' @param wcol columns of window for detection of maxima in a backest results matrix
#'
#' @return xyz
#' @export selectStrategyParameter
#'
#' @examples selectStrategyParameter(backtest_results, wrow=4, wcol=2)
selectStrategyParameter <- function (backtest_results, wrow=4, wcol=2) {

  #wrow/wcol : window for calculation of statistics on each cell in the backtest results matrix
  backtest_statistics <- list()

  for (i in 1:length(backtest_results)) {

    #extend borders of the backtest results matrix
    d <- max(wrow, wcol)
    x <- backtest_results[[i]][[2]]
    x_ext <- matrix(as.numeric(quantile(x, 0.25)),
                    nrow = dim(x)[1]+2*d, ncol = dim(x)[2]+2*d)
    x_ext[(1+d):(dim(x_ext)[1]-d),(1+d):(dim(x_ext)[2]-d)] <- x

    #window definition
    #x_ext[(r-wrow):(r+wrow),(k-wcol):(k+wcol)]
    #subset by rolling windows / colnames are backtest screen parameters
    windows_list <- list()
    for (r in (d+1):(nrow(x_ext)-d)) {

      windows_list[[r-d]] <- sapply( (d+1):(ncol(x_ext)-d),
                                     function (k)  x_ext[(r-wrow):(r+wrow),(k-wcol):(k+wcol)] ) %>%
        'colnames<-'(paste0( rownames(backtest_results[[i]][[2]])[r-d], ", ",
                             colnames(backtest_results[[i]][[2]]) ))

    }
    cell_statistics <- do.call(cbind, windows_list)
    cell_mean <- round(apply(cell_statistics, 2, mean, na.rm=TRUE), 2)
    cell_sd <- round(apply(cell_statistics, 2, sd, na.rm=TRUE), 2)

    stats <- cbind.data.frame(cell_mean, cell_sd)
    stats$parameter <- as.character(names(cell_mean))
    stats$stoploss <- rep(backtest_results[[i]][[1]], times=nrow(stats))

    backtest_statistics[[i]] <- stats

  }
  return(backtest_statistics)

}
rengelke/quantTraiding_trato documentation built on Oct. 13, 2020, 12:01 p.m.