在quantstrat中实现多个条件,同时在TA指标中引用n个周期

时间:2014-08-08 08:14:06

标签: r quantstrat

我正在尝试使用ADX指标在quantstrat中应用一个非常基本的策略。该策略寻找具有低但向上趋势的ADX的情况,特别是:

规则1:ADX< 20;

规则2:今天的ADX大于ADX 5个时期之前;

规则3:当ADX> 35

时退出交易

我试图跟随Guy Yollen的优秀指南,但我仍然陷入“交易逻辑”组件:

library(blotter)
currency("USD")
stock("SPY",currency="USD",multiplier=1)
get("USD",envir=FinancialInstrument:::.instrument)
get("SPY",envir=FinancialInstrument:::.instrument)

Sys.setenv(TZ="UTC")
startDate <- '1998-01-01'
endDate <- '2014-07-31'

getSymbols('SPY',from=startDate,to=endDate,index.class=c("POSIXt","POSIXct"),
           adjust=T)

SPY = to.monthly(SPY,indexAt='endof',drop.time=FALSE)


SPY$ADX <- ADX(HLC(SPY))

#rm.strat(a.strategy)
a.strategy <- "TestADX"
initPortf(a.strategy,'SPY',initDate='1997-12-31')
initAcct(a.strategy,portfolios=a.strategy,initDate='1997-12-31',initEq=1e6)

first(SPY)


myTheme <- chart_theme()
myTheme$col$dn.col <- 'lightblue'
myTheme$col$dn.border <- 'lightgray'
myTheme$col$up.border <- 'lightgray'


###Not sure why this one-liner does not work but not critical
chartSeries(x=SPY,theme=myTheme,name="SPY",TA="addADX()")  

#####################Trading logic############################################

for( i in 1:nrow(SPY))
{
  #update values for this date
  CurrentDate <- time(SPY)[i]
  equity = getEndEq(a.strategy,CurrentDate)
  ClosePrice <- as.numeric(Cl(SPY[i,]))
  Posn <- getPosQty(a.strategy,Symbol='SPY',Date=CurrentDate)
  UnitSize = as.numeric(trunc(equity/ClosePrice))
  adx <- as.numeric(SPY[i,'ADX'])
  diffadx <- as.numeric(diff(SPY[i,'ADX',lag=5]))#####INSERT

  #change mkt position if necessary

  if( !is.na(adx) )#if the moving avg has begun
  {
    if(Posn == 0) {#No position test to go long
        #if((adx < 20) && (diff(adx,lag=5) > 0.2)){
        if((adx < 20) && (diffadx > 0.2)){    #####INSERT
        #enter long position
        addTxn(a.strategy,Symbol='SPY',TxnDate=CurrentDate,
               TxnPrice=ClosePrice,TxnQty=UnitSize,TxnFees=0)}
    }else {#Have a position so check exit
      if ( adx > 35){
        #exit position
        addTxn(a.strategy,Symbol='SPY',TxnDate=CurrentDate,
               TxnPrice = ClosePrice,TxnQty = -Posn,TxnFees=0)}
    }
  }

  #Calculate P&L and resulting Equity with blotter
  updatePortf(a.strategy,Dates=CurrentDate)
  updateAcct(a.strategy,Dates=CurrentDate)
  updateEndEq(a.strategy,Dates=CurrentDate)
}#end Dates loop

##End of trading logic piece####

在此阶段R返回错误: if((adx&lt; 20)&amp;&amp;(diffadx&gt; 0.2)){的错误:   缺少需要TRUE / FALSE的值

chart.Posn(a.strategy,Symbol='SPY',Dates='1998::',theme=myTheme)     

plot(add_ADX(n=14,col=4,on=1))  

0 个答案:

没有答案