# Simple MACD strategy # # MACD may be used in many ways, this will demonstrate a trend indicator. # # traditionally, when the MACD signal crosses zero, this indicated a establishment of a positive trend # # we'll buy on positive treshold crossover of the 'signal' column, and sell on negative threshold crossover # # Author: brian ############################################################################### require(quantstrat) suppressWarnings(rm("order_book.macd",pos=.strategy)) suppressWarnings(rm("account.macd","portfolio.macd",pos=.blotter)) suppressWarnings(rm("account.st","portfolio.st","stock.str","stratMACD","initDate","initEq",'start_t','end_t')) #correct for TZ issues if they crop up oldtz<-Sys.getenv('TZ') if(oldtz=='') { Sys.setenv(TZ="GMT") } stock.str='GE' # what are we trying it on #MA parameters for MACD fastMA = 12 slowMA = 26 signalMA = 9 maType="EMA" currency('USD') stock(stock.str,currency='USD',multiplier=1) #or use fake data #stock.str='sample_matrix' # what are we trying it on #data(sample_matrix) # data included in package xts #sample_matrix<-as.xts(sample_matrix) ##### PLACE DEMO AND TEST DATES HERE ################# # #if(isTRUE(options('in_test')$in_test)) # # use test dates # {initDate="2011-01-01" # endDate="2012-12-31" # } else # # use demo defaults # {initDate="1999-12-31" # endDate=Sys.Date()} initDate='2014-01-01' endDate='2014-07-04' initEq=1000000 portfolio.st='macd' account.st='macd' initPortf(portfolio.st,symbols=stock.str, initDate=initDate) initAcct(account.st,portfolios=portfolio.st, initDate=initDate) initOrders(portfolio=portfolio.st,initDate=initDate) strat.st<-portfolio.st # define the strategy strategy(strat.st, store=TRUE) #one indicator add.indicator(strat.st, name = "MACD", arguments = list(x=quote(Cl(mktdata))), label='_' ) #two signals add.signal(strat.st,name="sigThreshold", arguments = list(column="signal._", relationship="gt", threshold=0, cross=TRUE), label="signal.gt.zero" ) add.signal(strat.st,name="sigThreshold", arguments = list(column="signal._", relationship="lt", threshold=0, cross=TRUE), label="signal.lt.zero" ) #### # add rules # entry add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero", sigval=TRUE, orderqty=100, ordertype='market', orderside='long', threshold=NULL), type='enter', label='enter', storefun=FALSE ) #alternatives for risk stops: # simple stoplimit order, with threshold multiplier #add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty='all', ordertype='stoplimit', orderside='long', threshold=-.05,tmult=TRUE, orderset='exit2'),type='chain', parent='enter', label='risk',storefun=FALSE) # alternately, use a trailing order, also with a threshold multiplier add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty='all', ordertype='stoptrailing', orderside='long', threshold=1,tmult=FALSE, orderset='exit2'), type='chain', parent='enter', label='trailingexit') # exit add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.lt.zero", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', threshold=NULL, orderset='exit2'), type='exit', label='exit' ) #end rules #### getSymbols(stock.str,from=initDate,to=endDate) start_t<-Sys.time() out<-applyStrategy(strat.st , portfolios=portfolio.st,parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType),verbose=TRUE) end_t<-Sys.time() print(end_t-start_t) start_t<-Sys.time() updatePortf(Portfolio=portfolio.st,Dates=paste('::',as.Date(Sys.time()),sep='')) end_t<-Sys.time() print("trade blotter portfolio update:") print(end_t-start_t) #look at the order book obook<-getOrderBook('macd') # Create the chart enhancements. This only works when there is just one symbol in # the portfolio, and just one trade in the data (initDate/endDate). # Construct the subset for when the trade was active, plus some extra bars. ## ss='2014-04-02/2014-06-26' ss=paste( index(obook[[1]][[1]])[1] - 1, "/", as.Date(as.vector(last( obook[[1]][[1]][,'Order.StatusTime']))) + 1, sep="") # Construct the set of subsets where new highs have been established and are in control. startSS = index(obook[[1]][[1]]) endSS = as.vector(obook[[1]][[1]][,'Order.StatusTime']) allSS = paste(startSS, "/", endSS, sep="") # Create the Entry Price Line. It's a few days too wide, but that's ok. ep = Cl(mktdata) names(ep) = 'entryPrice' ep[,1] = NA ep[ss,1] = 26.23 # Create the High Price Line hp = Cl(mktdata) names(hp) = 'highPrice' hp[,1] = NA # Create the Trailing Price Line tp = Cl(mktdata) names(tp) = 'trailingPrice' tp[,1] = NA # Loop over the Order Book "events" (subsets) and fill in High Price and Trailing Price objects for(i in 1:length(startSS)) { hiSoFar = as.vector(Hi(mktdata[startSS[i]])) hp[allSS[i],1] = hiSoFar tp[allSS[i],1] = hiSoFar - 1 } # Create the TA parameter for chart.Posn() and chart_Series() too ta = paste( "add_TA(x=ep, on=1, col='blue', lwd=1)", "add_TA(x=hp, on=1, col='green', lwd=1)", "add_TA(x=tp, on=1, col='red', lwd=1)", sep=";" ) #jpeg(file = "~/Macd-TrailingStop-Annotated.jpeg", width=1920, height=1080) chart.Posn(Portfolio=portfolio.st,Symbol=stock.str,Dates=ss, TA=ta) plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA")) #dev.off() # set tz as it was before the demo Sys.setenv(TZ=oldtz) ############################################################################### # R (http://r-project.org/) Quantitative Strategy Model Framework # # Copyright (c) 2009-2012 # Peter Carl, Dirk Eddelbuettel, Brian G. Peterson, Jeffrey Ryan, and Joshua Ulrich # # This library is distributed under the terms of the GNU Public License (GPL) # for full details see the file COPYING # # $Id: macd.R 1614 2014-06-04 14:40:03Z efmrforge $ # ############################################################################## ##### PLACE THIS BLOCK AT END OF DEMO SCRIPT ################### # book = getOrderBook(port) # stats = tradeStats(port) # rets = PortfReturns(acct) ################################################################