R Quantstrat optimization for KST()

Viewed 7

I want to optimize the parameters of the KST indicator. But i just cant make it work. The problem is that the KST needs 4 different ROC and for each ROC a SMA but it looks like it is not possible to use multiple parameters for one variable at the same time during the optimisation. Also I am completely new to quantstrat and R basicly so forgive me if my code isnt as sexy as it could be or if the solution is obvious to some of you. is it even possible or can i use a different method?

First my code for creating the strategy:

library(quantstrat)
library(dplyr)
#library(data.table)
library(DT)
library(ggplot2)
library(htmltools)
library(htmlwidgets)
library(knitr)
library(lattice)
library(pander)
#kernvariablen
init_date<-"2017-12-31"
start_date<-"2018-01-01"
end_date<-Sys.Date()
initEq<-10000
currency("USD")
adjustment<-TRUE
currency("USD")
Sys.setenv(TZ = "UTC")
basic_symbols<-function(){
  symbols<-c(
    #"FUTY",
    "XLY"#,
    # "VAW",
    #"PTH"
  )
}

portfolio.st<-"Port.KST"
account.st<-"Acct.KST"
strategy.st<-"Strat.KST"
#symbols<-c("XLY")
symbols<-basic_symbols()
getSymbols(Symbols = symbols,
           from= start_date,
           to= end_date,
           index.class="POSIXct")
stock(symbols,
      currency = "USD",
      multiplier = 1)
rm.strat(portfolio.st)
rm.strat(account.st)
rm.strat(strategy.st)
initPortf(name = portfolio.st,
          symbols = symbols,
          initDate = init_date)
initAcct(name = account.st,
         portfolios = portfolio.st,
         initDate = init_date,
         initEq = initEq)
initOrders(portfolio = portfolio.st,
           symbols = symbols,
           initDate = init_date)
strategy(strategy.st,
         store = TRUE)

add.indicator(strategy = strategy.st, 
              name = "KST", 
              arguments = list(price = quote(Cl(mktdata)),
                               n=c(10,10,10,15),
                               wts=1:4),
              label = "kst")
mean(.kstDistr2)
add.signal(strategy =strategy.st,
           name = "sigCrossover",
           arguments = list(
             columns =c("signal","kst"),
             relationship="gte"),
           label = "long")
add.signal(strategy.st,
           name = "sigCrossover",
           arguments = list(columns =c("signal","kst"),
                            relationship="lt"),
           label = "short")
add.rule(strategy = strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol="long",
                          sigval=TRUE,
                          orderqty=100,
                          ordertype="stoplimit",
                          orderside="long",
                          threshold=0.0005,
                          prefer="High",
                          TxmFees=-10,
                          replace=FALSE),
         type = "enter",
         label = "EnterLONG")
add.rule(strategy = strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol="short",
                          sigval=TRUE,
                          orderqty=-100,
                          ordertype="stoplimit",
                          orderside="short",
                          threshold=-0.005,
                          prefer="Low",
                          TxmFees=-10,
                          replace=FALSE),
         type = "enter",
         label = "EnterLONG")
add.rule(strategy = strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol="short",
                          sigval=TRUE,
                          orderside="short",
                          ordertype="market",
                          orderqty="all",
                          TynFees=-10,
                          replace=TRUE),
         type = "exit",
         label = "Exit2SHORT")
add.rule(strategy = strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol="long",
                          sigval=TRUE,
                          orderside="short",
                          ordertype="market",
                          orderqty="all",
                          TynFees=-10,
                          replace=TRUE),
         type = "exit",
         label = "Exit2LONG")
checkBlotterUpdate <- function(port.st = portfolio.st, 
                               account.st = account.st, 
                               verbose = TRUE) {
  
  ok <- TRUE
  p <- getPortfolio(port.st)
  a <- getAccount(account.st)
  syms <- names(p$symbols)
  port.tot <- sum(
    sapply(
      syms, 
      FUN = function(x) eval(
        parse(
          text = paste("sum(p$symbols", 
                       x, 
                       "posPL.USD$Net.Trading.PL)", 
                       sep = "$")))))
  
  port.sum.tot <- sum(p$summary$Net.Trading.PL)
  
  if(!isTRUE(all.equal(port.tot, port.sum.tot))) {
    ok <- FALSE
    if(verbose) print("portfolio P&L doesn't match sum of symbols P&L")
  }
  
  initEq <- as.numeric(first(a$summary$End.Eq))
  endEq <- as.numeric(last(a$summary$End.Eq))
  
  if(!isTRUE(all.equal(port.tot, endEq - initEq)) ) {
    ok <- FALSE
    if(verbose) print("portfolio P&L doesn't match account P&L")
  }
  
  if(sum(duplicated(index(p$summary)))) {
    ok <- FALSE
    if(verbose)print("duplicate timestamps in portfolio summary")
    
  }
  
  if(sum(duplicated(index(a$summary)))) {
    ok <- FALSE
    if(verbose) print("duplicate timestamps in account summary")
  }
  return(ok)
}
cwd <- getwd()
results_file <- paste("results", strategy.st, "RData", sep = ".")
if( file.exists(results_file) ) {
  load(results_file)
} else {
  results <- applyStrategy(strategy.st, portfolios = portfolio.st)
  updatePortf(portfolio.st)
  updateAcct(account.st)
  updateEndEq(account.st)
  if(checkBlotterUpdate(portfolio.st, account.st, verbose = TRUE)) {
    save(list = "results", file = results_file)
    save.strategy(strategy.st)
  }
}
setwd(cwd)
applyStrategy(strategy.st, portfolios = portfolio.st)
updatePortf(portfolio.st)
updateAcct(account.st)
updateEndEq(account.st)
tstats <- tradeStats(portfolio.st)
kable(t(tstats))

now the code for the optimization process:

.kstDistr1 <- 1:10
.kstDistr2 <- matrix(runif(16,10,16),4,4)%>%round()
library(parallel)
if( Sys.info()['sysname'] == "Windows") {
  library(doParallel)
  registerDoParallel(cores=detectCores())
} else {
  library(doMC)
  registerDoMC(cores=detectCores())
}
#Add Distribution
nn1<-10:15
nn2<-10:15
nn3<-10:15
nn4<-10:15
nROCn<- 10:20
add.distribution(strategy.st,
                 paramset.label = "KST1",
                 component.type = "indicator",
                 component.label = "kst",
                 variable = list(n=c(nn1,nn2,nn3,nn4)),
                 label = "kst")
add.distribution(strategy.st,
                 paramset.label = "KST1",
                 component.type = "indicator",
                 component.label = "kst",
                 variable = list(n=c(nn1,nn2,nn3,nn4)),
                 label = "kst2")
add.distribution(strategy.st,
                 paramset.label = "KST1",
                 component.type = "indicator",
                 component.label = "kst",
                 variable = list(n=c(nn1,nn2,nn3,nn4)),
                 label = "kst3")
add.distribution(strategy.st,
                 paramset.label = "KST1",
                 component.type = "indicator",
                 component.label = "kst",
                 variable = list(n=c(nn1,nn2,nn3,nn4)),
                 label = "kst4")
set.seed(20201312)
.nsamples <-5
rm(results)
results <- apply.paramset(strategy.st,
                          paramset.label = "KST1",
                          portfolio.st = portfolio.st,
                          account.st = account.st,
                          nsamples = .nsamples,
                          #paramsets = t(.kstDistr2),
                          verbose = TRUE)
closeAllConnections()
0 Answers
Related