SCM

SCM Repository

[blotter] Annotation of /pkg/quantstrat/sandbox/init.strat_0.5.3.R
ViewVC logotype

Annotation of /pkg/quantstrat/sandbox/init.strat_0.5.3.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 773 - (view) (download)

1 : gsee 773 ###########################################
2 :     # Functions that allow you to rapidly
3 :     # build (or remove) a quantstrat strategy
4 :     # First draft.
5 :     ###########################################
6 :    
7 :     ## Depends FinancialInstrument (>=0.6.5)
8 :     ## Depends quantstrat (>=0.5.3)
9 :     require(quantstrat)
10 :    
11 :    
12 :     #' init strategy, portfolio, account, and orders, and download data (getSymbols)
13 :     #' @param symbols character names of instrument primary_ids
14 :     #' @param portfolio character name of portfolio
15 :     #' @param initDate starting date
16 :     #' @param initEq initial portfolio value
17 :     #' @param account name of account. Not fully supported. Default is to use \code{portfolio}
18 :     #' @param env where to assign the strategy
19 :     #' @param store TRUE/FALSE whether to store the strategy in the .strategy environment, or return it. default FALSE
20 :     #' @author Garrett See
21 :     init.strat <-
22 :     function(symbols,
23 :     portfolio='default',
24 :     initDate = '2011-01-01',
25 :     initEq = 0,
26 :     account=portfolio,
27 :     currency='USD',
28 :     env=.GlobalEnv,
29 :     store=FALSE)
30 :     {
31 :     #if the currency hasn't been defined yet, define it.
32 :     if (!is.currency(currency)) currency <- currency(currency)
33 :    
34 :     #if any 'symbols' are not defined as instruments, we'll make a basic instrument
35 :     getsyms <- NULL #symbols that aren't in .GlobalEnv that we'll have to get
36 :     for (sym in symbols) {
37 :     if(!is.instrument(getInstrument(sym,silent=TRUE))) {
38 :     instrument.auto(sym, currency=currency)
39 :     }
40 :     tmp <- try(get(sym,pos=env),silent=TRUE)
41 :     #test for is.xts here?
42 :     if (inherits(tmp, 'try-error')) getsyms <- c(getsyms, sym)
43 :     }
44 :     if (!is.null(getsyms)) getSymbols(getsyms,from=initDate) #get the data that didn't exist in env
45 :     initPortf(name=portfolio, symbols=symbols, initPosQty=0, initDate=initDate)
46 :     initAcct(name=account, portfolios=portfolio, initDate=initDate, initEq=initEq, currency=currency)
47 :     initOrders(portfolio=portfolio, symbols=symbols, initDate=initDate)
48 :     if (store)
49 :     assign(portfolio, strategy(portfolio), env=env)
50 :     else return(strategy(portfolio))
51 :     portfolio
52 :     }
53 :    
54 :    
55 :     #' Remove objects associated with a strategy
56 :     #'
57 :     #' Remove the order_book, account, and portfolio
58 :     #' @param name name of the portfolio.
59 :     rm.strat <- function(name='default') {
60 :     if (is.strategy(name)) name <- name[['name']]
61 :     try(rm(list=paste("order_book",name,sep="."), pos=.strategy))
62 :     try(rm(list=paste(c("account", "portfolio"), name, sep="."), pos=.blotter))
63 :     }
64 :    
65 :    
66 :     #' Add sigCrossover signals and rules to your strategy
67 :     #' @param strategy name of a strategy or the strategy itself
68 :     #' @param pcolumns vector of names of price columns that need to cross indicator columns to trigger a signal. First columns in \code{\link{sigCrossover}} columns argument
69 :     #' @param icolumns vecror of names of indicator columns that when crossed by price columns will trigger a signal. Second columns in \code{\link{sigCrossover}} columns argument
70 :     #' @param relationships vector of same length as \code{pcolumns} indicating how to compare pcolumns and icolumns ('gt', 'lt', 'gte', 'lte' for greater than, less than, greater than or equal, less than or equal, respectively
71 :     #' @param ruletypes vector of same lenghth as \code{pcolumns} indicating type of rule ('enter', 'exit', etc.)
72 :     #' @param orderqty list of same length as \code{pcolumns} indicating or1der quantities
73 :     #' @param ordertypes vector of same length as \code{pcolumns} indicating type of order ('market', 'limit', etc')
74 :     #' @param df optional data.frame with columns named \code{pcolumns}, \code{icolumns}, \code{relationships},
75 :     #' \code{ruletypes}, \code{orderqty}, \code{ordertypes} to use instead of those respective arguments.
76 :     #' @param portfolio name of portfolio. if missing, it will become the same as the strategy name
77 :     #' @param store TRUE/FALSE whether to store the strategy in the .strategy environment, or return it. default FALSE
78 :     #' @author Garrett See
79 :     add.sigCrossovers <-
80 :     function(strategy,
81 :     pcolumns= rep("Close",4),
82 :     icolumns= c('dn','up','mavg','mavg'),
83 :     relationships=c('lt','gt','gt','lt'),
84 :     ruletypes= c('enter','enter','exit','exit'),
85 :     orderqty= list(100,-100,'all','all'),
86 :     ordertypes= rep("market",4),
87 :     df= NULL,
88 :     osFUN='osNoOp',
89 :     portfolio,
90 :     store = FALSE) {
91 :     #if (is.strategy(strategy)) strategy <- strategy$name
92 :     if (!is.strategy(strategy)) strategy <- getStrategy(strategy)
93 :     if (missing(portfolio)) portfolio <- strategy$name
94 :     if (!is.null(df)) {
95 :     if (!is.null(df$pcolumns)) pcolumns <- df$pcolumns
96 :     if (!is.null(df$icolumns)) icolumns <- df$icolumns
97 :     if (!is.null(df$relationships)) relationships <- df$relationships
98 :     if (!is.null(df$ruletypes)) ruletypes <- df$ruletypes
99 :     if (!is.null(df$orderqty)) orderqty <- df$orderqty
100 :     if (!is.null(df$ordertypes)) ordertypes <- df$ordertypes
101 :     }
102 :     lpc <- length(pcolumns)
103 :     if (lpc != length(icolumns) || lpc != length(relationships)
104 :     || lpc != length(ruletypes) || lpc !=length(ordertypes)
105 :     || lpc !=length(orderqty)) stop("all args except 'strategy' must be of the same length")
106 :     for (i in seq_along(pcolumns)) {
107 :     rulename <- paste(pcolumns[[i]],relationships[[i]],icolumns[[i]],sep=".")
108 :     strategy <- add.signal(strategy, name="sigCrossover",
109 :     arguments = list(columns=c(pcolumns[[i]],icolumns[[i]]),relationship=relationships[[i]]),
110 :     label=rulename, store=FALSE)
111 :     qty <- ifelse(orderqty[[i]] != 'all',as.numeric(orderqty[[i]]), 'all')
112 :     strategy <- add.rule(strategy, 'ruleSignal',
113 :     arguments = list(sigcol=rulename, sigval=TRUE,
114 :     orderqty=orderqty[[i]],
115 :     orderside=NULL,
116 :     threshold=NULL,
117 :     pricemethod='opside',
118 :     portfolio=portfolio,
119 :     ordertype=ordertypes[[i]],
120 :     osFUN=osFUN),
121 :     type=ruletypes[[i]],
122 :     store=FALSE)
123 :     }
124 :     if (store) assign(strategy$name, strategy, pos='.strategy')
125 :     else return(strategy)
126 :     strategy$name
127 :     }
128 :    
129 :     #' update portfolio, account, and ending equity
130 :     #' @param portfolio string identifying a portfolio
131 :     #' @param account string identifying an account. Same as \code{portfolio} by default
132 :     #' @param Symbols: character vector of names of symbols whose portfolios will be updated
133 :     #' @param Dates optional xts-style ISO-8601 time range to run updatePortf over, default NULL (will use times from Prices)
134 :     #' @param Prices optional xts object containing prices and timestamps to mark the book on, default NULL
135 :     #' @param showEq TRUE/FALSE should ending equity be printed to the screen with a call to \code{cat}. default TRUE
136 :     #' @param chart TRUE/FALSE if TRUE (default) a call will be made to \code{chart.Posn}
137 :     #' @seealso \code{\link{updatePortf}}, \code{\link{updateAcct}}, \code{\link{updateEndEq}}
138 :     #' @author Garrett See
139 :     update.strat <-
140 :     function(portfolio='default',
141 :     account=portfolio,
142 :     Symbols=NULL,
143 :     Dates=NULL,
144 :     Prices=NULL,
145 :     showEq=TRUE,
146 :     chart=TRUE)
147 :     {
148 :     out <- list()
149 :     out[['portfolio.st']] <- updatePortf(Portfolio=portfolio, Symbols=Symbols, Dates=Dates, Prices=Prices)
150 :     out[['account.st']] <- updateAcct(name=account,Dates=Dates)
151 :     updateEndEq(Account=account,Dates=Dates)
152 :     if (showEq) cat('EndingEq: ', getEndEq(Account=account,Date=Sys.time()), '\n')
153 :     if (chart) chart.Posn(Portfolio=portfolio, Symbol=names(getPortfolio(portfolio)$symbols)[[1]])
154 :     if (out[[1]] == out[[2]]) out[[1]]
155 :     else out
156 :     }
157 :    
158 :     ##########################################################################################################
159 :     ##### Now for a demo. These few lines will do what the bbands demo does.
160 :     #rm.strat('bbands')
161 :     strat <- init.strat(stock("IBM",currency("USD"),src='yahoo'), portfolio='bbands', initDate='2006-12-31')
162 :     strat <- add.indicator(strat, name='BBands', arguments=list(HLC=quote(HLC(mktdata)), maType='SMA'))
163 :     strat <- add.sigCrossovers(strat)
164 :     out<-try(applyStrategy(strat, strat$name, parameters=list(sd=2,n=20)) )
165 :     update.strat('bbands')
166 :     ##### End bbands demo.
167 :     ##########################################################################################################
168 :    
169 :    
170 :     #####
171 :     ## Although it is recommended, it is not required to define the stock beforehand
172 :     ## (or in the call as we did above with stock("IBM",currency("USD"),src='yahoo')),
173 :     ## The below would have worked by creating a basic instrument with multiplier=1 and type=NULL.
174 :     ## it would make an 'instrument' and a portfolio called 'default'
175 :     #
176 :     # strat <- init.strat('IBM',initDate='2006-12-31')
177 :     #####
178 :    
179 :     #########################################################################################################
180 :     #### OR you can pass a df that contains a column for each pertinent argument.
181 :     #rm.strat()
182 :     strat <- init.strat('IBM', initDate='2010-01-01')
183 :     strat <- add.indicator(strat, name='BBands',arguments=list(HLC=quote(HLC(mktdata)),maType='SMA'))
184 :    
185 :     sigrule.args <- data.frame(cbind(
186 :     pcolumns= c("Close","Close","High","Low"),
187 :     icolumns= c('dn','up','mavg','mavg'),
188 :     relationships=c('lt','gt','gt','lt'),
189 :     ruletypes= c('enter','enter','exit','exit'),
190 :     orderqty= list(100,-100,'all','all'),
191 :     ordertypes= rep("market",4)
192 :     ))
193 :    
194 :     strat <- add.sigCrossovers(strat,df=sigrule.args)
195 :     out <- try(applyStrategy(strat, strat$name, parameters=list(sd=1.8,n=50)))
196 :     ########################################################################################################
197 :    
198 :    
199 :     ########################################################################################################
200 :     #make a break-out strategy with "PBands"
201 :     library(twsInstrument)
202 :     library(qmao)
203 :    
204 :     rm.strat()
205 :     #rm(list=symb)
206 :     rm_futures()
207 :     future("VX",multiplier=1000,src='cfe',underlying_id=synthetic("VIX",currency("USD")))
208 :     symb <- future_series("VX_G07")
209 :     getSymbols(symb)
210 :     #start(VX_G07)
211 :     strat <- init.strat(symb,initDate='2006-04-01')
212 :     strat <- add.indicator(strat, name='PBands',arguments=list(prices=quote(Cl(mktdata)),maType='SMA'))
213 :     #breakout strategy. Buy when it crosses upper band exit at 'center'.
214 :     #Sell at bottom band cross. exit at center
215 :     strat <- add.sigCrossovers(strat,
216 :     icolumns=c("up","dn","center","center"),
217 :     relationships=c("gt", "lt", "lt", "gt"),
218 :     orderqty=list(1,-1,'all','all'))
219 :     out<-try(applyStrategy(strat, strat$name, parameters=list(sd=2,n=20,fastn=2)) )
220 :     update.strat()
221 :     #########################################################################################################
222 :    
223 :    
224 :     ##########################################################
225 :     # This is a proof-of-concept script.
226 :     # There is an uncommitted new version that does not require
227 :     # that all the lines begin with strat <-
228 :     # but it requires a couple tweaks to quantstrat.
229 :     ##
230 :     # Everything is subject to change including function and
231 :     # argument names as well as usage, return values,
232 :     # flexibility, and functionality.
233 :     ##########################################################
234 :    
235 :    

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