R/hedge.R

Defines functions simulate_hedge

Documented in simulate_hedge

#' Hedge optimization simulation
#'
#' @param scenarios Shares paths scenarios
#' @param S0        Shares initial price
#' @param I0        Index Initial price
#' @param size      Population size
#' @param epochs    Number of epochs
#'
#' @return          A GA object
#' @importFrom GA ga
#' @export
#'
#' @examples
#' ## Not Run: obj <- simulate_hedge(scenarios, closing_last, index, 50, 200)
#'
simulate_hedge <- function(fitfun, scenarios, S0, I0, size, epochs) {

  # preparing market data from scenarios
  px_end <- NULL
  idx_end <- NULL
  for (s in 1:length(scenarios)) {
    scn <- scenarios[[s]]
    px_end <- rbind(px_end,
                    scn[nrow(scn), ])
    idx_end <- rbind(idx_end,
                     compute_index(as.matrix(scn[nrow(scn), ]),
                                   symbol$Weight))
  }


  model1 <- GA::ga("real-valued",
                  fitness = function(x) -fitfun(x[1],   x[2],  x[3],  x[4],  x[5],  x[6],  x[7],  x[8],  x[9], x[10],
                                                  x[11], x[12], x[13], x[14], x[15], x[16], x[17], x[18], x[19], x[20],
                                                  x[21], x[22], x[23], x[24], x[25], x[26], x[27], x[28], x[29], x[30],
                                                  x[31], x[32], x[33], x[34], x[35], S0, I0, px_end, idx_end),
                  lower = rep(-500, 35),
                  upper = rep(500, 35),
                  popSize = size[1],
                  pcrossover = 0.8,
                  pmutation = 0.20,
                  maxiter = epochs[1],
                  names = colnames(scenarios[[1]]),
                  parallel = TRUE)
  cat("\n")
  model2 <- GA::ga("real-valued",
                  fitness = function(x) -fitfun(x[1],   x[2],  x[3],  x[4],  x[5],  x[6],  x[7],  x[8],  x[9], x[10],
                                                  x[11], x[12], x[13], x[14], x[15], x[16], x[17], x[18], x[19], x[20],
                                                  x[21], x[22], x[23], x[24], x[25], x[26], x[27], x[28], x[29], x[30],
                                                  x[31], x[32], x[33], x[34], x[35], S0, I0, px_end, idx_end),
                  lower = model1@solution / 2,
                  upper = abs(model1@solution) * 2,
                  popSize = size[2],
                  pcrossover = 0.8,
                  pmutation = 0.10,
                  maxiter = epochs[2],
                  names = colnames(scenarios[[1]]),
                  suggestions = model1@solution,
                  parallel = TRUE)

  invisible(list(model1, model2))
}
bpvgoncalves/DynHedge documentation built on Dec. 19, 2021, 10:52 a.m.