[Blotter-commits] r220 - pkg/blotter/demo

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Sat Jan 30 14:30:29 CET 2010


Author: braverock
Date: 2010-01-30 14:30:29 +0100 (Sat, 30 Jan 2010)
New Revision: 220

Modified:
   pkg/blotter/demo/longtrend.R
   pkg/blotter/demo/turtles.R
Log:
- make turtles demo work with new code (environments)
- update variable names for fewer side effects

Modified: pkg/blotter/demo/longtrend.R
===================================================================
--- pkg/blotter/demo/longtrend.R	2010-01-29 21:12:16 UTC (rev 219)
+++ pkg/blotter/demo/longtrend.R	2010-01-30 13:30:29 UTC (rev 220)
@@ -48,7 +48,8 @@
 require(blotter)
 
 # Try to clean up in case the demo was run previously
-try(rm("account.longtrend","portfolio.longtrend",pos=.blotter))
+try(rm("account.longtrend","portfolio.longtrend",pos=.blotter),silent=TRUE)
+try(rm("ltaccount","ltportfolio","ClosePrice","CurrentDate","equity","GSPC","i","initDate","initEq","Posn","UnitSize","verbose"),silent=TRUE)
 
 
 # Set initial values
@@ -68,10 +69,10 @@
 
 # Set up a portfolio object and an account object in blotter
 print("Initializing portfolio and account structure")
-portfolio='longtrend'
-account='longtrend'
-initPortf(portfolio,'GSPC', initDate=initDate)
-initAcct(account,portfolios='longtrend', initDate=initDate)
+ltportfolio='longtrend'
+ltaccount='longtrend'
+initPortf(ltportfolio,'GSPC', initDate=initDate)
+initAcct(ltaccount,portfolios='longtrend', initDate=initDate)
 verbose=TRUE
 
 # Create trades
@@ -79,10 +80,10 @@
     # browser()
     CurrentDate=time(GSPC)[i]
     cat(".")
-    equity = getEndEq(account, CurrentDate)
+    equity = getEndEq(ltaccount, CurrentDate)
 
     ClosePrice = as.numeric(Ad(GSPC[i,]))
-    Posn = getPosQty(portfolio, Symbol='GSPC', Date=CurrentDate)
+    Posn = getPosQty(ltportfolio, Symbol='GSPC', Date=CurrentDate)
     UnitSize = as.numeric(trunc(equity/ClosePrice))
 
     # Position Entry (assume fill at close)
@@ -91,34 +92,34 @@
         if( as.numeric(Ad(GSPC[i,])) > as.numeric(GSPC[i,'SMA10m']) ) { 
             cat('\n')
             # Store trade with blotter
-            addTxn(portfolio, Symbol='GSPC', TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = UnitSize , TxnFees=0, verbose=verbose)
+            addTxn(ltportfolio, Symbol='GSPC', TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = UnitSize , TxnFees=0, verbose=verbose)
         } 
     } else {
     # Have a position, so check exit
         if( as.numeric(Ad(GSPC[i,]))  <  as.numeric(GSPC[i,'SMA10m'])) { 
             cat('\n')
             # Store trade with blotter
-            addTxn(portfolio, Symbol='GSPC', TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = -Posn , TxnFees=0, verbose=verbose)
+            addTxn(ltportfolio, Symbol='GSPC', TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = -Posn , TxnFees=0, verbose=verbose)
         } 
     }
 
     # Calculate P&L and resulting equity with blotter
-    updatePortf(portfolio, Dates = CurrentDate)
-    updateAcct(account, Dates = CurrentDate)
-    updateEndEq(account, Dates = CurrentDate)
+    updatePortf(ltportfolio, Dates = CurrentDate)
+    updateAcct(ltaccount, Dates = CurrentDate)
+    updateEndEq(ltaccount, Dates = CurrentDate)
 } # End dates loop
 cat('\n')
 
 # Chart results with quantmod
-chart.Posn(portfolio, Symbol = 'GSPC', Dates = '1998::', theme=chartTheme('white',up.col='lightgreen',dn.col='pink'), type='bar')
-plot(addTA(GSPC$SMA10['1998::',],pch=1,type='l',col='darkgreen', on=1))
+chart.Posn(ltportfolio, Symbol = 'GSPC', Dates = '1998::',theme='white')
+plot(addSMA(n=10,col='darkgreen', on=1))
 
 getTxns(Portfolio="longtrend", Symbol="GSPC", Date="2000::2004")
 
 # Copy the results into the local environment
 print("Retrieving resulting portfolio and account")
-portfolio = getPortfolio("longtrend")
-account = getAccount("longtrend")
+ltportfolio = getPortfolio("longtrend")
+ltaccount = getAccount("longtrend")
 
 ###############################################################################
 # Blotter: Tools for transaction-oriented trading systems development

Modified: pkg/blotter/demo/turtles.R
===================================================================
--- pkg/blotter/demo/turtles.R	2010-01-29 21:12:16 UTC (rev 219)
+++ pkg/blotter/demo/turtles.R	2010-01-30 13:30:29 UTC (rev 220)
@@ -16,12 +16,12 @@
 
     # FUNCTION
     # Store the transaction and calculations, returns the portfolio
-    
+    pname=Portfolio
     NewTxn = xts(t(c(PosUnitsQty, UnitSize, StopPrice, TxnPrice, TxnN)), order.by=as.POSIXct(TxnDate))
     colnames(NewTxn) = c('Pos.Units', 'Unit.Size', 'Stop.Price', 'Txn.Price', 'Txn.N')
+    Portfolio<-getPortfolio(Portfolio)
     Portfolio[[Symbol]]$strat <- rbind(Portfolio[[Symbol]]$strat, NewTxn)
-    return(Portfolio)
-
+    assign( paste("portfolio",pname,sep='.'), Portfolio, envir=.blotter )
 }
 
 # - Turtle System #1
@@ -37,21 +37,31 @@
 print("Initializing portfolio and account structure")
 # Assemble a small portfolio of three stocks
 symbols = c("XLF", "XLP", "XLE")#, "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
+currency("USD")
+for(symbol in symbols){
+    stock(symbol, currency="USD",multiplier=1)
+}
 
 getSymbols(symbols, index.class="POSIXct", from=initDate, source="yahoo")
 # getSymbols now defaults (as originally) to "Date" indexing.  We can change to use POSIXct here.
 # getSymbols(symbols, index.class=c("POSIXt","POSIXct"), from=initDate, source="yahoo")
 
 # Set up a portfolio object and an account object
-portfolio = initPortf(symbols, initDate=initDate)
-account = initAcct(portfolios="portfolio", initDate=initDate)
+portfolio = "turtles" 
+initPortf(name=portfolio,symbols, initDate=initDate)
+account = "turtles"
+initAcct(name=account,portfolios="turtles", initDate=initDate)
 
 # This table stores transaction-related information relative to the strategy
 # Placing it into the portfolio object, sure why not?
+Portfolio<-getPortfolio(portfolio)
 for(symbol in symbols){
-  portfolio[[symbol]]$strat <- xts( as.matrix(t(c(0,0,0,0,0))), order.by=as.POSIXct(initDate) )
-  colnames(portfolio[[symbol]]$strat) <- c('Pos.Units', 'Unit.Size', 'Stop.Price', 'Txn.Price', 'Txn.N')
+  Portfolio[[symbol]]$strat <- xts( as.matrix(t(c(0,0,0,0,0))), order.by=as.POSIXct(initDate) )
+  colnames(Portfolio[[symbol]]$strat) <- c('Pos.Units', 'Unit.Size', 'Stop.Price', 'Txn.Price', 'Txn.N')
 }
+# now put it back where it belongs
+assign( "portfolio.turtles", Portfolio , envir=.blotter )
+rm("Portfolio")
 
 # @todo: decrease the size of the notional account by 20% each time lose 10% of original account (10% drawdown).  E.g., if trading a $1M account and down 100K, trade as if $800K account until out of drawdown.  If lose another 10% from 800K, or 80K loss, then reduce account size another 20% for notional size of 640K.
 
@@ -104,7 +114,7 @@
     ClosePrice = as.numeric(Cl(x[i,]))
 
     Posn = getPosQty(Portfolio=portfolio, Symbol=symbol, Date=CurrentDate)
-    s = tail(portfolio[[symbol]]$strat,1)
+    s = tail(getPortfolio(portfolio)[[symbol]]$strat,1)
 #      print(s)
     Units = as.numeric(s[,'Pos.Units'])
     TxnPrice = as.numeric(s[,'Txn.Price'])
@@ -117,52 +127,53 @@
     if( Posn == 0 ) { 
       # Initiate Long position
       if( as.numeric(Hi(x[i-1,])) > as.numeric(x[i-2,'Max55']) ) { 
-        portfolio = addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = UnitSize , TxnFees=0, verbose=verbose)
+        addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = UnitSize , TxnFees=0, verbose=verbose)
         N = as.numeric(x[i-1,'N'])
-        portfolio = updateStrat(Portfolio=portfolio, Symbol=symbol, TxnDate = CurrentDate, PosUnitsQty = 1, UnitSize = UnitSize, StopPrice = (ClosePrice-2*N), TxnPrice = ClosePrice, TxnN = N)
+        updateStrat(Portfolio=portfolio, Symbol=symbol, TxnDate = CurrentDate, PosUnitsQty = 1, UnitSize = UnitSize, StopPrice = (ClosePrice-2*N), TxnPrice = ClosePrice, TxnN = N)
       } else
       # Initiate Short position
       if( as.numeric(Lo(x[i-1,]))  < as.numeric(x[i-2,'Min55']) ) { 
-        portfolio = addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = -UnitSize , TxnFees=0, verbose=verbose)
+        addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = -UnitSize , TxnFees=0, verbose=verbose)
         N = as.numeric(x[i-1,'N'])
-        portfolio = updateStrat(Portfolio=portfolio, Symbol = symbol, TxnDate = CurrentDate, PosUnitsQty = Units, UnitSize = UnitSize, StopPrice = (ClosePrice +2*N), TxnPrice = ClosePrice, TxnN = N)
+        updateStrat(Portfolio=portfolio, Symbol = symbol, TxnDate = CurrentDate, PosUnitsQty = Units, UnitSize = UnitSize, StopPrice = (ClosePrice +2*N), TxnPrice = ClosePrice, TxnN = N)
       }
     } else
     # Position exits and stops
     if( ( Posn > 0 && ( as.numeric(Lo(x[i-1,]))  <  as.numeric(x[i-2,'Min20']) || Lo(x[i-1,])  < Stop ) ) || 
         ( Posn < 0 && ( as.numeric(Hi(x[i-1,])) > as.numeric(x[i-2,'Max20']) || Hi(x[i-1,]) > Stop ) ) ) {
-        portfolio = addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = -Posn , TxnFees=0, verbose=verbose)
+        addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = -Posn , TxnFees=0, verbose=verbose)
         N = as.numeric(x[i-1,'N'])
-        portfolio = updateStrat(Portfolio = portfolio, Symbol = symbol, TxnDate = CurrentDate, PosUnitsQty = 0, UnitSize = UnitSize, StopPrice = NA, TxnPrice = ClosePrice, TxnN = N)
+        updateStrat(Portfolio = portfolio, Symbol = symbol, TxnDate = CurrentDate, PosUnitsQty = 0, UnitSize = UnitSize, StopPrice = NA, TxnPrice = ClosePrice, TxnN = N)
     } else
     # Add to long position
 	if( Posn > 0  && Units < maxUnits && Hi(x[i-1,]) > ( TxnPrice + N * 0.5 ) ) {
-	  portfolio = addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = UnitSize , TxnFees=0, verbose=verbose)
+	  addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=ClosePrice, TxnQty = UnitSize , TxnFees=0, verbose=verbose)
 	  N = as.numeric(x[i-1,'N'])
-	  portfolio = updateStrat(Portfolio = portfolio, Symbol = symbol, TxnDate = CurrentDate, PosUnitsQty = Units+1, UnitSize = UnitSize, StopPrice = (ClosePrice-2*N), TxnPrice = ClosePrice, TxnN = N)
+	  updateStrat(Portfolio = portfolio, Symbol = symbol, TxnDate = CurrentDate, PosUnitsQty = Units+1, UnitSize = UnitSize, StopPrice = (ClosePrice-2*N), TxnPrice = ClosePrice, TxnN = N)
     } else
     # Add to short position
 	if( Posn < 0 && Units < maxUnits && Lo(x[i-1,])  < ( TxnPrice - N * 0.5 ) ) {
-	  portfolio = addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=Cl(x[i,]), TxnQty = -UnitSize , TxnFees=0, verbose=verbose)
+	  addTxn(Portfolio=portfolio, Symbol=symbol, TxnDate=CurrentDate, TxnPrice=Cl(x[i,]), TxnQty = -UnitSize , TxnFees=0, verbose=verbose)
 	  N = as.numeric(x[i-1,'N'])
-	  portfolio = updateStrat(Portfolio=portfolio, Symbol=symbol, TxnDate = CurrentDate, PosUnitsQty = Units+1, UnitSize = UnitSize, StopPrice = (ClosePrice+2*N), TxnPrice = ClosePrice, TxnN = N)
+	  updateStrat(Portfolio=portfolio, Symbol=symbol, TxnDate = CurrentDate, PosUnitsQty = Units+1, UnitSize = UnitSize, StopPrice = (ClosePrice+2*N), TxnPrice = ClosePrice, TxnN = N)
     } #else
     # Maintain Position
   } # End symbol loop
   # Now that we've updated all of our trades, its time to mark the book
-  portfolio = updatePortf(Portfolio = portfolio, Dates = CurrentDate)
-  account = updateAcct(Account = account, Dates = CurrentDate)
-  account = updateEndEq(Account = account, Dates = CurrentDate)
+  updatePortf(Portfolio = portfolio, Dates = CurrentDate)
+  updateAcct(account, Dates = CurrentDate)
+  updateEndEq(account, Dates = CurrentDate)
 } # End dates loop
 
 # Final values
 cat('Return: ',(getEndEq(Account=account, Date=CurrentDate)-initEq)/initEq,'\n')
 
 if (require(quantmod)) {
-  Buys = portfolio[["XLF"]]$txn$Txn.Price*(portfolio[["XLF"]]$txn[,'Txn.Qty']>0)
-  Sells = portfolio[["XLF"]]$txn$Txn.Price*(portfolio[["XLF"]]$txn[,'Txn.Qty']<0)
-  Position = portfolio[["XLF"]]$posPL[,'Pos.Qty']
-  CumPL = cumsum(portfolio[["XLF"]]$posPL[,'Trading.PL'])
+  Portfolio<-getPortfolio(portfolio)  
+  Buys = Portfolio[["XLF"]]$txn$Txn.Price*(Portfolio[["XLF"]]$txn[,'Txn.Qty']>0)
+  Sells = Portfolio[["XLF"]]$txn$Txn.Price*(Portfolio[["XLF"]]$txn[,'Txn.Qty']<0)
+  Position = Portfolio[["XLF"]]$posPL[,'Pos.Qty']
+  CumPL = cumsum(Portfolio[["XLF"]]$posPL[,'Trading.PL'])
   chartSeries(XLF['2008::2009',], TA=NULL, type='bar', theme=chartTheme('white',up.col='lightgreen',dn.col='pink'))
   plot(addTA(Buys['2008::2009',],pch=2,type='p',col='darkgreen', on=1));
   plot(addTA(Sells['2008::2009',],pch=6,type='p',col='darkred', on=1));
@@ -170,6 +181,7 @@
   plot(addTA(CumPL['2008::2009',], col='darkgreen', lwd=2))
 }
 
-# require(PerformanceAnalytics)
-# return = Delt(account[["TOTAL"]]$End.Eq)
-# charts.PerformanceSummary(as.zoo(return))
+if(require(PerformanceAnalytics)){
+    return = Delt(getAccount(account)[["TOTAL"]]$End.Eq)
+    charts.PerformanceSummary(as.zoo(return),main="Turtle Demo Performance")   
+}



More information about the Blotter-commits mailing list