0

我一直在按照以下教程学习如何在 quantstrat 中测试不同的变量。

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

关于优化的教程部分在此链接的第 7 部分,但它取决于前面的部分。

输入后apply.paramset, R 不返回任何内容。

如果我输入tradeStats(portfolio.st,'SPY'),它会返回这个;

 [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)

这个数据框是我期望的格式,但它没有值。我希望得到的将显示慢速和快速 SMA 值的每种组合的值。

我尝试运行apply.strategy,但这给了我相同的结果。

我的理解是apply.paramsetapply.strategy.

我尝试在有和没有这部分的情况下运行它,结果相同。

library(parallel)

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

直接取自本教程的代码如下。

我在这里缺少什么吗?我浏览了本教程的第 12 部分,并且可以轻松查看第 5 部分的结果,其中不包括分发。但是,我没有看到任何关于优化后查看结果的内容。

#教程第 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)
4

1 回答 1

0

嗨@mineralpoint,那本书相对于最新版本的 quantstrat 来说已经很老了,并且该脚本中的代码顺序不正确。您需要在运行原始策略后运行参数优化,applyStrategy并且有一些代码删除portfolio.st,这就是为什么tradeStats(portfolio.st,'SPY')为空。我可以建议的最好的事情是在https://github.com/braverock/quantstrat/tree/master/demo上查看 repo 上的演示范围。

于 2020-07-05T01:28:50.443 回答