Implementation of several conditions in quantumstratum, while mentioning n periods ago in the TA indicator
I am trying to apply a very basic strategy in quantstrate using the ADX indicator. The strategy looks for situations with a low but upward ADX trend, in particular:
Rule 1: ADX <20;
Rule 2: ADX today is greater than ADX 5 periods ago;
Rule 3: Exiting a trade when ADX> 35
I tried to follow Guy Yollen's excellent guide, but I'm still stuck with the Trade Logic component:
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####
At this point, R returns the error: Error in if ((adx <20) && (diffadx> 0.2)) {: missing TRUE / FALSE
chart.Posn(a.strategy,Symbol='SPY',Dates='1998::',theme=myTheme)
plot(add_ADX(n=14,col=4,on=1))
+3
source to share
No one has answered this question yet
Check out similar questions: