SCM

SCM Repository

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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1370 - (view) (download)

1 : braverock 389 # 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 :     # Try to clean up in case the demo was run previously
49 : gsee 621 suppressWarnings(rm("account.faber","account.faberMC","portfolio.faber","portfolio.combMC",
50 :     "portfolio.GDAXI", "portfolio.GSPC", "portfolio.N225",pos=.blotter))
51 :     suppressWarnings(rm("ltaccount","ltportfolio","ClosePrice","CurrentDate","equity","stratFaber","initDate","initEq","Posn","UnitSize","verbose"))
52 :     suppressWarnings(rm("order_book.faber","order_book.combMC", "order_book.GDAXI", "order_book.GSPC", "order_book.N225", pos=.strategy))
53 : braverock 389
54 : milktrader 1370 ##### 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 : braverock 389 # Set initial values
62 : gsee 621 initDate='2000-01-01'
63 : braverock 389 initEq=100000
64 :    
65 :     # Set up instruments with FinancialInstruments package
66 : gsee 621 symbols = c("^GSPC", "^N225", "^GDAXI")
67 : braverock 389
68 :     currency("USD")
69 :     currency("JPY")
70 :     currency("EUR")
71 :    
72 :     #get the currencies
73 : gsee 642 USDJPY<-getPrice(to.monthly(getSymbols("JPY=X",auto.assign=FALSE),indexAt='lastof',drop.time=TRUE))
74 : braverock 389 EURUSD<-getPrice(to.monthly(getSymbols("EURUSD=X",auto.assign=FALSE),indexAt='lastof',drop.time=TRUE))
75 : gsee 642 colnames(USDJPY)<-"USDJPY"
76 : braverock 389 colnames(EURUSD)<-"EURUSD"
77 :    
78 :     getSymbols(symbols,from=initDate)
79 :     #takes out the carat
80 : gsee 621 symbols = c("GSPC", "N225", "GDAXI")
81 : braverock 389
82 :    
83 :     stock(symbols[1], currency="USD",multiplier=1)
84 :     stock(symbols[2], currency="JPY",multiplier=1)
85 :     stock(symbols[3], currency="EUR",multiplier=1)
86 :     # to do this truly correctly, we'd use the futures contracts, which are tradable
87 :    
88 :     for(symbol in symbols) {
89 :     x<-get(symbol)
90 :     x<-to.monthly(x,indexAt='lastof',drop.time=TRUE)
91 :     indexFormat(x)<-'%Y-%m-%d'
92 :     colnames(x)<-gsub("x",symbol,colnames(x))
93 :     assign(symbol,x)
94 :     initPortf(symbol, symbols=symbol, initDate=initDate, currency=getInstrument(symbol)$currency)
95 :     initOrders(portfolio=symbol, initDate=initDate)
96 :     }
97 :    
98 :    
99 :     initAcct('faberMC', portfolios=symbols, initDate=initDate, currency="USD")
100 :    
101 :     # Initialize portfolio and account
102 :    
103 :     print("setup completed")
104 :    
105 :     # Initialize a strategy object
106 :     stratFaber <- strategy("faber")
107 :    
108 :     # Add an indicator
109 :     stratFaber <- add.indicator(strategy = stratFaber, name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
110 :    
111 :     # There are two signals:
112 :     # The first is when monthly price crosses over the 10-month SMA
113 : gsee 639 stratFaber <- add.signal(stratFaber,name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="gte"),label="Cl.gt.SMA")
114 : braverock 389 # The second is when the monthly price crosses under the 10-month SMA
115 :     stratFaber <- add.signal(stratFaber,name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")
116 :    
117 :     # There are two rules:
118 :     # The first is to buy when the price crosses above the SMA
119 :     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)
120 :     # The second is to sell when the price crosses below the SMA
121 :     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)
122 :    
123 :     # Process the indicators and generate trades
124 :     start_t<-Sys.time()
125 :     out<-try(applyStrategy(strategy=stratFaber , portfolios=symbols))
126 :     end_t<-Sys.time()
127 :     print("Strategy Loop:")
128 :     print(end_t-start_t)
129 :    
130 :     # look at the order book
131 :     #print(getOrderBook('faber'))
132 :    
133 :     start_t<-Sys.time()
134 :     for(symbol in symbols) {
135 :     updatePortf(Portfolio=symbol,Dates=paste('::',as.Date(Sys.time()),sep=''))
136 :     }
137 :     end_t<-Sys.time()
138 :     print("trade blotter portfolio update:")
139 :     print(end_t-start_t)
140 :    
141 :     #and a combined portfolio
142 :     initPortf('combMC', symbols=symbols, initDate=initDate, currency="USD")
143 :     initOrders(portfolio= 'combMC', initDate=initDate)
144 :     comb.out<-applyStrategy(strategy=stratFaber , portfolios='combMC')
145 :     updatePortf(Portfolio='combMC',Dates=paste('::',as.Date(Sys.time()),sep=''))
146 :    
147 :     # hack for new quantmod graphics, remove later
148 :     themelist<-chart_theme()
149 : braverock 450 themelist$col$up.col<-'lightgreen'
150 :     themelist$col$dn.col<-'pink'
151 : braverock 389 for(symbol in symbols){
152 :     dev.new()
153 :     chart.Posn(Portfolio=symbol,Symbol=symbol,theme=themelist)
154 :     plot(add_SMA(n=10,col='darkgreen', on=1))
155 :     }
156 :    
157 :    
158 :     ###############################################################################
159 :     # R (http://r-project.org/) Quantitative Strategy Model Framework
160 :     #
161 : braverock 1194 # Copyright (c) 2009-2012
162 : gsee 639 # Peter Carl, Dirk Eddelbuettel, Brian G. Peterson,
163 :     # Jeffrey Ryan, Joshua Ulrich, and Garrett See
164 : braverock 389 #
165 :     # This library is distributed under the terms of the GNU Public License (GPL)
166 :     # for full details see the file COPYING
167 :     #
168 :     # $Id: faber.R 371 2010-08-12 20:18:09Z braverock $
169 :     #
170 : gsee 621 ###############################################################################
171 : milktrader 1370
172 :     ##### PLACE THIS BLOCK AT END OF DEMO SCRIPT ###################
173 :     # book = getOrderBook(port)
174 :     # stats = tradeStats(port)
175 :     # rets = PortfReturns(acct)
176 :     ################################################################

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