require(quantstrat) require(quantmod) require(blotter) Sys.setenv(TZ="UTC") # Setup strategyName = "MACD" portfolioName = "MACD" accountName = "MACD" symbol = "SPY" symbolFile = "SPY.bin" initDate = "1993-01-01" endDate = "2012-12-31" initEq = 100000 orderQty = initEq # verbose = FALSE verbose = TRUE suppressWarnings( rm("order_book.MACD", pos=.strategy) ) suppressWarnings( rm("account.MACD", "portfolio.MACD", pos=.blotter) ) # Define the strategy strategy( strategyName, store=TRUE ) # One indicator add.indicator( strategyName, name="MACD", label="MACD", arguments=list(x=quote(Cl(mktdata)), nFast=1, nSlow=10, maType="SMA") ) # Two signals add.signal( strategyName, name="sigThreshold", arguments=list(column="macd", relationship="gte", threshold=0, cross=TRUE), label="macd.gte.zero" ) add.signal( strategyName, name="sigThreshold", arguments=list(column="macd", relationship="lt", threshold=0, cross=TRUE), label="macd.lt.zero" ) # Entry add.rule( strategyName, name='ruleSignal', arguments=list(sigcol="macd.gte.zero", sigval=TRUE, orderqty=1000, ordertype='market', pricemethod='market', orderside='long'), type='enter', label='enter.long') # Exit add.rule( strategyName, name='ruleSignal', arguments=list(sigcol="macd.lt.zero", sigval=TRUE, orderqty='all', ordertype='market', pricemethod='market', orderside='long'), type='exit', label='exit.long') currency( "USD" ) stock( symbol, currency="USD", multiplier=1 ) load( file=symbolFile ) ss = get( symbol ) ss = to.monthly( ss, indexAt="lastOf", drop.time=TRUE ) indexFormat( ss ) = "%Y-%m-%d" colnames( ss ) = gsub( "ss", symbol, colnames(ss) ) assign( symbol, ss ) SPY = SPY[paste("/", endDate, sep="")] # Portfolio, account and order book initPortf( portfolioName, symbols=symbol, initDate=initDate ) initAcct( accountName, portfolios=portfolioName, initDate=initDate, initEq=initEq ) initOrders( portfolio=portfolioName, initDate=initDate ) out = try( applyStrategy(strategy=strategyName, portfolios=portfolioName) ) updatePortf( portfolioName, Symbols=symbol, Dates=paste("/", as.Date(Sys.time()), sep="") ) updateAcct( portfolioName ) print( paste( "Net Trading PnL: ", as.numeric( tradeStats( portfolioName, symbol )$Net.Trading.PL ), sep="" ) )