[Blotter-commits] r362 - pkg/quantstrat/demo

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Wed Jul 28 18:47:40 CEST 2010


Author: braverock
Date: 2010-07-28 18:47:39 +0200 (Wed, 28 Jul 2010)
New Revision: 362

Added:
   pkg/quantstrat/demo/bbands.R
   pkg/quantstrat/demo/macd.R
   pkg/quantstrat/demo/rsi.R
Removed:
   pkg/quantstrat/demo/BBands.R
   pkg/quantstrat/demo/MACD.R
   pkg/quantstrat/demo/RSI.R
Modified:
   pkg/quantstrat/demo/00Index
   pkg/quantstrat/demo/faber.R
Log:
- rename demos to not collide with TTR function names
- add example of stoplimit order rule to macd demo
- minor updates 

Modified: pkg/quantstrat/demo/00Index
===================================================================
--- pkg/quantstrat/demo/00Index	2010-07-27 14:06:38 UTC (rev 361)
+++ pkg/quantstrat/demo/00Index	2010-07-28 16:47:39 UTC (rev 362)
@@ -1,5 +1,5 @@
-BBands     Build a simple Bollinger Bands strategy using one indicator, three signals, and three trade rules
+bbands     Build a simple Bollinger Bands strategy using one indicator, three signals, and three trade rules
 faber      demonstrate a simple long term trend model using a 10-month SMA on a small portfolio of ETFs based on Mebane Faber paper
-MACD       example of Moving Average Convergence/Divergence used as a trend indicator
+macd       example of Moving Average Convergence/Divergence (MACD) used as a trend indicator
 maCross    classic 'Golden Cross' 50/200 period moving average cross strategy, long only, with long/short extra rules commented out
-RSI        Relative Strength Index (RSI) strategy demonstrating long-only threshold actions
+rsi        Relative Strength Index (RSI) strategy demonstrating long-only threshold actions

Deleted: pkg/quantstrat/demo/BBands.R
===================================================================
--- pkg/quantstrat/demo/BBands.R	2010-07-27 14:06:38 UTC (rev 361)
+++ pkg/quantstrat/demo/BBands.R	2010-07-28 16:47:39 UTC (rev 362)
@@ -1,73 +0,0 @@
-require(quantstrat)
-try(rm("order_book.bbands",pos=.strategy),silent=TRUE)
-try(rm("account.bbands","portfolio.bbands",pos=.blotter),silent=TRUE)
-try(rm("account.st","portfolio.st","stock.str","s","initDate","initEq",'start_t','end_t'),silent=TRUE)
-
-# some things to set up here
-stock.str='IBM' # what are we trying it on
-
-# we'll pass these 
-SD = 2 # how many standard deviations, traditionally 2
-N = 20 # how many periods for the moving average, traditionally 20
-
-
-currency('USD')
-stock(stock.str,currency='USD',multiplier=1)
-
-initDate='2006-12-31'
-initEq=1000000
-
-portfolio.st='bbands'
-account.st='bbands'
-
-initPortf(portfolio.st,symbols=stock.str, initDate=initDate)
-initAcct(account.st,portfolios='bbands', initDate=initDate)
-initOrders(portfolio=portfolio.st,initDate=initDate)
-
-s <- strategy("bbands")
-
-#one indicator
-s <- add.indicator(strategy = s, name = "BBands", arguments = list(HLC = quote(HLC(mktdata)), maType='SMA'))
-
-
-#if you wanted to manually apply a signal function for demonstration
-#cbind(IBM.mod,sigComparison(label="Close.gt.Open",data=IBM.inds,columns=c("Close","Open"),">"))
-#cbind(IBM.mod,sigComparison(label="Adjusted.gt.SMA",data=IBM.inds,columns=c("Adjusted","SMA10"),">"))
-
-#add signals:
-s<- add.signal(s,name="sigCrossover",arguments = list(data=quote(mktdata),columns=c("Close","up"),relationship="gt"),label="Cl.gt.UpperBand")
-s<- add.signal(s,name="sigCrossover",arguments = list(data=quote(mktdata),columns=c("Close","dn"),relationship="lt"),label="Cl.lt.LowerBand")
-s<- add.signal(s,name="sigCrossover",arguments = list(data=quote(mktdata),columns=c("High","Low","mavg"),relationship="op"),label="Cross.Mid")
-
-# lets add some rules
-s 
-s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Cl.gt.UpperBand",sigval=TRUE, orderqty=-100, ordertype='market', orderside=NULL, threshold=NULL),type='enter')
-s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Cl.lt.LowerBand",sigval=TRUE, orderqty= 100, ordertype='market', orderside=NULL, threshold=NULL),type='enter')
-s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Cross.Mid",sigval=TRUE, orderqty= 'all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
-#s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Lo.gt.UpperBand",sigval=TRUE, orderqty= 'all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
-#s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Hi.lt.LowerBand",sigval=TRUE, orderqty= 'all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
-#TODO add thresholds and stop-entry and stop-exit handling to test
-
-getSymbols(stock.str,from=initDate)
-start_t<-Sys.time()
-out<-try(applyStrategy(strategy='s' , portfolios='bbands',parameters=list(sd=SD,n=N)))
-
-# look at the order book
-#getOrderBook('bbands')
-end_t<-Sys.time()
-end_t-start_t
-updatePortf(Portfolio='bbands',Dates=paste('::',as.Date(Sys.time()),sep=''))
-chart.Posn(Portfolio='bbands',Symbol=stock.str)
-plot(add_BBands(on=1,sd=SD,n=N))
-###############################################################################
-# R (http://r-project.org/) Quantitative Strategy Model Framework
-#
-# Copyright (c) 2009-2010
-# 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$
-#
-###############################################################################

Deleted: pkg/quantstrat/demo/MACD.R
===================================================================
--- pkg/quantstrat/demo/MACD.R	2010-07-27 14:06:38 UTC (rev 361)
+++ pkg/quantstrat/demo/MACD.R	2010-07-28 16:47:39 UTC (rev 362)
@@ -1,58 +0,0 @@
-# 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)
-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","s","initDate","initEq",'start_t','end_t'),silent=TRUE)
-
-stock.str='IBM' # 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)
-
-initDate='2006-12-31'
-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)
-
-
-stratMACD <- strategy(portfolio.st)
-
-stratMACD <- add.indicator(strategy = stratMACD, name = "MACD", arguments = list(x=quote(Cl(mktdata))) )
-
-stratMACD <- add.signal(strategy = stratMACD,name="sigThreshold",arguments = list(data=quote(mktdata),column="signal",relationship="gt",threshold=0,cross=TRUE),label="signal.gt.zero")
-stratMACD <- add.signal(strategy = stratMACD,name="sigThreshold",arguments = list(data=quote(mktdata),column="signal",relationship="lt",threshold=0,cross=TRUE),label="signal.lt.zero")
-
-stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="signal.gt.zero",sigval=TRUE, orderqty=100, ordertype='market', orderside=NULL, threshold=NULL),type='enter')
-stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="signal.lt.zero",sigval=TRUE, orderqty='all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
-
-getSymbols(stock.str,from=initDate)
-start_t<-Sys.time()
-out<-try(applyStrategy(strategy=stratMACD , portfolios=portfolio.st,parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType)))
-end_t<-Sys.time()
-end_t-start_t
-updatePortf(Portfolio='macd',Dates=paste('::',as.Date(Sys.time()),sep=''))
-chart.Posn(Portfolio='macd',Symbol=stock.str)
-plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA"))
-
-

Deleted: pkg/quantstrat/demo/RSI.R
===================================================================
--- pkg/quantstrat/demo/RSI.R	2010-07-27 14:06:38 UTC (rev 361)
+++ pkg/quantstrat/demo/RSI.R	2010-07-28 16:47:39 UTC (rev 362)
@@ -1,76 +0,0 @@
-# Initialize a strategy object
-stratRSI <- strategy("RSI")
-
-# Add an indicator
-stratRSI <- add.indicator(strategy = stratRSI, name = "RSI", arguments = list(price = quote(getPrice(mktdata)), n=2), label="RSI")
-
-# There are two signals:
-# The first is when RSI is greater than 90
-stratRSI <- add.signal(strategy = stratRSI, name="sigThreshold",arguments = list(data=quote(mktdata),threshold=90, column="RSI",relationship="gt", cross=TRUE),label="RSI.gt.90")
-# The second is when RSI is less than 10
-stratRSI <- add.signal(strategy = stratRSI, name="sigThreshold",arguments = list(data=quote(mktdata),threshold=10, column="RSI",relationship="lt",cross=TRUE),label="RSI.lt.10")
-
-# There are two rules:
-#'## we would Use osMaxPos to put trade on in layers, or to a maximum position. 
-# The first is to sell when the RSI crosses above the threshold
-stratRSI <- add.rule(strategy = stratRSI, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="RSI.gt.90", sigval=TRUE, orderqty=-1000, ordertype='market', orderside='short', pricemethod='market'), type='enter', path.dep=TRUE)
-stratRSI <- add.rule(strategy = stratRSI, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="RSI.lt.10", sigval=TRUE, orderqty='all', ordertype='market', orderside='short', pricemethod='market'), type='exit', path.dep=TRUE)
-# The second is to buy when the RSI crosses below the threshold
-stratRSI <- add.rule(strategy = stratRSI, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="RSI.lt.10", sigval=TRUE, orderqty= 1000, ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE)
-stratRSI <- add.rule(strategy = stratRSI, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="RSI.gt.90", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE)
-
-#add changeable parameters
-# add level in/out
-
-# add trailing entry
-
-# add trailing exit?
-
-currency("USD")
-currency("EUR")
-symbols = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
-for(symbol in symbols){ # establish trade-able instruments
-    stock(symbol, currency="USD",multiplier=1)
-}
-
-
-# you can test with something like this:
-# applySignals(strategy=stratRSI, mktdata=applyIndicators(strategy=stratRSI, mktdata=symbols[1]))
-
-
-initDate='2009-02-06'
-initEq=100000
-port.st<-'RSISPX' #use a string here for easier changing of parameters and re-trying
-
-initPortf(port.st, symbols=symbols, initDate=initDate)
-initAcct(port.st, portfolios=port.st, initDate=initDate)
-initOrders(portfolio=port.st, initDate=initDate)
-
-print("setup completed")
-
-# Process the indicators and generate trades
-portfolios=c("RSISPX","RSIGDAXI","RSIboth")
-start_t<-Sys.time()
-out<-try(applyStrategy(strategy=stratRSI , portfolios=c(port.st)))
-end_t<-Sys.time()
-print("Strategy Loop:")
-print(end_t-start_t)
-
-# look at the order book
-#print(getOrderBook(port.st))
-
-start_t<-Sys.time()
-updatePortf(Portfolio=port.st,Dates=paste('::',as.Date(Sys.time()),sep=''))
-end_t<-Sys.time()
-print("trade blotter portfolio update:")
-print(end_t-start_t)
-
-# hack for new quantmod graphics, remove later
-themelist<-chart_theme()
-themelist$up.col<-'lightgreen'
-themelist$down.col<-'pink'
-for(symbol in symbols){
-    dev.new()
-    chart.Posn(Portfolio=port.st,Symbol=symbol,theme=themelist)
-    plot(add_RSI(n=2))
-}

Copied: pkg/quantstrat/demo/bbands.R (from rev 360, pkg/quantstrat/demo/BBands.R)
===================================================================
--- pkg/quantstrat/demo/bbands.R	                        (rev 0)
+++ pkg/quantstrat/demo/bbands.R	2010-07-28 16:47:39 UTC (rev 362)
@@ -0,0 +1,73 @@
+require(quantstrat)
+try(rm("order_book.bbands",pos=.strategy),silent=TRUE)
+try(rm("account.bbands","portfolio.bbands",pos=.blotter),silent=TRUE)
+try(rm("account.st","portfolio.st","stock.str","s","initDate","initEq",'start_t','end_t'),silent=TRUE)
+
+# some things to set up here
+stock.str='IBM' # what are we trying it on
+
+# we'll pass these 
+SD = 2 # how many standard deviations, traditionally 2
+N = 20 # how many periods for the moving average, traditionally 20
+
+
+currency('USD')
+stock(stock.str,currency='USD',multiplier=1)
+
+initDate='2006-12-31'
+initEq=1000000
+
+portfolio.st='bbands'
+account.st='bbands'
+
+initPortf(portfolio.st,symbols=stock.str, initDate=initDate)
+initAcct(account.st,portfolios='bbands', initDate=initDate)
+initOrders(portfolio=portfolio.st,initDate=initDate)
+
+s <- strategy("bbands")
+
+#one indicator
+s <- add.indicator(strategy = s, name = "BBands", arguments = list(HLC = quote(HLC(mktdata)), maType='SMA'))
+
+
+#if you wanted to manually apply a signal function for demonstration
+#cbind(IBM.mod,sigComparison(label="Close.gt.Open",data=IBM.inds,columns=c("Close","Open"),">"))
+#cbind(IBM.mod,sigComparison(label="Adjusted.gt.SMA",data=IBM.inds,columns=c("Adjusted","SMA10"),">"))
+
+#add signals:
+s<- add.signal(s,name="sigCrossover",arguments = list(data=quote(mktdata),columns=c("Close","up"),relationship="gt"),label="Cl.gt.UpperBand")
+s<- add.signal(s,name="sigCrossover",arguments = list(data=quote(mktdata),columns=c("Close","dn"),relationship="lt"),label="Cl.lt.LowerBand")
+s<- add.signal(s,name="sigCrossover",arguments = list(data=quote(mktdata),columns=c("High","Low","mavg"),relationship="op"),label="Cross.Mid")
+
+# lets add some rules
+s 
+s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Cl.gt.UpperBand",sigval=TRUE, orderqty=-100, ordertype='market', orderside=NULL, threshold=NULL),type='enter')
+s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Cl.lt.LowerBand",sigval=TRUE, orderqty= 100, ordertype='market', orderside=NULL, threshold=NULL),type='enter')
+s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Cross.Mid",sigval=TRUE, orderqty= 'all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
+#s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Lo.gt.UpperBand",sigval=TRUE, orderqty= 'all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
+#s <- add.rule(s,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="Hi.lt.LowerBand",sigval=TRUE, orderqty= 'all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
+#TODO add thresholds and stop-entry and stop-exit handling to test
+
+getSymbols(stock.str,from=initDate)
+start_t<-Sys.time()
+out<-try(applyStrategy(strategy='s' , portfolios='bbands',parameters=list(sd=SD,n=N)) )
+
+# look at the order book
+#getOrderBook('bbands')
+end_t<-Sys.time()
+end_t-start_t
+updatePortf(Portfolio='bbands',Dates=paste('::',as.Date(Sys.time()),sep=''))
+chart.Posn(Portfolio='bbands',Symbol=stock.str)
+plot(add_BBands(on=1,sd=SD,n=N))
+###############################################################################
+# R (http://r-project.org/) Quantitative Strategy Model Framework
+#
+# Copyright (c) 2009-2010
+# 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$
+#
+###############################################################################

Modified: pkg/quantstrat/demo/faber.R
===================================================================
--- pkg/quantstrat/demo/faber.R	2010-07-27 14:06:38 UTC (rev 361)
+++ pkg/quantstrat/demo/faber.R	2010-07-28 16:47:39 UTC (rev 362)
@@ -46,9 +46,9 @@
 require(quantstrat)
 
 # Try to clean up in case the demo was run previously
-try(rm("account.longtrend","portfolio.longtrend",pos=.blotter),silent=TRUE)
+try(rm("account.faber","portfolio.faber",pos=.blotter),silent=TRUE)
 try(rm("ltaccount","ltportfolio","ClosePrice","CurrentDate","equity","GSPC","i","initDate","initEq","Posn","UnitSize","verbose"),silent=TRUE)
-try(rm("order_book.longtrend",pos=.strategy),silent=TRUE)
+try(rm("order_book.faber",pos=.strategy),silent=TRUE)
 
 # Set initial values
 initDate='1997-12-31'
@@ -75,14 +75,14 @@
 }
 
 # Initialize portfolio and account
-initPortf('longtrend', symbols=symbols, initDate=initDate)
-initAcct('longtrend', portfolios='longtrend', initDate=initDate)
-initOrders(portfolio='longtrend', initDate=initDate)
+initPortf('faber', symbols=symbols, initDate=initDate)
+initAcct('faber', portfolios='faber', initDate=initDate)
+initOrders(portfolio='faber', initDate=initDate)
 
 print("setup completed")
 
 # Initialize a strategy object
-s <- strategy("longtrend")
+s <- strategy("faber")
 
 # Add an indicator
 s <- add.indicator(strategy = s, name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
@@ -101,16 +101,16 @@
 
 # Process the indicators and generate trades
 start_t<-Sys.time()
-out<-try(applyStrategy(strategy='s' , portfolios='longtrend'))
+out<-try(applyStrategy(strategy='s' , portfolios='faber'))
 end_t<-Sys.time()
 print("Strategy Loop:")
 print(end_t-start_t)
 
 # look at the order book
-#print(getOrderBook('longtrend'))
+#print(getOrderBook('faber'))
 
 start_t<-Sys.time()
-updatePortf(Portfolio='longtrend',Dates=paste('::',as.Date(Sys.time()),sep=''))
+updatePortf(Portfolio='faber',Dates=paste('::',as.Date(Sys.time()),sep=''))
 end_t<-Sys.time()
 print("trade blotter portfolio update:")
 print(end_t-start_t)
@@ -121,7 +121,7 @@
 themelist$down.col<-'pink'
 for(symbol in symbols){
     dev.new()
-    chart.Posn(Portfolio='longtrend',Symbol=symbol,theme=themelist)
+    chart.Posn(Portfolio='faber',Symbol=symbol,theme=themelist)
     plot(add_SMA(n=10,col='darkgreen', on=1))
 }
 

Copied: pkg/quantstrat/demo/macd.R (from rev 361, pkg/quantstrat/demo/MACD.R)
===================================================================
--- pkg/quantstrat/demo/macd.R	                        (rev 0)
+++ pkg/quantstrat/demo/macd.R	2010-07-28 16:47:39 UTC (rev 362)
@@ -0,0 +1,59 @@
+# 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)
+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","s","initDate","initEq",'start_t','end_t'),silent=TRUE)
+
+stock.str='AAPL' # 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)
+
+initDate='2006-12-31'
+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)
+
+
+stratMACD <- strategy(portfolio.st)
+
+stratMACD <- add.indicator(strategy = stratMACD, name = "MACD", arguments = list(x=quote(Cl(mktdata))) )
+
+stratMACD <- add.signal(strategy = stratMACD,name="sigThreshold",arguments = list(data=quote(mktdata),column="signal",relationship="gt",threshold=0,cross=TRUE),label="signal.gt.zero")
+stratMACD <- add.signal(strategy = stratMACD,name="sigThreshold",arguments = list(data=quote(mktdata),column="signal",relationship="lt",threshold=0,cross=TRUE),label="signal.lt.zero")
+
+stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="signal.gt.zero",sigval=TRUE, orderqty=100, ordertype='market', orderside='long', threshold=NULL),type='enter')
+stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="signal.gt.zero",sigval=TRUE, orderqty=-100, ordertype='stoplimit', orderside='long', threshold=.95,tmult=TRUE),type='risk')
+stratMACD <- add.rule(strategy = stratMACD,name='ruleSignal', arguments = list(data=quote(mktdata),sigcol="signal.lt.zero",sigval=TRUE, orderqty='all', ordertype='market', orderside='long', threshold=NULL),type='exit')
+
+getSymbols(stock.str,from=initDate)
+start_t<-Sys.time()
+out<-try(applyStrategy(strategy=stratMACD , portfolios=portfolio.st,parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType)))
+end_t<-Sys.time()
+end_t-start_t
+updatePortf(Portfolio='macd',Dates=paste('::',as.Date(Sys.time()),sep=''))
+chart.Posn(Portfolio='macd',Symbol=stock.str)
+plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA"))
+
+

Copied: pkg/quantstrat/demo/rsi.R (from rev 358, pkg/quantstrat/demo/RSI.R)
===================================================================
--- pkg/quantstrat/demo/rsi.R	                        (rev 0)
+++ pkg/quantstrat/demo/rsi.R	2010-07-28 16:47:39 UTC (rev 362)
@@ -0,0 +1,76 @@
+# Initialize a strategy object
+stratRSI <- strategy("RSI")
+
+# Add an indicator
+stratRSI <- add.indicator(strategy = stratRSI, name = "RSI", arguments = list(price = quote(getPrice(mktdata))), label="RSI")
+
+# There are two signals:
+# The first is when RSI is greater than 90
+stratRSI <- add.signal(strategy = stratRSI, name="sigThreshold",arguments = list(data=quote(mktdata),threshold=90, column="RSI",relationship="gt", cross=TRUE),label="RSI.gt.90")
+# The second is when RSI is less than 10
+stratRSI <- add.signal(strategy = stratRSI, name="sigThreshold",arguments = list(data=quote(mktdata),threshold=10, column="RSI",relationship="lt",cross=TRUE),label="RSI.lt.10")
+
+# There are two rules:
+#'## we would Use osMaxPos to put trade on in layers, or to a maximum position. 
+# The first is to sell when the RSI crosses above the threshold
+stratRSI <- add.rule(strategy = stratRSI, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="RSI.gt.90", sigval=TRUE, orderqty=-1000, ordertype='market', orderside='short', pricemethod='market'), type='enter', path.dep=TRUE)
+stratRSI <- add.rule(strategy = stratRSI, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="RSI.lt.10", sigval=TRUE, orderqty='all', ordertype='market', orderside='short', pricemethod='market'), type='exit', path.dep=TRUE)
+# The second is to buy when the RSI crosses below the threshold
+stratRSI <- add.rule(strategy = stratRSI, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="RSI.lt.10", sigval=TRUE, orderqty= 1000, ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE)
+stratRSI <- add.rule(strategy = stratRSI, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="RSI.gt.90", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE)
+
+#add changeable parameters
+# add level in/out
+
+# add trailing entry
+
+# add trailing exit?
+
+currency("USD")
+currency("EUR")
+symbols = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
+for(symbol in symbols){ # establish trade-able instruments
+    stock(symbol, currency="USD",multiplier=1)
+}
+
+
+# you can test with something like this:
+# applySignals(strategy=stratRSI, mktdata=applyIndicators(strategy=stratRSI, mktdata=symbols[1]))
+
+
+initDate='2009-02-06'
+initEq=100000
+port.st<-'RSISPX' #use a string here for easier changing of parameters and re-trying
+
+initPortf(port.st, symbols=symbols, initDate=initDate)
+initAcct(port.st, portfolios=port.st, initDate=initDate)
+initOrders(portfolio=port.st, initDate=initDate)
+
+print("setup completed")
+
+# Process the indicators and generate trades
+portfolios=c("RSISPX","RSIGDAXI","RSIboth")
+start_t<-Sys.time()
+out<-try(applyStrategy(strategy=stratRSI , portfolios=c(port.st),parameters=list(n=2) ) )
+end_t<-Sys.time()
+print("Strategy Loop:")
+print(end_t-start_t)
+
+# look at the order book
+#print(getOrderBook(port.st))
+
+start_t<-Sys.time()
+updatePortf(Portfolio=port.st,Dates=paste('::',as.Date(Sys.time()),sep=''))
+end_t<-Sys.time()
+print("trade blotter portfolio update:")
+print(end_t-start_t)
+
+# hack for new quantmod graphics, remove later
+themelist<-chart_theme()
+themelist$up.col<-'lightgreen'
+themelist$down.col<-'pink'
+for(symbol in symbols){
+    dev.new()
+    chart.Posn(Portfolio=port.st,Symbol=symbol,theme=themelist)
+    plot(add_RSI(n=2))
+}



More information about the Blotter-commits mailing list