[R-SIG-Finance] sample code for a custom rule to replace ruleSignal

Gambulator Gambulator gambulator at gmail.com
Sat Oct 17 18:15:45 CEST 2015


Hi

I saw this
http://r.789695.n4.nabble.com/Writing-sell-rules-with-quantstrat-td4389599.html

by Sergey Pisarenko
<http://r.789695.n4.nabble.com/template/NamlServlet.jtp?macro=user_nodes&user=344717>
and I am trying to implement something similar by starting out with what
he's got (firstProfitable function below)

The program would run and give me the 1st buy and sell signal but then it
keeps saying
"Error in if (!orderPrefer == "") prefer = orderPrefer :
  missing value where TRUE/FALSE needed"

and die right after the 1st signal.


So, I went into debug mode and see what's happening. I am only testing 1
symbol SPY and there is only one order of buy and one order to sell. I
don't add positions in-between. Somehow, Ithis orderPrice variable has 2
entries and I think that's why the prefer is also expecting 2 entries. Does
anyone have a simple sample ? By the way, for the entry, I am still using
signalRule, I only want to replace the exit with this custom function.

add.rule(qs.strategy, name="ruleSignal",
         arguments=list(sigcol="longEntry", sigval=TRUE, orderqty=100,
                        ordertype="market", orderside="long",
                        replace=FALSE, prefer="Close",orderset='rsilong',
allowMagicalThinking=TRUE,osFUN=osMaxEquity),
         type='enter', label="long RDM"
)

add.rule(qs.strategy, name="firstProfitable",
         arguments=list(sigcol="longExit", sigval=TRUE,
orderqty='all',data=mktdata,symbol,maxHold=5,orderside="long",prefer="Close"
                        ),
         type='exit', label="sell RDM"
)





firstProfitable<-function(data, timestamp, portfolio,
symbol,maxHold,prefer) {
  posn <- getPosQty(portfolio, symbol, timestamp)
  if (posn != 0) {
    pos         <- getPos(portfolio, symbol, timestamp)
    holdPeriod  <- as.Date(timestamp) - as.Date(index(pos) )
    print(index(pos))
    print((pos))
    print(as.POSIXlt(timestamp))
    print(as.Date(index(pos)))
    orderprice <- as.numeric(Cl(data[timestamp,]))
    print(orderprice)
    #qty        <- as.vector(pos[, 1])

    if (holdPeriod > maxHold) {
      addOrder(portfolio=portfolio, symbol=symbol,
               timestamp=timestamp, qty='all',
price=as.numeric(orderprice),
               ordertype='market',
side='long',prefer='Close',label='maxHold')
    }

    buy_price   <- as.numeric(pos[1, 2])
    close_price <- as.numeric(Cl(mktdata[timestamp,]))
    profit      <- (close_price - buy_price) / buy_price

    if (profit > 0) {
      addOrder(portfolio=portfolio, symbol=symbol,
               timestamp=timestamp, qty='all',
price=as.numeric(orderprice),
               ordertype='market',
side='long',prefer='Close',label='maxHold')
    }
  }
}

	[[alternative HTML version deleted]]



More information about the R-SIG-Finance mailing list