SCM

SCM Repository

[blotter] Diff of /pkg/quantstrat/demo/faber.R
ViewVC logotype

Diff of /pkg/quantstrat/demo/faber.R

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 450, Sat Nov 13 18:30:40 2010 UTC revision 1370, Thu Jan 17 20:58:10 2013 UTC
# Line 46  Line 46 
46  require(quantstrat)  require(quantstrat)
47    
48  # Try to clean up in case the demo was run previously  # Try to clean up in case the demo was run previously
49  try(rm("account.faber","portfolio.faber",pos=.blotter),silent=TRUE)  suppressWarnings(rm("account.faber","portfolio.faber",pos=.blotter))
50  try(rm("ltaccount","ltportfolio","ClosePrice","CurrentDate","equity","GSPC","stratFaber","initDate","initEq","Posn","UnitSize","verbose"),silent=TRUE)  suppressWarnings(rm("ltaccount", "ltportfolio", "ClosePrice", "CurrentDate", "equity",
51  try(rm("order_book.faber",pos=.strategy),silent=TRUE)              "GSPC", "stratFaber", "initDate", "initEq", "Posn", "UnitSize", "verbose"))
52    suppressWarnings(rm("order_book.faber",pos=.strategy))
53    
54    ##### PLACE THIS BLOCK AHEAD OF DATE INITS IN DEMO SCRIPT ######
55    # if(!exists('in_test') || !isTRUE(in_test)){
56    #     initDate='2005-12-31' # ensure this is demo default
57    #     endDate=Sys.Date()    # ensure this is demo default
58    # }
59    ################################################################
60    
61  # Set initial values  # Set initial values
62  initDate='1997-12-31'  initDate='1997-12-31'
# Line 76  Line 84 
84    
85  # Initialize portfolio and account  # Initialize portfolio and account
86  initPortf('faber', symbols=symbols, initDate=initDate)  initPortf('faber', symbols=symbols, initDate=initDate)
87  initAcct('faber', portfolios='faber', initDate=initDate)  initAcct('faber', portfolios='faber', initDate=initDate, initEq=100000)
88  initOrders(portfolio='faber', initDate=initDate)  initOrders(portfolio='faber', initDate=initDate)
89    
90  print("setup completed")  print("setup completed")
91    
92  # Initialize a strategy object  # Initialize a strategy object
93  stratFaber <- strategy("faber")  strategy("faber", store=TRUE)
94    
95  # Add an indicator  # Add an indicator
96  stratFaber <- add.indicator(strategy = stratFaber, name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")  add.indicator('faber', name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
97    
98  # There are two signals:  # There are two signals:
99  # The first is when monthly price crosses over the 10-month SMA  # The first is when monthly price crosses over the 10-month SMA
100  stratFaber <- add.signal(stratFaber,name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="gt"),label="Cl.gt.SMA")  add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="gte"),label="Cl.gt.SMA")
101  # The second is when the monthly price crosses under the 10-month SMA  # The second is when the monthly price crosses under the 10-month SMA
102  stratFaber <- add.signal(stratFaber,name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")  add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")
103    
104  # There are two rules:  # There are two rules:
105  # The first is to buy when the price crosses above the SMA  # The first is to buy when the price crosses above the SMA
106  stratFaber <- add.rule(stratFaber, name='ruleSignal', arguments = list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=1000, ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE)  add.rule('faber', name='ruleSignal', arguments = list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=500, ordertype='market', orderside='long', pricemethod='market',TxnFees=-5), type='enter', path.dep=TRUE)
107  # The second is to sell when the price crosses below the SMA  # The second is to sell when the price crosses below the SMA
108  stratFaber <- add.rule(stratFaber, name='ruleSignal', arguments = list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market'), type='exit', path.dep=TRUE)  add.rule('faber', name='ruleSignal', arguments = list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market',TxnFees=-5), type='exit', path.dep=TRUE)
109    
110  # Process the indicators and generate trades  # Process the indicators and generate trades
111  start_t<-Sys.time()  start_t<-Sys.time()
112  out<-try(applyStrategy(strategy=stratFaber , portfolios='faber'))  out<-try(applyStrategy(strategy='faber' , portfolios='faber'))
113  end_t<-Sys.time()  end_t<-Sys.time()
114  print("Strategy Loop:")  print("Strategy Loop:")
115  print(end_t-start_t)  print(end_t-start_t)
# Line 111  Line 119 
119    
120  start_t<-Sys.time()  start_t<-Sys.time()
121  updatePortf(Portfolio='faber',Dates=paste('::',as.Date(Sys.time()),sep=''))  updatePortf(Portfolio='faber',Dates=paste('::',as.Date(Sys.time()),sep=''))
122    updateAcct('faber')
123  end_t<-Sys.time()  end_t<-Sys.time()
124  print("trade blotter portfolio update:")  print("trade blotter portfolio update:")
125  print(end_t-start_t)  print(end_t-start_t)
# Line 119  Line 128 
128  themelist<-chart_theme()  themelist<-chart_theme()
129  themelist$col$up.col<-'lightgreen'  themelist$col$up.col<-'lightgreen'
130  themelist$col$dn.col<-'pink'  themelist$col$dn.col<-'pink'
131    
132    dev.new()
133    layout(mat=matrix(1:(length(symbols)+1),ncol=2))
134  for(symbol in symbols){  for(symbol in symbols){
135        chart.Posn(Portfolio='faber',Symbol=symbol,theme=themelist,TA="add_SMA(n=10,col='darkgreen')")
136    }
137    
138    ret1 <- PortfReturns('faber')
139    ret1$total<-rowSums(ret1)
140    ret1
141    
142    if("package:PerformanceAnalytics" %in% search() || require("PerformanceAnalytics",quietly=TRUE)){
143            getSymbols("SPY", src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
144            SPY<-to.monthly(SPY)
145            SPY.ret<-Return.calculate(SPY$SPY.Close)
146            index(SPY.ret)<-index(ret1)
147      dev.new()      dev.new()
148      chart.Posn(Portfolio='faber',Symbol=symbol,theme=themelist)          charts.PerformanceSummary(cbind(ret1$total,SPY.ret), geometric=FALSE, wealth.index=TRUE)
     plot(add_SMA(n=10,col='darkgreen', on=1))  
149  }  }
150    
151    faber.stats<-tradeStats('faber')[,c('Net.Trading.PL','Max.Drawdown','Num.Trades','Profit.Factor','Std.Dev.Trade.PL','Largest.Winner','Largest.Loser','Max.Equity','Min.Equity')]
152    faber.stats
153    
154  ###############################################################################  ###############################################################################
155  # R (http://r-project.org/) Quantitative Strategy Model Framework  # R (http://r-project.org/) Quantitative Strategy Model Framework
156  #  #
157  # Copyright (c) 2009-2010  # Copyright (c) 2009-2012
158  # Peter Carl, Dirk Eddelbuettel, Brian G. Peterson, Jeffrey Ryan, and Joshua Ulrich  # Peter Carl, Dirk Eddelbuettel, Brian G. Peterson,
159    # Jeffrey Ryan, Joshua Ulrich, and Garrett See
160  #  #
161  # This library is distributed under the terms of the GNU Public License (GPL)  # This library is distributed under the terms of the GNU Public License (GPL)
162  # for full details see the file COPYING  # for full details see the file COPYING
# Line 138  Line 164 
164  # $Id$  # $Id$
165  #  #
166  ###############################################################################  ###############################################################################
167    
168    ##### PLACE THIS BLOCK AT END OF DEMO SCRIPT ###################
169    # book  = getOrderBook(port)
170    # stats = tradeStats(port)
171    # rets  = PortfReturns(acct)
172    ################################################################

Legend:
Removed from v.450  
changed lines
  Added in v.1370

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge