mineralpoint
mineralpoint

Reputation: 23

What step is necessary to get an output after running add.distribution and apply.paramset when optimizing in Quantstrat?

I have been following the following tutorial to learn how to test different variables in quantstrat.

https://timtrice.github.io/backtesting-strategies/parameter-optimization.html

The part of the tutorial about optimization is in part 7 of this link, but it depends on the previous sections.

After I enter apply.paramset, R doesn't return anything.

If I enter tradeStats(portfolio.st,'SPY'), it returns this;

 [1] Portfolio          Symbol             Num.Txns           Num.Trades        
 [5] Total.Net.Profit   Avg.Trade.PL       Med.Trade.PL       Std.Err.Trade.PL  
 [9] Largest.Winner     Largest.Loser      Gross.Profits      Gross.Losses      
[13] Std.Dev.Trade.PL   Percent.Positive   Percent.Negative   Profit.Factor     
[17] Avg.Win.Trade      Med.Win.Trade      Avg.Losing.Trade   Med.Losing.Trade  
[21] Avg.Daily.PL       Med.Daily.PL       Std.Dev.Daily.PL   Std.Err.Daily.PL  
[25] Ann.Sharpe         Max.Drawdown       Profit.To.Max.Draw Avg.WinLoss.Ratio 
[29] Med.WinLoss.Ratio  Max.Equity         Min.Equity         End.Equity        
<0 rows> (or 0-length row.names)

This dataframe is in the format I would expect, but it has no values. What I am hoping to get will show me values for each combination of slow and fast SMA values.

I tried running apply.strategy, but that gives me the same result.

My understanding is that apply.paramset has a similar function to apply.strategy.

I tried running it with and without this section which gives the same result.

library(parallel)

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

The code, taken directly from this tutorial is as follows.

Is there something I am missing here? I went through part 12 of the tutorial, and had no trouble viewing the results of part 5, which does not include a distribution. However, I don't see anything in there about viewing results after optimization.

#Tutorial Part 5

  library(quantstrat)
    library(blotter)
Sys.setenv(TZ = "UTC")

currency('USD')

init_date <- "2007-12-31"
start_date <- "2008-01-01"
end_date <- "2009-12-31"
init_equity <- 1e4 # $10,000
adjustment <- TRUE


basic_symbols <- function() {
  symbols <- c(
    "IWM", # iShares Russell 2000 Index ETF
    "QQQ", # PowerShares QQQ TRust, Series 1 ETF
    "SPY" # SPDR S&P 500 ETF Trust
  )
}

symbols <- basic_symbols()

getSymbols(Symbols = symbols, 
           src = "yahoo", 
           index.class = "POSIXct",
           from = start_date, 
           to = end_date, 
           adjust = adjustment)

stock(symbols, 
      currency = "USD", 
      multiplier = 1)

portfolio.st <- "Port.Luxor"
account.st <- "Acct.Luxor"
strategy.st <- "Strat.Luxor"

rm.strat(portfolio.st)
rm.strat(account.st)

initPortf(name = portfolio.st,
          symbols = symbols,
          initDate = init_date)

initAcct(name = account.st,
         portfolios = portfolio.st,
         initDate = init_date,
         initEq = init_equity)

initOrders(portfolio = portfolio.st,
           symbols = symbols,
           initDate = init_date)
strategy(strategy.st, store = TRUE)

add.indicator(strategy = strategy.st,
              name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), 
                               n = 10),
              label = "nFast")
add.indicator(strategy = strategy.st, 
              name = "SMA", 
              arguments = list(x = quote(Cl(mktdata)), 
                               n = 30), 
              label = "nSlow")

add.signal(strategy = strategy.st,
           name="sigCrossover",
           arguments = list(columns = c("nFast", "nSlow"),
                            relationship = "gte"),
           label = "long")

add.signal(strategy = strategy.st,
           name="sigCrossover",
           arguments = list(columns = c("nFast", "nSlow"),
                            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", 
                          TxnFees = -10, 
                          replace = FALSE),
         type = "enter",
         label = "EnterLONG")

add.rule(strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "short",
                          sigval = TRUE,
                          orderqty = -100,
                          ordertype = "stoplimit",
                          threshold = -0.005, 
                          orderside = "short", 
                          replace = FALSE, 
                          TxnFees = -10, 
                          prefer = "Low"),
         type = "enter",
         label = "EnterSHORT")

add.rule(strategy.st, 
         name = "ruleSignal", 
         arguments = list(sigcol = "short", 
                          sigval = TRUE, 
                          orderside = "long", 
                          ordertype = "market", 
                          orderqty = "all", 
                          TxnFees = -10, 
                          replace = TRUE), 
         type = "exit", 
         label = "Exit2SHORT")
add.rule(strategy.st, 
         name = "ruleSignal", 
         arguments = list(sigcol = "long", 
                          sigval = TRUE, 
                          orderside = "short", 
                          ordertype = "market", 
                          orderqty = "all", 
                          TxnFees = -10, 
                          replace = TRUE), 
         type = "exit", 
         label = "Exit2LONG")
cwd <- getwd()
setwd("C:\\Users\\NEW USER\\Desktop\\RYO\\R Working Directory")
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)

#Tutorial, Part 7
.fastSMA <- (1:30)
.slowSMA <- (20:80)
.nsamples <- 5
portfolio.st <- "Port.Luxor.MA.Opt"
account.st <- "Acct.Luxor.MA.Opt"
strategy.st <- "Strat.Luxor.MA.Opt"

rm.strat(portfolio.st)
rm.strat(account.st)

initPortf(name = portfolio.st,
          symbols = symbols,
          initDate = init_date)
initAcct(name = account.st,
         portfolios = portfolio.st,
         initDate = init_date,
         initEq = init_equity)
initOrders(portfolio = portfolio.st,
           symbols = symbols,
           initDate = init_date)

strategy(strategy.st, store = TRUE)

rm.strat(portfolio.st)
rm.strat(account.st)
initPortf(name = portfolio.st,
          symbols = symbols,
          initDate = init_date)
initAcct(name = account.st,
        portfolios = portfolio.st,
        initDate = init_date)
initOrders(portfolio = portfolio.st,
           initDate = init_date)
add.distribution(strategy.st,
                 paramset.label = "SMA",
                 component.type = "indicator",
                 component.label = "nFast",
                 variable = list(n = .fastSMA),
                 label = "nFAST")
add.distribution(strategy.st,
                 paramset.label = "SMA",
                 component.type = "indicator",
                 component.label = "nSlow",
                 variable = list(n = .slowSMA),
                 label = "nSLOW")
add.distribution.constraint(strategy.st,
                            paramset.label = "SMA",
                            distribution.label.1 = "nFAST",
                            distribution.label.2 = "nSLOW",
                            operator = "<",
                            label = "SMA.Constraint")
library(parallel)

if( Sys.info()['sysname'] == "Windows") {
  library(doParallel)
  registerDoParallel(cores=detectCores())
} else {
  library(doMC)
  registerDoMC(cores=detectCores())
}
cwd <- getwd()
setwd("C:\\Users\\NEW USER\\Desktop\\RYO\\R Working Directory")
results_file <- paste("results", strategy.st, "RData", sep = ".")
if( file.exists(results_file) ) {
  load(results_file)
} else {
  results <- apply.paramset(strategy.st,
                            paramset.label = "SMA",
                            portfolio.st = portfolio.st,
                            account.st = account.st, 
                            nsamples = .nsamples)
  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)

checkBlotterUpdate(portfolio.st, account.st, verbose = TRUE)

updatePortf(portfolio.st)
updateAcct(account.st)
updateAcct(account.st)

Upvotes: 1

Views: 153

Answers (1)

Jasen Mackie
Jasen Mackie

Reputation: 71

Hi @mineralpoint that book is quite old relative to the latest version of quantstrat, and the order of code in that script is not correct. You need to run the parameter optimizations after the original strategy is run with applyStrategy and there is some code removing portfolio.st which is why tradeStats(portfolio.st,'SPY') is empty. Best thing i can advise is to look at the range of demos on the repo at https://github.com/braverock/quantstrat/tree/master/demo.

Upvotes: 1

Related Questions