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 287 - (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 :     # Try to clean up in case the demo was run previously
49 :     try(rm("account.longtrend","portfolio.longtrend",pos=.blotter),silent=TRUE)
50 :     try(rm("ltaccount","ltportfolio","ClosePrice","CurrentDate","equity","GSPC","i","initDate","initEq","Posn","UnitSize","verbose"),silent=TRUE)
51 :     try(rm("order_book.longtrend",pos=.strategy),silent=TRUE)
52 :    
53 :     # Set initial values
54 :     initDate='1997-12-31'
55 :     initEq=100000
56 :    
57 :     # Set up instruments with FinancialInstruments package
58 :     currency("USD")
59 :     symbols = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
60 :     for(symbol in symbols){ # establish tradable instruments
61 :     stock(symbol, currency="USD",multiplier=1)
62 :     }
63 :    
64 :     # Load data with quantmod
65 :     #getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1998-01-01')
66 :     ### Download monthly data instead?
67 :     ### GSPC=to.monthly(GSPC, indexAt='endof')
68 :     getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
69 :     for(symbol in symbols) {
70 :     x<-get(symbol)
71 :     x<-to.monthly(x,indexAt='lastof',drop.time=TRUE)
72 :     indexFormat(x)<-'%Y-%m-%d'
73 :     colnames(x)<-gsub("x",symbol,colnames(x))
74 :     assign(symbol,x)
75 :     }
76 :    
77 :     # Initialize portfolio and account
78 :     initPortf('longtrend', symbols=symbols, initDate=initDate)
79 :     initAcct('longtrend', portfolios='longtrend', initDate=initDate)
80 :     initOrders(portfolio='longtrend', initDate=initDate)
81 :    
82 :     print("setup completed")
83 :    
84 :     # Initialize a strategy object
85 :     s <- strategy("longtrend")
86 :    
87 :     # Add an indicator
88 :     s <- add.indicator(strategy = s, name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
89 :    
90 :     # There are two signals:
91 :     # The first is when monthly price crosses over the 10-month SMA
92 :     s<- add.signal(s,name="sigCrossover",arguments = list(data=quote(mktdata),columns=c("Close","SMA10"),relationship="gt"),label="Cl.gt.SMA")
93 :     # The second is when the monthly price crosses under the 10-month SMA
94 :     s<- add.signal(s,name="sigCrossover",arguments = list(data=quote(mktdata),columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")
95 :    
96 :     # There are two rules:
97 :     # The first is to buy when the price crosses above the SMA
98 :     s <- add.rule(s, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=1000, ordertype='market', orderside='long', pricemethod='market'), type='enter', path.dep=TRUE)
99 :     # The second is to sell when the price crosses below the SMA
100 :     s <- add.rule(s, name='ruleSignal', arguments = list(data=quote(mktdata), sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market'), type='exit', path.dep=TRUE)
101 :    
102 :     # Process the indicators and generate trades
103 :     start_t<-Sys.time()
104 :     out<-try(applyStrategy(strategy='s' , portfolios='longtrend'))
105 :     end_t<-Sys.time()
106 :     print("Strategy Loop:")
107 :     print(end_t-start_t)
108 :    
109 :     # look at the order book
110 :     #print(getOrderBook('longtrend'))
111 :    
112 :     start_t<-Sys.time()
113 :     updatePortf(Portfolio='longtrend',Dates=paste('::',as.Date(Sys.time()),sep=''))
114 :     end_t<-Sys.time()
115 :     print("trade blotter portfolio update:")
116 :     print(end_t-start_t)
117 :    
118 :     for(symbol in symbols){
119 :     dev.new()
120 :     chart.Posn(Portfolio='longtrend',Symbol=symbol,theme=chartTheme('white', up.col='lightgreen', dn.col='pink'), type='bar')
121 :     plot(addSMA(n=10,col='darkgreen', on=1))
122 :     }
123 :    
124 :    
125 :     ###############################################################################
126 :     # R (http://r-project.org/) Quantitative Strategy Model Framework
127 :     #
128 :     # Copyright (c) 2009-2010
129 :     # Peter Carl, Dirk Eddelbuettel, Brian G. Peterson, Jeffrey Ryan, and Joshua Ulrich
130 :     #
131 :     # This library is distributed under the terms of the GNU Public License (GPL)
132 :     # for full details see the file COPYING
133 :     #
134 :     # $Id$
135 :     #
136 :     ###############################################################################

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