[R-SIG-Finance] quantstrat newbie indicators example

Rob Schmidt roschm at ymail.com
Fri Mar 22 21:59:52 CET 2013


Hello All,

More newbie adventures in quantstrat.  This started from putting together a
file of some TA indicators as examples.  They are BBands, EMA, MACD, dual
SMA, RSI, Volatility, and IBS(Internal Bar Strength) as a custom indicator. 
It has morphed into a wierd little example of having multiple different
strategies for these TAs.  Each arbitrarily selected combination of TAs can
have a separate strategy.  And there are are almost none in there.  Only IBS
and SMA alone, and the both together have example strategies.  The rest of
the time it just goes long since it doesn't have one.  

There is also my attempt to make using the fast indicators as nearly
painless as the very slow but simple method from the first Frankenstein (so
that we might as well do the fast ones all the time).  

This also has some examples of generic plotting of columns from mktdata by
variable and by value.  This hasn't gotten too focused yet, so parts may be
useful as a basis for other ideas.  Please rip and tear.

I am reinventing the wheel, LOL.

Thanks in advance for all comments, suggestions, and warnings.

Rob

# the frankenstein of indicators(hyperbole),  Rob Schmidt
# thanks to the people who made these great packages and
# thanks to all who made the examples from which I copied 
# please feel free to copy/mangle/use this file in any way

# an example of using and plotting some technical indicators
# and selecting particular combinations of them for a strategy

# shows an example of utilizing fast signal indicators which
# are (nearly) as painless as the simple but very slow methods

# choose IBS and/or SMA TAs only to see an example strategy
# but almost all strategies are missing, in which case go long

writeResultFiles = FALSE  #TRUE  #
if(writeResultFiles)
{   resultsPath = '/home/rob/work/R/quantstrat/' # fix me
    setwd(resultsPath)
}

tmptz = Sys.getenv('TZ')
if(tmptz != 'UTC') ttz = tmptz
Sys.setenv(TZ='UTC')  # set default timezone

require(quantstrat)

try(rm("order_book.frank", pos=.strategy), silent=TRUE)
try(rm("account.frank", "portfolio.frank", pos=.blotter), 
                silent=TRUE)

stratg = "frank"  #  a creature from a collection of parts
symbol = "QQQ"
initDate = '2011-02-01'
endDate = '2011-06-01'
initEq = 1.0e6
orderSize = 100

useTA = list()  # a list of useable TA indicators

# Declare a TA indicator and choose
# TRUE or FALSE whether to enable it

useTA$BBands = FALSE
useTA$EMA = FALSE
useTA$IBS = TRUE
useTA$MACD = FALSE
useTA$SMA = TRUE
useTA$RSI = FALSE
useTA$Volatility = FALSE

numTAs = length(which(useTA == TRUE))  # number of TRUEs
indicatorLabels = list() # labels of the used indicators

currency("USD")
stock(symbol, currency="USD", multiplier=1)
getSymbols(symbol, from=initDate, to=endDate, adjust=TRUE)
initPortf(stratg, symbol, initDate=initDate)
initAcct(stratg, portfolios=stratg, initDate=initDate,
        initEq=initEq)
initOrders(portfolio=stratg, initDate=initDate)
strat = strategy(stratg)

# set parameters and declare indicatorLabel variables

if(useTA$BBands)  #  Bollinger Bands
{   bbPeriods = 12
    bbSD = 2
    bb = paste("BB",bbPeriods,".",bbSD,sep='')
    indicatorLabels$bb = bb
}
if(useTA$EMA)   #  Exponential Moving Average
{   emaPeriods = 10
    ema = paste("EMA",emaPeriods,sep='')
    indicatorLabels$ema = ema
}
if(useTA$IBS) # Internal Bar Strength custom indicator
{   ibsPeriods = 8
    ibs = paste("IBS",ibsPeriods,sep='')
    indicatorLabels$ibs = ibs
    
    # range: -1(closes at lows) to 1(closes at highs)
    # this is nonstandard: typical is 0 to 1 range
    # return 0 if hi == lo, to avoid divide by zero
    IBS = function(hi, lo, cl, n)
    {   temp = ifelse(hi > lo, 
                      2.0*runMean((cl-lo)/(hi-lo), n)-1.0, 0.0)
        colnames(temp) = ibs
        return(temp)
    }
}
if(useTA$MACD)  #  Moving Average Convergence Divergence
{   macdFast = 8 # 12
    macdSlow = 18 # 26
    macdSig = 6 # 9
}
if(useTA$RSI)  #  Relative Strength Indicator
{   rsiPeriods = 10
    rsi = paste("RSI",rsiPeriods,sep='')
    indicatorLabels$rsi = rsi
}
if(useTA$SMA)  #  Simple Moving Average
{   fastPeriods = 10
    slowPeriods = 2*fastPeriods
    smaFast = paste("SMA",fastPeriods,sep='')
    smaSlow = paste("SMA",slowPeriods,sep='')
    indicatorLabels$smaFast = smaFast
    indicatorLabels$smaSlow = smaSlow
}
if(useTA$Volatility)  #  Volatility
{   voltPeriods = 15
    voltCalc = "close"
    volt = paste("VOLT",voltPeriods,sep='')
    indicatorLabels$volt = volt
}

# select a particular combination of indicators
#   to redefine parameter values for this case only

if(useTA$IBS & useTA$SMA & (numTAs == 2)) # IBS and SMA only
{   ibsPeriods = 12
    ibs = paste("IBS",ibsPeriods,sep='')
    indicatorLabels$ibs = ibs

    fastPeriods = 8
    slowPeriods = 3*fastPeriods
    smaFast = paste("SMA",fastPeriods,sep='')
    smaSlow = paste("SMA",slowPeriods,sep='')
    indicatorLabels$smaFast = smaFast
    indicatorLabels$smaSlow = smaSlow
}

# add the original indicators

if(useTA$BBands)  #  Bollinger Bands
{   strat = add.indicator(strategy = strat, name = "BBands",
                arguments = list(HLC = quote(HLC(mktdata)), 
                maType='SMA', n=bbPeriods, sd=bbSD), 
                label=bb)
}
if(useTA$EMA)   #  Exponential Moving Average
{   strat = add.indicator(strategy=strat, name="EMA",
                arguments=list(x=quote(Cl(mktdata)), 
                n=emaPeriods), label=ema)
}
if(useTA$IBS) # Internal Bar Strength custom indicator
{   strat = add.indicator(strategy=strat, name="IBS",
                arguments=list(hi=get(symbol)[,2], 
                lo=get(symbol)[,3], cl=get(symbol)[,4], 
                n=ibsPeriods), label=ibs)
}
if(useTA$MACD)  #  Moving Average Convergence Divergence
{   strat = add.indicator(strategy=strat, name="MACD",
                arguments=list(x=quote(Cl(mktdata)),
                nFast=macdFast, nSlow=macdSlow, nSig=macdSig, 
                maType="EMA"), label="MACD")
}
if(useTA$RSI)  #  Relative Strength Indicator
{   strat = add.indicator(strategy=strat, name="RSI",
                arguments=list(price=quote(Cl(mktdata)), 
                n=rsiPeriods, maType="EMA"), label=rsi)
}
if(useTA$SMA)  #  Simple Moving Average
{   strat = add.indicator(strategy=strat, name="SMA",
                arguments=list(x=quote(Cl(mktdata)), 
                n=fastPeriods), label=smaFast)
    strat = add.indicator(strategy=strat, name="SMA",
                arguments=list(x=quote(Cl(mktdata)), 
                n=slowPeriods), label=smaSlow)
}
if(useTA$Volatility)  #  Volatility
{   strat = add.indicator(strategy=strat, name="volatility",
                arguments=list(OHLC=quote(OHLC(mktdata)), 
                n=voltPeriods, calc=voltCalc), label=volt)
}

# make some signal part indicators from previous indicators

# Simple and easy but very slow method:  var = "(val > 0)"
# More than 1000X faster: strat = sigThresh(strat, var, val, "gt", 0)

# input parameter order: (label) = (column)(relationship)(threshold)
sigThresh = function(straty, label, column, relationship, threshold)
{   return(add.signal(strategy=straty, name="sigThreshold",
        arguments = list(threshold=threshold, column=column,
        relationship=relationship, cross=FALSE), label=label))
}
# input parameter order:  (label) = (column1)(relationship)(column2)
sigCompare = function(straty, label, column1, relationship, column2)
{   return(add.signal(strategy=straty, name="sigComparison",
        arguments = list(columns=c(column1,column2),
        relationship=relationship, cross=FALSE), label=label))
}

closePr = paste(symbol,".Close",sep='')
# want to make these calls easily readable
# variables from indicatorLabels: ibs, smaFast, etc
if(useTA$IBS)
{   ibsUp = "ibsUp"; ibsDn = "ibsDn"  
    strat = sigThresh(strat, ibsUp, ibs, "gt", 0) # ibsUp = ibs > 0
    strat = sigThresh(strat, ibsDn, ibs, "lt", 0) # ibsDn = ibs < 0
}
if(useTA$SMA)
{   smaUp = "smaUp"; smaDn = "smaDn"
    strat = sigCompare(strat, smaUp, smaFast, "gt", smaSlow)
    strat = sigCompare(strat, smaDn, smaFast, "lt", smaSlow)
    closeAbvFst = "closeAbvFst";  closeBlwFst = "closeBlwFst"
    closeAbvSlw = "closeAbvSlw";  closeBlwSlw = "closeBlwSlw"
    strat = sigCompare(strat, closeAbvSlw, closePr, "gt", smaSlow)
    strat = sigCompare(strat, closeBlwSlw, closePr, "lt", smaSlow)
    strat = sigCompare(strat, closeAbvFst, closePr, "gt", smaFast)
    strat = sigCompare(strat, closeBlwFst, closePr, "lt", smaFast)
}

# paste parts together for entry/exit/long/short signal formulas

goLong = ""; exitLong = ""; goShort = ""; exitShort = ""

if(useTA$IBS & (numTAs == 1))  #   IBS only
{   goLong = ibsDn  #  counter-trend
    exitLong = ibsUp
    goShort = ibsUp
    exitShort = ibsDn
}
if(useTA$SMA & (numTAs == 1))  #   SMA only
{   goLong = paste(smaUp,"&",closeAbvFst,sep='')
    exitLong = paste(smaDn,"|",closeBlwFst,sep='')
    goShort = paste(smaDn,"&",closeBlwFst,sep='')
    exitShort = paste(smaUp,"|",closeAbvFst,sep='')
}
if(useTA$IBS & useTA$SMA & (numTAs == 2))   #  only IBS and SMA
{   goLong = paste(smaUp,"&",closeBlwFst,"&",ibsUp,sep='')
    exitLong = paste(smaDn,"|",closeBlwSlw,sep='')
    goShort = paste(smaDn,"&",closeAbvFst,"&",ibsDn,sep='')
    exitShort = paste(smaUp,"|",closeAbvSlw,sep='')
}

# when long/short signal rules are missing, just go long

goLongCross = TRUE  #  normal behavior
needSignals = (goLong == "")|(exitLong == "")|
            (goShort == "")|(exitShort == "") 
if(needSignals)
{   goLongCross = FALSE
    goLong = paste("(", closePr, " > 0.0)", sep='')
    exitLong = paste("(", closePr, " < 0.0)", sep='')
    goShort = paste("(", closePr, " < 0.0)", sep='')
    exitShort = paste("(", closePr, " < 0.0)", sep='')
}

# apply the sigFormulas and rules

strat = add.signal(strat, name="sigFormula", label="goLong",
            arguments=list(columns=indicatorLabels, 
            formula=goLong, cross=goLongCross))
strat = add.signal(strat, name="sigFormula", label="exitLong",
            arguments=list(columns=indicatorLabels, 
            formula=exitLong, cross=TRUE))
strat = add.signal(strat, name="sigFormula", label="goShort",
            arguments=list(columns=indicatorLabels, 
            formula=goShort, cross=TRUE))
strat = add.signal(strat, name="sigFormula", label="exitShort",
            arguments=list(columns=indicatorLabels, 
            formula=exitShort, cross=TRUE))

strat = add.rule(strategy = strat, name='ruleSignal', type='enter',
            arguments = list(sigcol="goLong", sigval=TRUE, 
            orderqty=orderSize, ordertype='market',
            osFUN=osMaxPos, orderside='long'))
strat = add.rule(strategy = strat, name='ruleSignal', type='exit',
            arguments = list(sigcol="exitLong", sigval=TRUE, 
            orderqty='all', ordertype='market', orderside='long'))
strat = add.rule(strategy = strat, name='ruleSignal', type='enter',
            arguments = list(sigcol="goShort", sigval=TRUE, 
            orderqty=-orderSize, ordertype='market',
            osFUN=osMaxPos, orderside='short'))
strat = add.rule(strategy = strat, name='ruleSignal', type='exit',
            arguments = list(sigcol="exitShort", sigval=TRUE, 
            orderqty='all', ordertype='market', orderside='short'))

addPosLimit(stratg, symbol, timestamp=initDate, 
                maxpos=orderSize, minpos=-orderSize)

out = applyStrategy(strategy=strat,portfolios=stratg,prefer='Open')
updatePortf(Portfolio=stratg)
updateAcct(name=stratg)

# make plots

chart.Posn(Portfolio = stratg, Symbol = symbol)
plot(add_TA(get(symbol)[,4], on=1, col='lightblue')) # closes

if(useTA$BBands)
{   plot(add_BBands(on=1,sd=bbSD,n=bbPeriods))
}
if(useTA$EMA)
{   plot(add_EMA(n=emaPeriods, on=1, col='orange'))
}
if(useTA$IBS)
{   plot(add_TA(IBS(hi=get(symbol)[,2],lo=get(symbol)[,3],
                cl=get(symbol)[,4], n=ibsPeriods)))
}
if(useTA$MACD) 
{   plot(add_MACD(fast=macdFast, slow=macdSlow, signal=macdSig, 
                  maType="EMA"))
}
if(useTA$RSI)
{   plot(add_RSI(n=rsiPeriods, maType="EMA"))
}
if(useTA$SMA)
{   plot(add_SMA(n=fastPeriods, on=1, col='magenta'))
    plot(add_SMA(n=slowPeriods, on=1, col='tan'))
    plot(add_TA(mktdata$smaUp))  # plot a column of mktdata by name
}
if(useTA$Volatility)  # plot a column by indicatorLabel variable
{   plot(add_TA(mktdata[,which(names(mktdata) == volt)]))
}

# write the results to files

if(writeResultFiles)
{   write.zoo(mktdata, quote=FALSE, 
                file=paste(stratg,"_",symbol,"_mktdata.csv", sep=''))
    write.zoo(getTxns(stratg, symbol), quote=FALSE, file= 
                paste(stratg, "_", symbol, "_txns.csv", sep=''))
    ob = getOrderBook(stratg)
    write.zoo(ob[[stratg]][[symbol]], quote=FALSE, file= 
                paste(stratg, "_", symbol, "_orderbook.csv",sep=''))
}




--
View this message in context: http://r.789695.n4.nabble.com/quantstrat-newbie-indicators-example-tp4662247.html
Sent from the Rmetrics mailing list archive at Nabble.com.



More information about the R-SIG-Finance mailing list