8.2 Blotter Package

Since working through quanstrat package requires the blotter package, which is rather complicated, we demostrate first how the blotter pacakge works first.

As we have seen, recording tranasction of stocks, keeping track of cash and stock holding, and evaluate return is rather messy. The blotter package is mainly for this purpose.

We first need to setup the working space.

We need to setup the currency and declare the data is the stock (using FinancialInstrument package).

The multipler is always one for stock, and currency is USD for US stock.

options("getSymbols.warning4.0"=FALSE)
from ="2008-01-01"
to ="2012-12-31"
symbols = c("AAPL", "IBM")
currency("USD")
getSymbols(symbols, from=from, to=to, 
           adjust=TRUE)
stock(symbols, currency="USD", multiplier=1)
initEq=10^6

To start, we initialize account and portfolio where:

  • Porfolio: stores which stocks to be traded

  • Account: stores which money transactions

rm("account.buyHold",pos=.blotter)
rm("portfolio.buyHold",pos=.blotter)

initPortf("buyHold", symbol=symbols)
initAcct("buyHold", portfolios = "buyHold",
         initEq = initEq)

8.2.1 Buy and hold

To illustrate, we just consider buy and hold strategy:

  • Buy on the first day at closing price
  • Sell on the last day at closing price

We first get the price and timing data:

Apple.Buy.Date <- first(time(AAPL))
Apple.Buy.Price <- as.numeric(Cl(AAPL[Apple.Buy.Date,]))
Apple.Sell.Date <- last(time(AAPL))
Apple.Sell.Price <- as.numeric(Cl(AAPL[Apple.Sell.Date,]))
Apple.Qty <- trunc(initEq/(2*Apple.Buy.Price))

IBM.Buy.Date <- first(time(IBM))
IBM.Buy.Price <- as.numeric(Cl(IBM[IBM.Buy.Date,]))
IBM.Sell.Date <- last(time(IBM))
IBM.Sell.Price <- as.numeric(Cl(IBM[IBM.Sell.Date,]))
IBM.Qty <- trunc(initEq/(2*IBM.Buy.Price))

We first add buy transactions to the system using the function addTxn:

addTxn(Portfolio = "buyHold", 
       Symbol = "AAPL", 
       TxnDate = Apple.Buy.Date, 
       TxnQty = Apple.Qty,
       TxnPrice = Apple.Buy.Price,
       TxnFees = 0)

addTxn(Portfolio = "buyHold", 
       Symbol = "IBM", 
       TxnDate = IBM.Buy.Date, 
       TxnQty = IBM.Qty,
       TxnPrice = IBM.Buy.Price,
       TxnFees = 0)

Then we add the sell transactions:

addTxn(Portfolio = "buyHold", 
       Symbol = "AAPL", 
       TxnDate = Apple.Sell.Date, 
       TxnQty = -Apple.Qty,
       TxnPrice = Apple.Sell.Price,
       TxnFees = 0)

addTxn(Portfolio = "buyHold", 
       Symbol = "IBM", 
       TxnDate = IBM.Sell.Date, 
       TxnQty = -IBM.Qty,
       TxnPrice = IBM.Sell.Price,
       TxnFees = 0)

Now we can update the account based on the added transactions:

updatePortf(Portfolio = "buyHold")
## [1] "buyHold"
updateAcct(name = "buyHold")
## [1] "buyHold"
updateEndEq(Account = "buyHold")
## [1] "buyHold"

We can chart our trading positions:

chart.Posn("buyHold", Symbol = "AAPL")

chart.Posn("buyHold", Symbol = "IBM")

We can see the trading statistics

out <- perTradeStats("buyHold", "IBM")
t(out)
##                     [,1]                 
## Start               "2008-01-02 08:00:00"
## End                 "2012-12-28 08:00:00"
## Init.Qty            "5223"               
## Init.Pos            "5223"               
## Max.Pos             "5223"               
## End.Pos             "0"                  
## Closing.Txn.Qty     "-5223"              
## Num.Txns            "2"                  
## Max.Notional.Cost   "499963.2"           
## Net.Trading.PL      "491518.9"           
## MAE                 "-151359.1"          
## MFE                 "597287.7"           
## Pct.Net.Trading.PL  "0.98311"            
## Pct.MAE             "-0.3027405"         
## Pct.MFE             "1.194663"           
## tick.Net.Trading.PL "9410.662"           
## tick.MAE            "-15135911"          
## tick.MFE            "59728767"           
## duration            "157420800 secs"
out <- perTradeStats("buyHold", "AAPL")
t(out)
##                     [,1]                 
## Start               "2008-01-02 08:00:00"
## End                 "2012-12-28 08:00:00"
## Init.Qty            "19126"              
## Init.Pos            "19126"              
## Max.Pos             "19126"              
## End.Pos             "0"                  
## Closing.Txn.Qty     "-19126"             
## Num.Txns            "2"                  
## Max.Notional.Cost   "499991.1"           
## Net.Trading.PL      "892354.3"           
## MAE                 "-299317.2"          
## MFE                 "1357293"            
## Pct.Net.Trading.PL  "1.78474"            
## Pct.MAE             "-0.598645"          
## Pct.MFE             "2.714634"           
## tick.Net.Trading.PL "4665.661"           
## tick.MAE            "-29931721"          
## tick.MFE            "135729299"          
## duration            "157420800 secs"

8.2.2 Buy Filter Rule

We use blotter package to apply simple filter rule

  • buy 1000 units signal if buy signal

  • hold otherwise

We first Download Data:

from ="2009-01-01"
to ="2012-12-31"
symbols = c("MSFT")
currency("USD")
getSymbols(symbols, from=from, to=to, 
           adjust=TRUE)
stock(symbols, currency="USD", multiplier=1)
initEq=10^6

Then setup the account and portfolio:

rm("account.filter",pos=.blotter)
rm("portfolio.filter",pos=.blotter)

initPortf("filter", symbol=symbols)
initAcct("filter", portfolios = "filter",
         initEq = initEq)

Here we generate trading indicator:

price <- Cl(MSFT)         
r <- price/Lag(price) - 1    
delta<-0.03
signal <-c(NA)
for (i in 2: length(price)){
    if (r[i] > delta){
         signal[i]<- 1
    } else if (r[i]< -delta){
         signal[i]<- -1
    } else
         signal[i]<- 0
}
signal<-reclass(signal,Cl(MSFT))

This convert trading indicator to trading signal:

trade <- Lag(signal)
trade <- na.fill(trade,0)

Now we are ready to apply trading signal into trading action:

for (i in 1:length(price)){
  if (as.numeric(trade[i]) == 1){
    addTxn(Portfolio = "filter",
           Symbol = "MSFT", 
           TxnDate = time(price[i]), 
           TxnQty = 1000,
           TxnPrice = price[i],
           TxnFees = 0)    
  }
    if (as.numeric(trade[i]) == -1){
    addTxn(Portfolio = "filter",
           Symbol = "MSFT", 
           TxnDate = time(price[i]), 
           TxnQty = -1000,
           TxnPrice = price[i],
           TxnFees = 0)    
  }
}

Finally, we update the account and do charting:

updatePortf(Portfolio = "filter")
updateAcct(name = "filter")
updateEndEq(Account = "filter")
chart.Posn("filter", Symbol = "MSFT")