在R中运行applyStrategy

时间:2016-04-22 13:59:49

标签: r quantitative-finance algorithmic-trading quantstrat back-testing

您好我正在研究配对交易策略。目前,我正在对我在某些假设下发现的任何一对进行反向测试。为此我在R中使用“quantstrat”包。我发现很难理解applyStrategy函数中究竟发生了什么,特别是在我经历了以下内容之后:

我为两对运行了一个演示代码:

suppressWarnings(rm("order_book.pair1",pos=.strategy))
suppressWarnings(rm("account.pairs", "portfolio.pair1", pos=.blotter))
suppressWarnings(rm("startDate", "endDate", "startDate", "initEq", "SD", "N", 
                "symb1", "symb2", "portfolio1.st", "account.st", 
                "pairStrat", "out1"))

initDate <- '2015-04-21'    
endDate <- '2016-04-21'
startDate <- '2015-04-22'
initEq <- 100000


MaxPos <- 1500  #max position in stockA; 

lvls <- 3  #how many times to fade; Each order's qty will = MaxPos/lvls

symb1 <- 'SYY' #change these to try other pairs
symb2 <- 'SRE' #if you change them, make sure position limits still make  sense

portfolio1.st <- 'pair1'
account.st <- 'pairs'

getSymbols(c(symb1, symb2), from=startDate, to=endDate, adjust=TRUE) 


alignSymbols <- function(symbols, env=.GlobalEnv) {
 # This is a simplified version of qmao::alignSymbols()

 if (length(symbols) < 2) 
 stop("Must provide at least 2 symbols")

 if (any(!is.character(symbols))) 
 stop("Symbols must be vector of character strings.")
  ff <- get(symbols[1],env=env)

   for (sym in symbols[-1]) {
      tmp.sym <- get(sym,env=env)
      ff <- merge(ff, tmp.sym, all=FALSE)
  }

  for (sym in symbols) {
    assign(sym,ff[,grep(sym, colnames(ff))], env=env)
 }
 symbols
}

alignSymbols(c(symb1, symb2))


currency("USD")
stock(symb1, currency="USD", multiplier=1)
stock(symb2, currency="USD", multiplier=1)


initPortf(name=portfolio1.st, c(symb1,symb2))
initAcct(account.st, portfolios=portfolio1.st, initEq=initEq)
initOrders(portfolio=portfolio1.st)

其余代码可在此处获取(https://r-forge.r-project.org/scm/viewvc.php/pkg/quantstrat/demo/pair_trade.R?view=markup&root=blotter

运行“策略”后,我计算累积回报并获得总计-0.05818081。

现在,如果我接下来要做的就是再次运行代码的最后一部分:

out1<-applyStrategy(strategy=pairStrat, portfolios=portfolio1.st)

updatePortf(Portfolio=portfolio1.st,
        Dates=paste("::", as.Date(Sys.time()), sep=''))
updateAcct(account.st, Dates=paste(startDate, endDate, sep="::")) 
updateEndEq(account.st, Dates=paste(startDate, endDate, sep="::"))
getEndEq(account.st, Sys.time())

dev.new()
chart.Posn(Portfolio=portfolio1.st, Symbol=symb1)
dev.new()
chart.Posn(Portfolio=portfolio1.st, Symbol=symb2)
dev.new()
chartSeries(Cl(get(symb1))/Cl(get(symb2)), TA="addBBands(n=N,sd=SD)")

ret1 <- PortfReturns(account.st)
ret1$total <- rowSums(ret1)
 Return.cumulative(ret1)

然后我得到-0.9044952作为累积回报。我知道如果我想再次获得-0.05818081的回报,那么我需要重新启动投资组合。但是,我正在寻找的是帮助理解运行

的影响
 applyStrategy() 

本评论中解释的两次。帮助将非常感谢!

0 个答案:

没有答案