braverock / quantstrat

289 stars 114 forks source link

add.distribution problem with KST() #147

Open maxsach opened 2 years ago

maxsach commented 2 years ago

hello, i am totally new to quantstrat and R so if my code might not be as "sexy" as it could. But feel free to mention parts where my code is redundant or if you have tips I am greatful for anything I basically tried to do a strategy with KST() and that works fine but the optimization doesnt. For the KST() i need 4 different ROC nROC = c(10, 15, 20, 30) then 4 different SMA that smooth the corresponding ROC n = c(10,10,10,15) 4 weights for each SMA wts = 1:4 this produces the KST line and lastly one SMA that makes the signal line nSig = 9 so what i want is totest for different combinations of values but I cant figure out how I tried the optimization only for values of n to see if it works but instead of getting 4 different SMA for my 4 different ROC it only works with the same SMA for all ROC also I get

Warning message: In xtfrm.data.frame(x) : cannot xtfrm data frames greatful for any help


my code
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), nROC = c(10, 15, 20, 30), nSig = 9, maType = "SMA", wts = 1:4), label = "kst") 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)

tstats <- tradeStats(portfolio.st) kable(t(tstats)) ###########################

.kstDistr <- matrix(c(10:12,10:12,10:12,15:17),4,3)

library(parallel)

if( Sys.info()['sysname'] == "Windows") { library(doParallel) registerDoParallel(cores=detectCores()) } else { library(doMC) registerDoMC(cores=detectCores()) }

Add Distribution

add.distribution(strategy.st, paramset.label = "KST", component.type = "indicator", component.label = "kst", variable = list(n = .kstDistr), label = "kst")

set.seed(20201312) .nsamples <-5 rm(results) results <- apply.paramset(strategy.st, paramset.label = "KST", portfolio.st = portfolio.st, account.st = account.st, nsamples = .nsamples, verbose = TRUE)

maxsach commented 2 years ago

ok i figured that when i use paramsets i can get a combination of values for n but now it either doesnt give me multiple samples and only uses the last row of the matix or if I use a nx1 vector it gives me the results for all rows but now i only have one vlaue for n

.kstDistr <- matrix(runif(8,10,16),4,2)%>%round()

library(parallel)

if( Sys.info()['sysname'] == "Windows") {
  library(doParallel)
  registerDoParallel(cores=detectCores())
} else {
  library(doMC)
  registerDoMC(cores=detectCores())
}
#Add Distribution
add.distribution(strategy.st,
                 paramset.label = "KST",
                 component.type = "indicator",
                 component.label = "kst",
                 variable = list(n=.kstDistr),
                 label = "kst")

runif(.kstDistr)

set.seed(20201312)
.nsamples <-5
rm(results)
results <- apply.paramset(strategy.st,
                          paramset.label = "KST",
                          portfolio.st = portfolio.st,
                          account.st = account.st,
                          nsamples = .nsamples,
                          paramsets = .kstDistr,
                          verbose = TRUE,
                          psgc=TRUE)

closeAllConnections()