[Blotter-commits] r1260 - in pkg/quantstrat: . R demo man

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Thu Nov 22 03:05:42 CET 2012


Author: braverock
Date: 2012-11-22 03:05:41 +0100 (Thu, 22 Nov 2012)
New Revision: 1260

Added:
   pkg/quantstrat/demo/faber_rebal.R
   pkg/quantstrat/demo/macdRebalancing.R
Modified:
   pkg/quantstrat/DESCRIPTION
   pkg/quantstrat/R/applyStrategy.rebalancing.R
   pkg/quantstrat/R/rebalance.rules.R
   pkg/quantstrat/R/ruleOrderProc.R
   pkg/quantstrat/R/rules.R
   pkg/quantstrat/demo/faber.R
   pkg/quantstrat/man/apply.paramset.Rd
   pkg/quantstrat/man/ruleOrderProc.Rd
Log:
- use timestamp rather than character timespan in ruleOrderProc
- remove obsolete code
- add rebalancing examples
- update roxygen docs


Modified: pkg/quantstrat/DESCRIPTION
===================================================================
--- pkg/quantstrat/DESCRIPTION	2012-11-21 19:59:26 UTC (rev 1259)
+++ pkg/quantstrat/DESCRIPTION	2012-11-22 02:05:41 UTC (rev 1260)
@@ -1,10 +1,9 @@
 Package: quantstrat
 Type: Package
 Title: Quantitative Strategy Model Framework
-Version: 0.7.4
+Version: 0.7.5
 Date: $Date$
-Author: Peter Carl, Dirk Eddelbuettel, Brian G. Peterson,
-    Jeffrey A. Ryan, Joshua Ulrich, Garrett See
+Author: Peter Carl, Brian G. Peterson, Joshua Ulrich, Jan Humme
 Depends:
     xts(>= 0.8-2),TTR(>= 0.2),blotter(>= 0.7.2),
     FinancialInstrument(>= 0.12.5)
@@ -13,7 +12,7 @@
 Maintainer: Brian G. Peterson <brian at braverock.com>
 Description: Specify, build, and back-test quantitative
     financial trading and portfolio strategies
-Contributors: Yu Chen, Joe Dunn, Jan Humme
+Contributors: Yu Chen, Joe Dunn, Dirk Eddelbuettel, Jeffrey A. Ryan, Garrett See   
 LazyLoad: yes
 License: GPL-3
-ByteCompile: TRUE
+ByteCompile: FALSE

Modified: pkg/quantstrat/R/applyStrategy.rebalancing.R
===================================================================
--- pkg/quantstrat/R/applyStrategy.rebalancing.R	2012-11-21 19:59:26 UTC (rev 1259)
+++ pkg/quantstrat/R/applyStrategy.rebalancing.R	2012-11-22 02:05:41 UTC (rev 1260)
@@ -139,8 +139,9 @@
                 md_subset<-mktdata[as.POSIXct(index(mktdata))>pindex[i-1]&as.POSIXct(index(mktdata))<=pindex[i]]
                 if(nrow(md_subset)<1) next()
                 #applyRules to this subset for this instrument  
-                sret$rules$pathdep<-rbind(sret$rules$pathdep,
-                                      applyRules(portfolio=portfolio, symbol=symbol, strategy=s, mktdata=md_subset, Dates=NULL, indicators=sret$indicators, signals=sret$signals, parameters=parameters,  ..., path.dep=TRUE))
+                #sret$rules$pathdep<-rbind(sret$rules$pathdep,
+                                      applyRules(portfolio=portfolio, symbol=symbol, strategy=s, mktdata=md_subset, Dates=NULL, indicators=sret$indicators, signals=sret$signals, parameters=parameters,  ..., path.dep=TRUE)
+                #)
                 
                 ret[[portfolio]][[symbol]]<-sret
             } #end loop over symbols for this sub-period

Modified: pkg/quantstrat/R/rebalance.rules.R
===================================================================
--- pkg/quantstrat/R/rebalance.rules.R	2012-11-21 19:59:26 UTC (rev 1259)
+++ pkg/quantstrat/R/rebalance.rules.R	2012-11-22 02:05:41 UTC (rev 1260)
@@ -26,7 +26,7 @@
 #' 
 #' @examples 
 #' # example rule definition
-#' \code{
+#' \dontrun{
 #' add.rule(strategy.name, 'rulePctEquity',
 #'         arguments=list(rebalance_on='months',
 #'                        trade.percent=.02,
@@ -63,6 +63,47 @@
                 shortlevels = shortlevels)
 }
 
+ruleWeights <- function (weights=NULL,
+        ...,
+        longlevels=1, 
+        shortlevels=1, 
+        digits=NULL,
+        portfolio,
+        symbol,
+        account=NULL,
+        timestamp)
+{
+    #update portfolio
+    dummy <- updatePortf(Portfolio=portfolio,
+            Dates=paste('::',timestamp,sep=''))
+    
+    #get total account equity
+    if(!is.null(account)){
+        dummy <- updateAcct(Account=account,
+                Dates=paste('::',timestamp,sep=''))
+        dummy <- updateEndEq(Account=account,
+                Dates=paste('::',timestamp,sep=''))
+        total.equity<-getEndEq(account)
+    } else {
+        trading.pl <- sum(getPortfolio(portfolio)$summary$Net.Trading.PL)
+        total.equity <- initEq+trading.pl
+    }
+    
+    if(!is.null(digits)) tradeSize<-round(tradeSize,digits)
+    addPosLimit(portfolio = portfolio, 
+            symbol = symbol, 
+            timestamp = timestamp, 
+            maxpos = tradeSize, 
+            longlevels = longlevels, 
+            minpos = -tradeSize, 
+            shortlevels = shortlevels)
+}
+
+#TODO weights rule that takes or calculates max position based on weights
+#TODO active weights rule that moved from current positions to target positions
+#TODO PortfolioAnalytics sizing
+#TODO LSPM sizing
+
 ###############################################################################
 # R (http://r-project.org/) Quantitative Strategy Model Framework
 #

Modified: pkg/quantstrat/R/ruleOrderProc.R
===================================================================
--- pkg/quantstrat/R/ruleOrderProc.R	2012-11-21 19:59:26 UTC (rev 1259)
+++ pkg/quantstrat/R/ruleOrderProc.R	2012-11-22 02:05:41 UTC (rev 1260)
@@ -39,7 +39,7 @@
 #' @param portfolio text name of the portfolio to associate the order book with
 #' @param symbol identfier of the instrument to find orders for.  The name of any associated price objects (xts prices, usually OHLC or BBO) should match these
 #' @param mktdata an xts object containing market data.  depending on indicators, may need to be in OHLCV or BBO formats, default NULL
-#' @param timespan xts-style character timespan to be the period to find orders to process in
+#' @param timestamp timestamp coercible to POSIXct that will be the time the order will be processed on 
 #' @param ordertype one of NULL, "market","limit","stoplimit", or "stoptrailing" default NULL
 #' @param ... any other passthru parameters
 #' @param slippageFUN default  NULL, not yet implemented
@@ -49,29 +49,26 @@
 #' @seealso addOrder
 #' @seealso updateOrders
 #' @export
-ruleOrderProc <- function(portfolio, symbol, mktdata, timespan=NULL, ordertype=NULL, ..., slippageFUN=NULL)
+ruleOrderProc <- function(portfolio, symbol, mktdata, timestamp=NULL, ordertype=NULL, ..., slippageFUN=NULL)
 {
-    if(is.null(timespan)) return()
+    if(is.null(timestamp)) return()
     orderbook <- getOrderBook(portfolio)
     ordersubset <- orderbook[[portfolio]][[symbol]]
     
     # get open orders
     OpenOrders.i=NULL
+    #TODO calculate timespan here?
     OpenOrders.i<-getOrders(portfolio=portfolio, symbol=symbol, status="open", timespan=timespan, ordertype=ordertype, which.i=TRUE)
 
     if(hasArg(prefer)) prefer=match.call(expand.dots=TRUE)$prefer
     else prefer = NULL
 
     # check for open orders
-    if (length(OpenOrders.i)>=1){
-        # get previous bar
-        prevtime  <- time(mktdata[last(mktdata[timespan, which.i = TRUE])-1]) 
-        timestamp <- time(last(mktdata[timespan]))
-        #switch on frequency
-        freq = periodicity(mktdata)
+    if (!(length(OpenOrders.i)>=1)){
+        return(NULL)  
+    } else {
         mktdataTimestamp <- mktdata[timestamp]
-        #str(mktdataTimestamp)
-        # Should we only keep the last observation per time stamp?
+        # only keep the last observation per time stamp
         if( NROW(mktdataTimestamp) > 1 ) mktdataTimestamp <- last(mktdataTimestamp)
         isOHLCmktdata <- is.OHLC(mktdata)
         isBBOmktdata  <- is.BBO(mktdata)
@@ -109,6 +106,8 @@
 
             orderType <- ordersubset[ii,"Order.Type"]
 
+            freq = periodicity(mktdata)
+            #switch on frequency
             switch(orderType,
                     market = {
                         switch(freq$scale,
@@ -117,7 +116,7 @@
                                 monthly = {
                                     txntime=as.character(index(ordersubset[ii,])) # transacts on this bar, e.g. in the intraday cross, or leading into the end of month, quarter, etc.
                                     # txntime=as.character(timestamp) # use this if you wanted to transact on the close of the next bar
-                                    txnprice=as.numeric(getPrice(last(mktdata[txntime]), prefer=prefer)[,1])
+                                    txnprice=as.numeric(getPrice(mktdataTimestamp, prefer=prefer)[,1])
                                 }, #end daily
                                 { 
                                     txntime = timestamp
@@ -338,7 +337,7 @@
                             }
                         }
 
-                    }
+                    } # end stoptrailing
             )
 
             if(!is.null(txnprice) && !isTRUE(is.na(txnprice)))

Modified: pkg/quantstrat/R/rules.R
===================================================================
--- pkg/quantstrat/R/rules.R	2012-11-21 19:59:26 UTC (rev 1259)
+++ pkg/quantstrat/R/rules.R	2012-11-22 02:05:41 UTC (rev 1260)
@@ -617,11 +617,11 @@
                             #(mktdata, portfolio, symbol, timestamp, slippageFUN=NULL)
 
                             if (isTRUE(path.dep))
-                                timespan <- format(timestamp, "::%Y-%m-%d %H:%M:%OS6")
+                                timespan <- format(timestamp, "::%Y-%m-%d %H:%M:%OS6") #may be unecessary
                             else
-                                timespan=NULL
+                                timestamp=NULL
 
-                            closed.orders <- ruleOrderProc(portfolio=portfolio, symbol=symbol, mktdata=mktdata, timespan=timespan, ...)
+                            closed.orders <- ruleOrderProc(portfolio=portfolio, symbol=symbol, mktdata=mktdata, timestamp=timestamp, ...)
                         }
                     },
                     chain = {

Modified: pkg/quantstrat/demo/faber.R
===================================================================
--- pkg/quantstrat/demo/faber.R	2012-11-21 19:59:26 UTC (rev 1259)
+++ pkg/quantstrat/demo/faber.R	2012-11-22 02:05:41 UTC (rev 1260)
@@ -96,7 +96,7 @@
 
 # There are two rules:
 # The first is to buy when the price crosses above the SMA
-add.rule('faber', name='ruleSignal', arguments = list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=1000, ordertype='market', orderside='long', pricemethod='market',TxnFees=-5), 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)
 # The second is to sell when the price crosses below the SMA
 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)
 

Added: pkg/quantstrat/demo/faber_rebal.R
===================================================================
--- pkg/quantstrat/demo/faber_rebal.R	                        (rev 0)
+++ pkg/quantstrat/demo/faber_rebal.R	2012-11-22 02:05:41 UTC (rev 1260)
@@ -0,0 +1,176 @@
+# This is a very simple trend following strategy for testing the results of:
+# Faber, Mebane T., "A Quantitative Approach to Tactical Asset Allocation." 
+# Journal of Risk Management (Spring 2007).
+# The article proposes a very simple quantitative market-timing model.  They 
+# test the model in sample on the US stock market since 1900 before testing
+# it out-of-sample in twenty other markets.
+
+# The article discusses a 200-day simple moving average, which is proposed
+# in Jeremy Seigel's book "Stocks for the Long Run" for timing the DJIA.  He 
+# concludes that a simple market timing strategy improves the absolute and
+# risk adjusted returns over a buy-and-hold strategy.  After all transaction
+# costs are included, the timing strategy falls short on the absolute return,
+# but still provides a better risk-adjusted return.  Siegel also tests timing on  
+# the Nasdaq composite since 1972 and finds better absolute and risk adjusted
+# returns.
+
+# The article implements a simpler version of the 200-day SMA, opting for a
+# 10-month SMA.  Monthly data is more easily available for long periods of time,
+# and the lower granularity should translate to lower transaction costs.  
+
+# The rules of the system are relatively simple:
+# - Buy when monthly price > 10-month SMA
+# - Sell and move to cash when monthly price < 10-month SMA
+
+# 1. All entry and exit prices are on the day of the signal at the close.
+# 2. All data series are total return series including dividends, updated monthly. 
+#    For the purposes of this demo, we only use price returns.
+# 3. Cash returns are estimated with 90-day commercial paper.  Margin rates for
+#    leveraged models are estimated with the broker call rate.  Again, for the
+#    purposes of this demo, we ignore interest and leverage.
+# 4. Taxes, commissions, and slippage are excluded.
+
+# This simple strategy is different from well-known trend-following systems in
+# three respects.  First, there's no shorting.  Positions are converted to cash on
+# a 'sell' signal, rather than taking a short position. Second, the entire position
+# is put on at trade inception.  No assumptions are made about increasing position
+# size as the trend progresses.  Third, there are no stops.  If the trend reverts
+# quickly, this system will wait for a sell signal before selling the position.
+
+# Data
+# Instead of using total returns data, this demo uses monthly data for the SP500
+# downloaded from Yahoo Finance.  We'll use about 10 years of data, starting at 
+# the beginning of 1998.
+
+# Load required libraries
+require(quantstrat)
+
+# Try to clean up in case the demo was run previously
+suppressWarnings(rm("account.faber","portfolio.faber",pos=.blotter))
+suppressWarnings(rm("ltaccount", "ltportfolio", "ClosePrice", "CurrentDate", "equity", 
+            "GSPC", "stratFaber", "initDate", "initEq", "Posn", "UnitSize", "verbose"))
+suppressWarnings(rm("order_book.faber",pos=.strategy))
+
+# Set initial values
+initDate='1997-12-31'
+initEq=100000
+
+# Set up instruments with FinancialInstruments package
+currency("USD")
+symbols = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
+for(symbol in symbols){ # establish tradable instruments
+    stock(symbol, currency="USD",multiplier=1)
+}
+
+# Load data with quantmod
+#getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1998-01-01')
+### Download monthly data instead?
+### GSPC=to.monthly(GSPC, indexAt='endof')
+getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
+for(symbol in symbols) {
+    x<-get(symbol)
+    x<-to.monthly(x,indexAt='lastof',drop.time=TRUE)
+    indexFormat(x)<-'%Y-%m-%d'
+    colnames(x)<-gsub("x",symbol,colnames(x))
+    assign(symbol,x)
+}
+
+# Initialize portfolio and account
+initPortf('faber', symbols=symbols, initDate=initDate)
+initAcct('faber', portfolios='faber', initDate=initDate, initEq=100000)
+initOrders(portfolio='faber', initDate=initDate)
+
+# set intial position limits
+posval<-initEq/length(symbols)
+for(symbol in symbols){
+    pos<-round((posval/first(getPrice(get(symbol)))),-2)
+    addPosLimit('faber',symbol,initDate, maxpos=pos,minpos=-pos)
+}
+print("setup completed")
+
+# Initialize a strategy object
+strategy("faber", store=TRUE)
+
+# Add an indicator
+add.indicator('faber', name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
+
+# There are two signals:
+# The first is when monthly price crosses over the 10-month SMA
+add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="gte"),label="Cl.gt.SMA")
+# The second is when the monthly price crosses under the 10-month SMA
+add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")
+
+# There are two rules:
+# The first is to buy when the price crosses above the SMA
+add.rule('faber', name='ruleSignal', arguments = list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=100000, osFUN='osMaxPos', ordertype='market', orderside='long', pricemethod='market',TxnFees=-5), type='enter', path.dep=TRUE)
+# The second is to sell when the price crosses below the SMA
+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)
+
+# add quaterly rebalancing
+add.rule('faber', 'rulePctEquity',
+        arguments=list(rebalance_on='quarters',
+                trade.percent=1/length(symbols),
+                refprice=quote(last(getPrice(mktdata)[paste('::',timestamp,sep='')])),
+                digits=0
+        ),
+        type='rebalance',
+        label='rebalance'
+)
+
+# Process the strategy and generate trades
+start_t<-Sys.time()
+out<-applyStrategy.rebalancing(strategy='faber' , portfolios='faber')
+end_t<-Sys.time()
+print("Strategy Loop:")
+print(end_t-start_t)
+
+# look at the order book
+#print(getOrderBook('faber'))
+
+start_t<-Sys.time()
+updatePortf(Portfolio='faber',Dates=paste('::',as.Date(Sys.time()),sep=''))
+updateAcct('faber')
+end_t<-Sys.time()
+print("trade blotter portfolio update:")
+print(end_t-start_t)
+
+# hack for new quantmod graphics, remove later
+themelist<-chart_theme()
+themelist$col$up.col<-'lightgreen'
+themelist$col$dn.col<-'pink'
+
+dev.new()
+layout(mat=matrix(1:(length(symbols)+1),ncol=2))
+for(symbol in symbols){
+    chart.Posn(Portfolio='faber',Symbol=symbol,theme=themelist,TA="add_SMA(n=10,col='darkgreen')")
+}
+
+ret1 <- PortfReturns('faber')
+ret1$total<-rowSums(ret1)
+ret1
+
+if("package:PerformanceAnalytics" %in% search() || require("PerformanceAnalytics",quietly=TRUE)){
+	getSymbols("SPY", src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
+	SPY<-to.monthly(SPY)
+	SPY.ret<-Return.calculate(SPY$SPY.Close)
+	index(SPY.ret)<-index(ret1)
+	dev.new()
+	charts.PerformanceSummary(cbind(ret1$total,SPY.ret), geometric=FALSE, wealth.index=TRUE)
+}
+
+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')]
+faber.stats
+
+###############################################################################
+# R (http://r-project.org/) Quantitative Strategy Model Framework
+#
+# Copyright (c) 2009-2012
+# Peter Carl, Dirk Eddelbuettel, Brian G. Peterson,
+# Jeffrey Ryan, Joshua Ulrich, and Garrett See
+#
+# This library is distributed under the terms of the GNU Public License (GPL)
+# for full details see the file COPYING
+#
+# $Id$
+#
+###############################################################################


Property changes on: pkg/quantstrat/demo/faber_rebal.R
___________________________________________________________________
Added: svn:keywords
   + Id Date Author

Added: pkg/quantstrat/demo/macdRebalancing.R
===================================================================
--- pkg/quantstrat/demo/macdRebalancing.R	                        (rev 0)
+++ pkg/quantstrat/demo/macdRebalancing.R	2012-11-22 02:05:41 UTC (rev 1260)
@@ -0,0 +1,141 @@
+# Simple MACD strategy
+#
+# MACD may be used in many ways, this will demonstrate a trend indicator.
+# 
+# traditionally, when the MACD signal crosses zero, this indicated a establishment of a positive trend
+#
+# we'll buy on positive treshold crossover of the 'signal' column, and sell on negative threshold crossover
+# 
+# Author: brian
+###############################################################################
+
+
+require(quantstrat)
+suppressWarnings(rm("order_book.macd",pos=.strategy))
+suppressWarnings(rm("account.macd","portfolio.macd",pos=.blotter))
+suppressWarnings(rm("account.st","portfolio.st","stock.str","stratMACD","initDate","initEq",'start_t','end_t'))
+
+stock.str='AAPL' # what are we trying it on
+
+#MA parameters for MACD
+fastMA = 12 
+slowMA = 26 
+signalMA = 9
+maType="EMA"
+
+currency('USD')
+stock(stock.str,currency='USD',multiplier=1)
+
+#or use fake data
+#stock.str='sample_matrix' # what are we trying it on
+#data(sample_matrix)                 # data included in package xts
+#sample_matrix<-as.xts(sample_matrix)
+
+
+initDate='2006-12-31'
+initEq=1000000
+portfolio.st='macd'
+account.st='macd'
+
+initPortf(portfolio.st,symbols=stock.str, initDate=initDate)
+initAcct(account.st,portfolios=portfolio.st, initDate=initDate)
+initOrders(portfolio=portfolio.st,initDate=initDate)
+
+strat.st<-portfolio.st
+
+
+# define the strategy
+strategy(strat.st, store=TRUE)
+
+#one indicator
+add.indicator(strat.st, name = "MACD", arguments = list(x=quote(Cl(mktdata))) )
+
+#two signals
+add.signal(strat.st,name="sigThreshold",
+           arguments = list(column="signal",
+                            relationship="gt",
+                            threshold=0,
+                            cross=TRUE),
+           label="signal.gt.zero")
+
+add.signal(strat.st,name="sigThreshold",
+           arguments = list(column="signal",
+                            relationship="lt",
+                            threshold=0,
+                            cross=TRUE),
+           label="signal.lt.zero")
+
+####
+# add rules
+
+# entry
+add.rule(strat.st,name='ruleSignal', 
+         arguments = list(sigcol="signal.gt.zero",
+                          sigval=TRUE, orderqty=1000000, 
+                          ordertype='market', 
+                          orderside='long', 
+                          threshold=NULL,
+                          osFUN='osMaxPos'),
+         type='enter',
+         label='enter')
+
+#alternatives for risk stops:
+# simple stoplimit order, with threshold multiplier
+#add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty='all', ordertype='stoplimit', orderside='long', threshold=-.05,tmult=TRUE, orderset='exit2'),type='risk',label='risk',storefun=FALSE)
+# alternately, use a trailing order, also with a threshold multiplier
+#add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty='all', ordertype='stoptrailing', orderside='long', threshold=-.15,tmult=TRUE, orderset='exit2'),type='risk',label='trailingexit')
+
+# exit
+add.rule(strat.st,name='ruleSignal', 
+         arguments = list(sigcol="signal.lt.zero",
+                          sigval=TRUE, orderqty='all', 
+                          ordertype='market', 
+                          orderside='long', 
+                          threshold=NULL,
+                          orderset='exit2'),
+         type='exit',
+         label='exit')
+
+add.rule(strat.st, 'rulePctEquity',
+        arguments=list(rebalance_on='months',
+                       trade.percent=.02,
+                       refprice=quote(last(getPrice(mktdata)[paste('::',timestamp,sep='')])),
+                       digits=0
+        ),
+        type='rebalance',
+        label='rebalance'
+)
+
+#end rules
+####
+
+getSymbols(stock.str,from=initDate)
+start_t<-Sys.time()
+out<-applyStrategy.rebalancing(strat.st , portfolios=portfolio.st,parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType),verbose=TRUE)
+end_t<-Sys.time()
+print(end_t-start_t)
+
+start_t<-Sys.time()
+updatePortf(Portfolio=portfolio.st,Dates=paste('::',as.Date(Sys.time()),sep=''))
+end_t<-Sys.time()
+print("trade blotter portfolio update:")
+print(end_t-start_t)
+
+chart.Posn(Portfolio=portfolio.st,Symbol=stock.str)
+plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA"))
+
+#look at the order book
+getOrderBook('macd')
+
+###############################################################################
+# R (http://r-project.org/) Quantitative Strategy Model Framework
+#
+# Copyright (c) 2009-2012
+# Peter Carl, Dirk Eddelbuettel, Brian G. Peterson, Jeffrey Ryan, and Joshua Ulrich 
+#
+# This library is distributed under the terms of the GNU Public License (GPL)
+# for full details see the file COPYING
+#
+# $Id$
+#
+##############################################################################


Property changes on: pkg/quantstrat/demo/macdRebalancing.R
___________________________________________________________________
Added: svn:keywords
   + Id Date Author

Modified: pkg/quantstrat/man/apply.paramset.Rd
===================================================================
--- pkg/quantstrat/man/apply.paramset.Rd	2012-11-21 19:59:26 UTC (rev 1259)
+++ pkg/quantstrat/man/apply.paramset.Rd	2012-11-22 02:05:41 UTC (rev 1260)
@@ -2,7 +2,7 @@
 \alias{apply.paramset}
 \title{Apply a paramset to the strategy}
 \usage{
-  apply.paramset(strategy, paramset.label, portfolio.st,
+  apply.paramset(strategy.st, paramset.label, portfolio.st,
     nsamples = 0, verbose = FALSE)
 }
 \arguments{

Modified: pkg/quantstrat/man/ruleOrderProc.Rd
===================================================================
--- pkg/quantstrat/man/ruleOrderProc.Rd	2012-11-21 19:59:26 UTC (rev 1259)
+++ pkg/quantstrat/man/ruleOrderProc.Rd	2012-11-22 02:05:41 UTC (rev 1260)
@@ -3,7 +3,7 @@
 \title{process open orders at time \emph{t}, generating transactions or new orders}
 \usage{
   ruleOrderProc(portfolio, symbol, mktdata,
-    timespan = NULL, ordertype = NULL, ...,
+    timestamp = NULL, ordertype = NULL, ...,
     slippageFUN = NULL)
 }
 \arguments{
@@ -18,8 +18,8 @@
   depending on indicators, may need to be in OHLCV or BBO
   formats, default NULL}
 
-  \item{timespan}{xts-style character timespan to be the
-  period to find orders to process in}
+  \item{timestamp}{timestamp coercible to POSIXct that will
+  be the time the order will be processed on}
 
   \item{ordertype}{one of NULL,
   "market","limit","stoplimit", or "stoptrailing" default



More information about the Blotter-commits mailing list