[Blotter-commits] r1516 - pkg/quantstrat/R

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Thu Oct 3 22:09:08 CEST 2013


Author: braverock
Date: 2013-10-03 22:09:08 +0200 (Thu, 03 Oct 2013)
New Revision: 1516

Modified:
   pkg/quantstrat/R/applyStrategy.rebalancing.R
   pkg/quantstrat/R/orders.R
   pkg/quantstrat/R/osFUNs.R
   pkg/quantstrat/R/rebalance.rules.R
   pkg/quantstrat/R/ruleOrderProc.R
   pkg/quantstrat/R/ruleSignal.R
Log:
- changes to be more robust to multiple columns returned by getPrice
- updates to fix rebalancing code


Modified: pkg/quantstrat/R/applyStrategy.rebalancing.R
===================================================================
--- pkg/quantstrat/R/applyStrategy.rebalancing.R	2013-10-03 08:11:20 UTC (rev 1515)
+++ pkg/quantstrat/R/applyStrategy.rebalancing.R	2013-10-03 20:09:08 UTC (rev 1516)
@@ -130,7 +130,8 @@
         
         #now we need to do the endpoints loop. 
         for(i in 2:length(pindex)){
-            #the proper endpoints for each symbol will vary, so we need to get them separately, and subset each one
+            #the proper endpoints for each symbol will vary, so we need to get
+            #them separately, and subset each one
             for (symbol in symbols){
                 #sret<-ret[[portfolio]][[symbol]]
                 mktdata<-get(symbol,pos=st)
@@ -138,11 +139,20 @@
                 md_subset<-mktdata[as.POSIXct(index(mktdata))>pindex[i-1]&as.POSIXct(index(mktdata))<=pindex[i]]
                 if(nrow(md_subset)<1) {
                     next()
-                } else{
+                } else {
                     #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

Modified: pkg/quantstrat/R/orders.R
===================================================================
--- pkg/quantstrat/R/orders.R	2013-10-03 08:11:20 UTC (rev 1515)
+++ pkg/quantstrat/R/orders.R	2013-10-03 20:09:08 UTC (rev 1516)
@@ -10,16 +10,16 @@
 #' 
 #' \describe{
 #'      \item{Order.Qty}{}
-#' 		\item{Order.Price}{}
-#' 		\item{Order.Type}{}
-#' 		\item{Order.Side}{}
-#' 		\item{Order.Threshold}{}
-#' 		\item{Order.Status}{}
-#' 		\item{Order.StatusTime}{}
-#' 		\item{Prefer}{}
-#' 		\item{Order.Set}{}
-#' 		\item{Txn.Fees}{}
-#' 		\item{Rule}{}
+#'     \item{Order.Price}{}
+#'     \item{Order.Type}{}
+#'     \item{Order.Side}{}
+#'     \item{Order.Threshold}{}
+#'     \item{Order.Status}{}
+#'     \item{Order.StatusTime}{}
+#'     \item{Prefer}{}
+#'     \item{Order.Set}{}
+#'     \item{Txn.Fees}{}
+#'     \item{Rule}{}
 #' }   
 #' @aliases
 #' get.orderbook
@@ -271,8 +271,8 @@
                      ..., 
                      TxnFees=0,
                      label='',
-		     time.in.force=''
-             )
+                     time.in.force=''
+)
 {
     # get order book
     #orderbook <- getOrderBook(portfolio)
@@ -371,7 +371,8 @@
                 time.in.force <- timestamp + time.in.force
 
             time.in.force <- format(time.in.force, "%Y-%m-%d %H:%M:%0S")
-	}
+            #TODO FIXME this line probably needs to be sensitive to the index of the market data, Date vs POSIXct
+  }
     }
 
     #set up the other parameters

Modified: pkg/quantstrat/R/osFUNs.R
===================================================================
--- pkg/quantstrat/R/osFUNs.R	2013-10-03 08:11:20 UTC (rev 1515)
+++ pkg/quantstrat/R/osFUNs.R	2013-10-03 20:09:08 UTC (rev 1516)
@@ -50,9 +50,16 @@
 addPosLimit <- function (portfolio, symbol, timestamp, maxpos, longlevels = 1, minpos = -maxpos, shortlevels = longlevels) 
 {
 	portf <- getPortfolio(portfolio)
+  #catch error where maxpos/minpos have length greater than 1
+	if(length(maxpos)>1) maxpos <- maxpos[,1]
+	if(length(minpos)>1) minpos <- minpos[,1]
 	newrow <- xts(cbind(maxpos, longlevels, minpos, shortlevels), order.by = as.POSIXct(timestamp))
-	colnames(newrow) <- c("MaxPos", "LongLevels", "MinPos", "ShortLevels")
-	
+	tc <- try(colnames(newrow) <- c("MaxPos", "LongLevels", "MinPos", "ShortLevels"))
+# 	if(inherits(tc, 'try-error')) {
+#     print(symbol)
+#     print(newrow)
+#     browser()
+# 	}
 	if (is.null(portf$symbols[[symbol]]$PosLimit)) {
 		portf$symbols[[symbol]]$PosLimit <- newrow
 	} else {

Modified: pkg/quantstrat/R/rebalance.rules.R
===================================================================
--- pkg/quantstrat/R/rebalance.rules.R	2013-10-03 08:11:20 UTC (rev 1515)
+++ pkg/quantstrat/R/rebalance.rules.R	2013-10-03 20:09:08 UTC (rev 1516)
@@ -30,7 +30,7 @@
 #' add.rule(strategy.name, 'rulePctEquity',
 #'         arguments=list(rebalance_on='months',
 #'                        trade.percent=.02,
-#'                        refprice=quote(last(getPrice(mktdata)[paste('::',timestamp,sep='')])),
+#'                        refprice=quote(last(getPrice(mktdata)[paste('::',timestamp,sep='')])[,1]),
 #'                        digits=0
 #'         ),
 #'         type='rebalance',
@@ -52,6 +52,7 @@
     trading.pl <- sum(getPortfolio(portfolio)$summary$Net.Trading.PL)
     total.equity <- initEq+trading.pl
     tradeSize <- total.equity * trade.percent
+    if(length(refprice)>1) refprice <- refprice[,1]
     if(!is.null(refprice)) tradeSize <- tradeSize/refprice
     if(!is.null(digits)) tradeSize<-round(tradeSize,digits)
     addPosLimit(portfolio = portfolio, 

Modified: pkg/quantstrat/R/ruleOrderProc.R
===================================================================
--- pkg/quantstrat/R/ruleOrderProc.R	2013-10-03 08:11:20 UTC (rev 1515)
+++ pkg/quantstrat/R/ruleOrderProc.R	2013-10-03 20:09:08 UTC (rev 1516)
@@ -176,7 +176,7 @@
                  if((orderQty > 0 && orderType != 'stoplimit') || (orderQty < 0 && (orderType=='stoplimit'))) {
                    # buy limit, or sell stoplimit
                    if( (has.Lo(mktdata) && orderPrice > as.numeric(Lo(mktdataTimestamp))) || 
-                         (!has.Lo(mktdata) && orderPrice > as.numeric(getPrice(mktdataTimestamp, prefer=prefer))))
+                         (!has.Lo(mktdata) && orderPrice > as.numeric(getPrice(mktdataTimestamp, prefer=prefer)[,1])))
                    {
                      txnprice = min(orderPrice, Hi(mktdataTimestamp))
                      txntime = timestamp
@@ -184,7 +184,7 @@
                  } else if((orderQty < 0 && orderType != 'stoplimit') || (orderQty > 0 && (orderType=='stoplimit'))) { 
                    # sell limit or buy stoplimit
                    if ( (has.Hi(mktdata) && orderPrice < as.numeric(Hi(mktdataTimestamp))) ||
-                          (!has.Hi(mktdata) && orderPrice < as.numeric(getPrice(mktdataTimestamp,prefer=prefer))) )
+                          (!has.Hi(mktdata) && orderPrice < as.numeric(getPrice(mktdataTimestamp,prefer=prefer)[,1])) )
                    {
                      txnprice = max(orderPrice, Lo(mktdataTimestamp))
                      txntime = timestamp

Modified: pkg/quantstrat/R/ruleSignal.R
===================================================================
--- pkg/quantstrat/R/ruleSignal.R	2013-10-03 08:11:20 UTC (rev 1515)
+++ pkg/quantstrat/R/ruleSignal.R	2013-10-03 20:09:08 UTC (rev 1516)
@@ -140,7 +140,7 @@
 				else
 				    prefer='bid'  # we're selling, so give it to them for what they're bidding  
 			    } 
-			    orderprice <- try(getPrice(x=mktdata, prefer=prefer))[timestamp] 
+			    orderprice <- try(getPrice(x=mktdata, prefer=prefer)[,1][timestamp]) 
 			},
 			passive =,
 			work =,
@@ -151,7 +151,7 @@
 				else
 				    prefer='ask'  # we're selling, so work the ask price
 			    }
-			    orderprice <- try(getPrice(x=mktdata, prefer=prefer))[timestamp]
+			    orderprice <- try(getPrice(x=mktdata, prefer=prefer)[,1][timestamp])
 			},
 			maker = {
 			    if(hasArg(price) & length(match.call(expand.dots=TRUE)$price)>1) {
@@ -159,9 +159,9 @@
 				orderprice <- try(match.call(expand.dots=TRUE)$price)
 			    } else {
 				if(!is.null(threshold)) {
-				    baseprice<- last(getPrice(x=mktdata)[timestamp]) # this should get either the last trade price or the Close
+				    baseprice<- last(getPrice(x=mktdata)[,1][timestamp]) # this should get either the last trade price or the Close
 				    if(hasArg(tmult) & isTRUE(match.call(expand.dots=TRUE)$tmult)) {
-					baseprice<- last(getPrice(x=mktdata)[timestamp]) # this should get either the last trade price or the Close
+					baseprice<- last(getPrice(x=mktdata)[,1][timestamp]) # this should get either the last trade price or the Close
 					# threshold is a multiplier of current price
 					if (length(threshold)>1){
 					    orderprice <- baseprice * threshold # assume the user has set proper threshold multipliers for each side



More information about the Blotter-commits mailing list