Search code examples
rquantmodquantstrat

Quantstrat sigPeak error: "k must be a non-negative integer"


I am trying to use a sigPeak signal and my code for adding this is:

add.signal(strategy=strat.id, name='sigPeak',
           arguments=list(column='ADX.ADX', direction="peak", data=quote(mktdata)),
           label='ADX.peak')

However, when I run applySignals(..., applyIndicators(..)) right after adding that one, I get an error:

Error in FUN(X[[i]], ...) : k must be a non-negative integer

I believe it is due to a contradictio in codicum in the following lines of quantmod and quantstrat:

Quantstrat, in the definition of sigPeak:

Lag(ret_sig,-1)

Quantmod, in the definition of Lag.quantmod.OHLC as that is the one that is used on XTS objects:

if(k.e<0||k.e!=as.integer(k.e)) stop("k must be a non-negative integer")

Does this mean that with the current versions of quantmod and quantstrat, sigPeak just doesn't work?


Solution

  • I'm not sure when that function was in a working state. That line was added in revision 588 in March 2011. Before that, the state of the function was:

    sigPeak <- function(label,data,column, direction=c("peak","bottom")){
        colNum<-match.names(column,colnames(data))
        direction=direction[1] # only use the first]
        switch(direction,
               "peak"   = { Lag(data[,colNum],2) < Lag(data[,colNum],1) & Lag(data[,colNum],1) > data[,colNum] } ,
               "bottom","valley" = { Lag(data[,colNum],2) > Lag(data[,colNum],1) & Lag(data[,colNum],1) < data[,colNum] }
        )
        colnames(ret_sig)<-paste(label,direction,"sig",sep='.')
        return(ret_sig)
    }
    

    You can see that ret_sig is not created before it's referenced via colnames, so the call to colnames would have thrown an error.

    Anyway, to fix the problem you just need to remove the Lag(ret_sig, -1) line. The value isn't assigned to anything, so it's not actually doing anything.

    Reported and fixed in issue #41.