###################################################################################### # This script tries to implement a stop loss on a closing price basis. # Rules: # BTO: when MACD crosses threshold of zero from below # STC: when MACD crosses threshold of zero from above # Stop Loss: If on any day the closing price is less than the BTO*(1-X), exit at market # on open the next day where X is the loss tolerable ###################################################################################### # libraries########################################################################### require(quantstrat) # remove old parameters ############################################################## try(rm("order_book.macd",pos=.strategy),silent=TRUE) try(rm("account.macd","portfolio.macd",pos=.blotter),silent=TRUE) try(rm("account.st","portfolio.st","stock.str","stratMACD","initDate","initEq",'start_t','end_t'),silent=TRUE) # settingup quantstrat ############################################################## stock.str='AAPL' currency('USD') stock(stock.str,currency='USD',multiplier=1) initDate<-'2009-12-31' initEq=1000000 portfolio.st<-'macd' account.st<-'macd' strat.name <- 'stratMACD' initPortf(portfolio.st,symbols=stock.str, initDate=initDate) initAcct(account.st,portfolios=portfolio.st, initDate=initDate) initOrders(portfolio=portfolio.st,initDate=initDate) strategy(strat.name,store = TRUE) # System parameters ################################################################## fastMA <- 12 slowMA <- 26 signalMA <- 9 maType <-"EMA" slpercent <-0.05 # Get Data ########################################################################### getSymbols(stock.str,from=initDate) # Custom Indicator Function ######################################################### # This is a function to create an indicator that is path dependent. # This function looks at the MACD signal that triggers an entry trade and then creates the appropriate stop loss # level for that entry. This will be used to create a signal SLPX<-function(OHLC,slpercent){ slpx<-rep(NA, times = nrow(OHLC)) # create the output vector and fill with NA OHLC$longlag<-lag(OHLC$signal.gt.zero.x,n=1) #lag the BTO signal by 1 bar as position taken the next day for (counter in (1:nrow(OHLC))){ slpx[counter] if (!is.na(OHLC[counter]$longlag)) { # do nothing if the signal is an NA value if(OHLC[counter]$longlag==1) { slpx[counter] = Op(OHLC[counter])*(1-slpercent) # if signal is 1, then figure out operating stop loss } else { slpx[counter] = slpx[counter-1] # is signal is zero then carry forward previously calculated value } } } return(slpx) } # Add Indicator MACD ############################################################### add.indicator(strategy = strat.name, name = "MACD", arguments = list(x = quote(Cl(mktdata)), nFast=fastMA, nSlow = maSlow, nSig = signalMA, maType=maType) ) # Add BTO Signal ###################################################################### add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "gt", threshold = 0, cross = TRUE ), label = "signal.gt.zero.x" ) # Add STC Signal ###################################################################### add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "lt", threshold = 0, cross = TRUE ), label = "signal.lt.zero.x" ) # Add signal that indicates whether there is a position due to BTO signal add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "gt", threshold = 0, cross = FALSE ), label = "signal.gt.zero.pos" ) # Lag the above signal by 1 bar as long position gets taken the next bar ############ add.indicator (strategy = strat.name, name = "lag", arguments = (list(x=quote(mktdata$signal.gt.zero.pos), n=1)), label = "longpos" ) # Add SLPX Indicator ################################################################ add.indicator( strategy = strat.name, name = "SLPX", arguments = (list(OHLC=quote(mktdata), slpercent = 0.05)), label = "SLPX") # Add signal to check whether Close on any day is less that the stop loss level from # the indicator SLPX ############################################################### add.signal(strategy = strat.name, name = "sigComparison", arguments = list(columns=c(quote(Cl(mktdata)),"SLPX")), label = "SLCondition") # Check whether longpos and SL condition are met simultaneously ##################### add.signal( strategy = strat.name, name = "sigFormula", arguments = list(formula = "longpos & SLCondition", cross = TRUE), label = "SLTrigger" ) # Add BTO Rule ####################################################################### add.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "signal.gt.zero.x", sigval = TRUE, orderqty = 100, prefer = "Open", replace = TRUE, ordertype = 'market', orderside = 'long', threshold = NULL ), type= "enter", label = "enterlong" ) # Add STC Rule ####################################################################### add.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "signal.lt.zero.x", sigval = TRUE, orderqty = 'all', prefer = "Open", replace = FALSE, ordertype = 'market', orderside = 'long', threshold = NULL, orderset = 'ocolong' ), type= "exit", label = "exitlong" ) # Add Stop Loss Rule [part of orderset 'ocolong'] ############################## add.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "SLTrigger", sigval = TRUE, orderqty = 'all', prefer = "Open", replace = FALSE, ordertype = 'market', orderside = 'long', threshold = NULL, orderset = 'ocolong' ), type= "exit", label = "SL") #Apply Strategy ####################################################################### applyStrategy(strategy=strat.name , portfolios=portfolio.st) # Updates ############################################################################# updatePortf(Portfolio=portfolio.st,Dates=paste('::',as.Date(Sys.time()),sep='')) # Outputs ############################################################################ chart.Posn(Portfolio=portfolio.st,Symbol=stock.str) plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA")) print ('order book') getOrderBook(portfolio.st) print('transactions') getTxns(Portfolio=portfolio.st, Symbol=stock.str)