通过Quantstat示例产生错误

时间:2019-06-18 13:05:27

标签: r quantstrat

我正在尝试遍历quantstrat的示例(https://statsmaths.github.io/stat395-f17/assets/final_project/amarnani.html):Dhiraj Amarnani的《定量交易简介》和Quanstrat [sic]库 2017年11月29日,但出现错误。

我试图找到未定义的变量;例如,定义了“策略”,但没有定义。我没有足够的经验来进一步解决问题。 我在Github上发布了一个问题。我还在通过DataCamp上的quantstrat课程学习,但是还无法解决问题。最后,我搜索了堆栈溢出;还有其他quantstrat示例,但此处未引用该示例(尽管另有很多引用)。

library(devtools)
library(quantmod)
library(quantstrat)
library(TTR)
library(png)
library(IKTrading)

_________ SETUP ___________

rm(list = ls(.blotter), envir = .blotter)

initdate <- "2010-01-01"
from <- "2011-01-01" #start of backtest
to <- "2017-01-01" #end of backtest
Sys.setenv(TZ= "EST") #Set up environment for timestamps

currency("USD") #Set up environment for currency to be used

symbols <- c("AAPL", "MSFT", "GOOG", "FB", "TWTR", "AMZN", "IBM") #symbols used in our backtest
getSymbols(Symbols = symbols, src = "google", from=from, to=to, adjust = TRUE) #receive data from google finance,  adjusted for splits/dividends

stock(symbols, currency = "USD", multiplier = 1) #tells quanstrat [sic] what instruments present and what currency to use

tradesize <-10000 #default trade size
initeq <- 100000 #default initial equity in our portfolio

strategy.st <- portfolio.st <- account.st <- "firststrat" #naming strategy, portfolio and account

# removes old portfolio and strategy from environment
rm.strat(portfolio.st)
rm.strat(strategy.st) 

# initialize portfolio, account, orders and strategy objects
initPortf(portfolio.st, symbols = symbols, initDate = initdate, currency = "USD")
initAcct(account.st, portfolios = portfolio.st, initDate = initdate, 
currency = "USD", initEq = initeq)
initOrders(portfolio.st, initDate = initdate)
strategy(strategy.st, store=TRUE)

_________指标___________

# graphs creation code excluded here

add.indicator(strategy = strategy.st,
          name = 'SMA',
          arguments = list(x = quote(Cl(mktdata)), n=200),
          label = 'SMA200')
add.indicator(strategy = strategy.st,
          name = 'SMA',
          arguments = list(x = quote(Cl(mktdata)), n=50),
          label = 'SMA50')
add.indicator(strategy = strategy.st,
          name = 'RSI',
          arguments = list(price = quote(Cl(mktdata)), n=3),
          label = 'RSI_3')

____________信号___________

# graphs creation code excluded here

#First Signal: sigComparison specifying when 50-day SMA above 200-day SMA
add.signal(strategy.st, name = 'sigComparison',
      arguments = list(columns=c("SMA50", "SMA200")),
      relationship = "gt",
      label = "longfilter")

#Second Signal: sigCrossover specifying the first instance when 50-day SMA
# below 200-day SMA 
add.signal(strategy.st, name = "sigCrossover",
       arguments = list(columns=c("SMA50", "SMA200")),
       relationship = "lt",
       lablel = "sigCrossover.sig")

#Third Signal: sigThreshold which specifies all instance when RSI is below 20 (indication of asset being oversold)
add.signal(strategy.st, name = "sigThreshold",
       arguments = list(column = "RSI_3", threshold = 20,
                        relationship = "lt", cross = FALSE),
       label = "longthreshold")

#Fourth Signal: sigThreshold which specifies the first instance when rsi is above 80 (indication of asset being overbought)
add.signal(strategy.st, name = "sigThreshold",
       arguments = list(column = "RSI_3", threshold = 80,
                        relationship = "gt", cross = TRUE),
       label = "thresholdexit")

#Fifth Signal: sigFormula which indicates that both longfilter and longthreshold must be true.
add.signal(strategy.st, name = "sigFormula",
       arguments = list(formula = "longfilter & longthreshold",
                        cross = TRUE),
      label = "longentry")

________________规则________________

#The first rule will be an exit rule. This exit rule will execute when the market environment is no longer conducive to a trade (i.e. when the SMA-50 falls below SMA-200)
add.rule(strategy.st, name = "ruleSignal",
     arguments = list(sigcol = "sigCrossover.sig", sigval = TRUE,
                      orderqty = "all", ordertype = "market",
                      orderside = "long", replace = FALSE,
                      prefer = "Open"),
     type = "exit")

#The second rule, similar to the first, executes when the RSI has crossed above 80. 
add.rule(strategy.st, name = "ruleSignal",
     arguments = list(sigcol = "thresholdexit", sigval = TRUE,
                      orderqty = "all", ordertype = "market",
                      orderside = "long", replace = FALSE,
                      prefer = "Open"),
     type = "exit")

#Additionally, we also need an entry rule. This rule executes when 
# longentry is true (or when long filter and longthreshold are true). 
# That is when SMA-50 is above SMA-200 and the RSI is below 20.
add.rule(strategy.st, name = "ruleSignal",
     arguments = list(sigcol = "longentry", sigval = TRUE,
                      orderqty = 1, ordertype = "market",
                      orderside = "long", replace = FALSE,
                      prefer = "Open", osFUN = IKTrading::osMaxDollar,
                      tradeSize = tradesize, maxSize = tradesize),
     type = "enter")

______________性能分析_________________

# Here is the code that didn't work (first line): 

out <- applyStrategy(strategy = strategy.st, portfolios = portfolio.st)
updatePortf(portfolio.st)
daterange <- time(getPortfolio(portfolio.st)$summary)[-1]

updateAcct(account.st, daterange)
updateEndEq(account.st)



# Error in `dimnames<-.xts`(`*tmp*`, value = dn) : length of 'dimnames' [2] not equal to array extent
# In addition: Warning messages:
# 1: In match.names(columns, colnames(data)) :
# all columns not located in SMA50 SMA200 for AAPL.Open AAPL.High AAPL.Low 
# AAPL.Close AAPL.Volume AAPL.Adjusted
# 2: In min(j, na.rm = TRUE) :
# no non-missing arguments to min; returning Inf
# 3: In max(j, na.rm = TRUE) :
# no non-missing arguments to max; returning -Inf
# 4: In min(j, na.rm = TRUE) :
# no non-missing arguments to min; returning Inf
# 5: In max(j, na.rm = TRUE) :
# no non-missing arguments to max; returning -Inf
# 6: In match.names(column, colnames(data)) :
# all columns not located in RSI_3 for AAPL.Open AAPL.High AAPL.Low 
# AAPL.Close AAPL.Volume AAPL.Adjusted longfilter sigCrossover.sig
# 7: In min(j, na.rm = TRUE) :  no non-missing arguments to min; returning Inf
# 8: In max(j, na.rm = TRUE) :  no non-missing arguments to max; returning -Inf

1 个答案:

答案 0 :(得分:0)

回答我自己的问题;从我的目标开始,这是获得quantstrat运行的示例,以便我可以逐步进行更改以符合我们团队的交易策略。令我失望的是,我无法使上面引用的示例正常工作(并且我对Stack Overflow也一无所获),我最终找到了DataCamp上的一门课程,名为“ R中的金融交易”,以非常简单的方式介绍了Quantstrat软件包。在我看来,我在这里引用的示例似乎是从该课程中摘取的。我尝试从DataCamp幻灯片中运行quantstrat失败,但是使用课程中的示例能够使Quantstrat工作。强烈推荐。如果有人感兴趣,很高兴传递R代码。