SCM

SCM Repository

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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1506 - (view) (download)

1 : peter_carl 287 # This is a very simple trend following strategy for testing the results of:
2 :     # Faber, Mebane T., "A Quantitative Approach to Tactical Asset Allocation."
3 :     # Journal of Risk Management (Spring 2007).
4 :     # The article proposes a very simple quantitative market-timing model. They
5 :     # test the model in sample on the US stock market since 1900 before testing
6 :     # it out-of-sample in twenty other markets.
7 :    
8 :     # The article discusses a 200-day simple moving average, which is proposed
9 :     # in Jeremy Seigel's book "Stocks for the Long Run" for timing the DJIA. He
10 :     # concludes that a simple market timing strategy improves the absolute and
11 :     # risk adjusted returns over a buy-and-hold strategy. After all transaction
12 :     # costs are included, the timing strategy falls short on the absolute return,
13 :     # but still provides a better risk-adjusted return. Siegel also tests timing on
14 :     # the Nasdaq composite since 1972 and finds better absolute and risk adjusted
15 :     # returns.
16 :    
17 :     # The article implements a simpler version of the 200-day SMA, opting for a
18 :     # 10-month SMA. Monthly data is more easily available for long periods of time,
19 :     # and the lower granularity should translate to lower transaction costs.
20 :    
21 :     # The rules of the system are relatively simple:
22 :     # - Buy when monthly price > 10-month SMA
23 :     # - Sell and move to cash when monthly price < 10-month SMA
24 :    
25 :     # 1. All entry and exit prices are on the day of the signal at the close.
26 :     # 2. All data series are total return series including dividends, updated monthly.
27 :     # For the purposes of this demo, we only use price returns.
28 :     # 3. Cash returns are estimated with 90-day commercial paper. Margin rates for
29 :     # leveraged models are estimated with the broker call rate. Again, for the
30 :     # purposes of this demo, we ignore interest and leverage.
31 :     # 4. Taxes, commissions, and slippage are excluded.
32 :    
33 :     # This simple strategy is different from well-known trend-following systems in
34 :     # three respects. First, there's no shorting. Positions are converted to cash on
35 :     # a 'sell' signal, rather than taking a short position. Second, the entire position
36 :     # is put on at trade inception. No assumptions are made about increasing position
37 :     # size as the trend progresses. Third, there are no stops. If the trend reverts
38 :     # quickly, this system will wait for a sell signal before selling the position.
39 :    
40 :     # Data
41 :     # Instead of using total returns data, this demo uses monthly data for the SP500
42 :     # downloaded from Yahoo Finance. We'll use about 10 years of data, starting at
43 :     # the beginning of 1998.
44 :    
45 :     # Load required libraries
46 :     require(quantstrat)
47 :    
48 : braverock 1418 #correct for TZ issues if they crop up
49 :     oldtz<-Sys.getenv('TZ')
50 :     if(oldtz=='') {
51 :     Sys.setenv(TZ="GMT")
52 :     }
53 : peter_carl 287 # Try to clean up in case the demo was run previously
54 : gsee 621 suppressWarnings(rm("account.faber","portfolio.faber",pos=.blotter))
55 :     suppressWarnings(rm("ltaccount", "ltportfolio", "ClosePrice", "CurrentDate", "equity",
56 :     "GSPC", "stratFaber", "initDate", "initEq", "Posn", "UnitSize", "verbose"))
57 :     suppressWarnings(rm("order_book.faber",pos=.strategy))
58 : peter_carl 287
59 : milktrader 1376 ##### PLACE DEMO AND TEST DATES HERE #################
60 :     #
61 :     #if(isTRUE(options('in_test')$in_test))
62 :     # # use test dates
63 :     # {initDate="2011-01-01"
64 :     # endDate="2012-12-31"
65 :     # } else
66 :     # # use demo defaults
67 :     # {initDate="1999-12-31"
68 :     # endDate=Sys.Date()}
69 : milktrader 1370
70 : peter_carl 287 # Set initial values
71 :     initDate='1997-12-31'
72 :     initEq=100000
73 :    
74 :     # Set up instruments with FinancialInstruments package
75 :     currency("USD")
76 :     symbols = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
77 :     for(symbol in symbols){ # establish tradable instruments
78 :     stock(symbol, currency="USD",multiplier=1)
79 :     }
80 :    
81 :     # Load data with quantmod
82 :     #getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1998-01-01')
83 :     ### Download monthly data instead?
84 :     ### GSPC=to.monthly(GSPC, indexAt='endof')
85 :     getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
86 :     for(symbol in symbols) {
87 :     x<-get(symbol)
88 :     x<-to.monthly(x,indexAt='lastof',drop.time=TRUE)
89 :     indexFormat(x)<-'%Y-%m-%d'
90 :     colnames(x)<-gsub("x",symbol,colnames(x))
91 :     assign(symbol,x)
92 :     }
93 :    
94 :     # Initialize portfolio and account
95 : braverock 362 initPortf('faber', symbols=symbols, initDate=initDate)
96 : braverock 599 initAcct('faber', portfolios='faber', initDate=initDate, initEq=100000)
97 : braverock 362 initOrders(portfolio='faber', initDate=initDate)
98 : peter_carl 287
99 :     print("setup completed")
100 :    
101 :     # Initialize a strategy object
102 : braverock 1254 strategy("faber", store=TRUE)
103 : peter_carl 287
104 :     # Add an indicator
105 : braverock 1254 add.indicator('faber', name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
106 : peter_carl 287
107 :     # There are two signals:
108 :     # The first is when monthly price crosses over the 10-month SMA
109 : braverock 1254 add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="gte"),label="Cl.gt.SMA")
110 : peter_carl 287 # The second is when the monthly price crosses under the 10-month SMA
111 : braverock 1254 add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")
112 : peter_carl 287
113 :     # There are two rules:
114 :     # The first is to buy when the price crosses above the SMA
115 : braverock 1260 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)
116 : peter_carl 287 # The second is to sell when the price crosses below the SMA
117 : braverock 1254 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)
118 : peter_carl 287
119 :     # Process the indicators and generate trades
120 :     start_t<-Sys.time()
121 : braverock 1254 out<-try(applyStrategy(strategy='faber' , portfolios='faber'))
122 : peter_carl 287 end_t<-Sys.time()
123 :     print("Strategy Loop:")
124 :     print(end_t-start_t)
125 :    
126 :     # look at the order book
127 : braverock 362 #print(getOrderBook('faber'))
128 : peter_carl 287
129 :     start_t<-Sys.time()
130 : braverock 362 updatePortf(Portfolio='faber',Dates=paste('::',as.Date(Sys.time()),sep=''))
131 : braverock 1254 updateAcct('faber')
132 : peter_carl 1489 updateEndEq('faber')
133 : peter_carl 287 end_t<-Sys.time()
134 :     print("trade blotter portfolio update:")
135 :     print(end_t-start_t)
136 :    
137 : braverock 309 # hack for new quantmod graphics, remove later
138 :     themelist<-chart_theme()
139 : braverock 450 themelist$col$up.col<-'lightgreen'
140 :     themelist$col$dn.col<-'pink'
141 : braverock 1254
142 :     dev.new()
143 :     layout(mat=matrix(1:(length(symbols)+1),ncol=2))
144 : peter_carl 287 for(symbol in symbols){
145 : braverock 1254 chart.Posn(Portfolio='faber',Symbol=symbol,theme=themelist,TA="add_SMA(n=10,col='darkgreen')")
146 : peter_carl 287 }
147 :    
148 : braverock 599 ret1 <- PortfReturns('faber')
149 : braverock 1418 ret1$total<-rowSums(ret1)
150 : braverock 1416 View(ret1)
151 : peter_carl 287
152 : braverock 599 if("package:PerformanceAnalytics" %in% search() || require("PerformanceAnalytics",quietly=TRUE)){
153 :     getSymbols("SPY", src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
154 :     SPY<-to.monthly(SPY)
155 :     SPY.ret<-Return.calculate(SPY$SPY.Close)
156 : braverock 1506 SPY.ret<-na.omit(SPY.ret)
157 : braverock 1418 index(SPY.ret)<-index(ret1)
158 : braverock 599 dev.new()
159 :     charts.PerformanceSummary(cbind(ret1$total,SPY.ret), geometric=FALSE, wealth.index=TRUE)
160 :     }
161 :    
162 : braverock 1212 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')]
163 : peter_carl 1489 View(faber.stats)
164 : braverock 599
165 : braverock 1418 Sys.setenv(TZ=oldtz)
166 : peter_carl 287 ###############################################################################
167 :     # R (http://r-project.org/) Quantitative Strategy Model Framework
168 :     #
169 : braverock 1194 # Copyright (c) 2009-2012
170 : gsee 639 # Peter Carl, Dirk Eddelbuettel, Brian G. Peterson,
171 :     # Jeffrey Ryan, Joshua Ulrich, and Garrett See
172 : peter_carl 287 #
173 :     # This library is distributed under the terms of the GNU Public License (GPL)
174 :     # for full details see the file COPYING
175 :     #
176 :     # $Id$
177 :     #
178 : braverock 599 ###############################################################################
179 : milktrader 1370
180 :     ##### PLACE THIS BLOCK AT END OF DEMO SCRIPT ###################
181 :     # book = getOrderBook(port)
182 :     # stats = tradeStats(port)
183 :     # rets = PortfReturns(acct)
184 :     ################################################################

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