Friday, April 25, 2014

Running backtesting with blotter in parallel

I was running backtestis with blotter package on many symbols and wanted to parallize the whole process with foreach loops.

Specifying portfolios inside the foreach loops like this:
.blotter <- new.env()
b.strategy <- paste(symbol, "strat", sep="_")
initPortf(b.strategy,symbol, initDate='2006-01-01')
initAcct(b.strategy,portfolios=b.strategy, initDate='2007-01-01', initEq=1e6)

Then running trough the data and adding transactions with:
        # enter long position
        addTxn(b.strategy, Symbol=symbol, TxnDate=CurrentDate,
               TxnPrice=ClosePrice, TxnQty = tradeSize , TxnFees=-1) 

It took some time to find out why I could not run updatePortf since it gave the error "object 'AAPL' not found".
Inside the loop I assigned the symbol with
assign(symbol, data)
Instead I needed to assign it with:
assign(symbol, data, envir=.GlobalEnv) since the parent frame to updatePortf inside the foreach loop is not the same as to assign and get.



Saturday, February 15, 2014

Wordcloud of tweets couple of hours after USA vs. Russia hockey game


Created with R from the twitter data-stream. Not quite possible to see who won from this data but one can see that there has been a hockey game and the most likely players were USA and Russia. 

Saturday, November 17, 2012

Some tips on backtesting in quantstrat


You might run into odd errors when backtesting strategies on tickers Ford (F) and ATT (T) in quantstrat. Since F is also reserved word False and T is shorthand for TRUE these ticker symbols will likely result in errors. Assigning F <- TRUE and T <- FALSE before backtesting will be a workaround as long as TRUE and FALSE is used elsewhere in the backtests.

Stoploss creation is a bit tricky. One has to use order-sets to get the exit orders cancelled once either target or stop is filled.

If you want to use limit orders you should use the "prefer" parameter to specify a column which contains the price for the limit order, "prefer" can be used for all columns in mktdata.


Canceling Limit orders in quantstrat

In quantstrat you might want to use Limit orders to avoid crossing the market. Since all orders in quantstrat are modeled as GTC orders the unfilled ones have to be cancelled once the conditions for placing them are not true anymore.
For that I made this function to cancel the orders https://r-forge.r-project.org/scm/viewvc.php/pkg/quantstrat/R/ruleCancel.R?view=markup&root=blotter&sortby=log&pathrev=1233

Speed performance considerations have to be taken into account because when using limit orders in quantstrat the signals are probably more often TRUE which causes more processing.


The code of ruleCancel.R:

#' rule to cancel an unfilled limit order on a signal
#' 
#' As described elsewhere in the documentation, quantstrat models 
#' \emph{orders}.  All orders in quantstrat are GTC orders, which means that
#' unfilled limit orders have to be cancelled manually or replaced by other orders.
#' 
#' This function is used for canceling the orders based on a signal.
#' 
#' @param data an xts object containing market data.  depending on rules, may need to be in OHLCV or BBO formats, and may include indicator and signal information
#' @param timestamp timestamp coercible to POSIXct that will be the time the order will be inserted on 
#' @param sigcol column name to check for signal
#' @param sigval signal value to match against
#' @param orderside one of either "long" or "short", default NULL, see details 
#' @param orderset tag to identify an orderset
#' @param portfolio text name of the portfolio to place orders in
#' @param symbol identifier of the instrument to cancel orders for
#' @param ruletype must be 'risk' for ruleCancel, see \code{\link{add.rule}}
#' @author Niklas Kolster
#' @seealso \code{\link{osNoOp}} , \code{\link{add.rule}}
#' @export
ruleCancel <- function(data=mktdata, timestamp, sigcol, sigval, orderside=NULL, orderset=NULL, portfolio, symbol, ruletype)
{
 

  if (ruletype!='risk') {
    stop(paste('Ruletype can only be risk'))
  }
  
  if(is.null(orderset)) orderset=NA
    
  updateOrder(portfolio=portfolio, 
              symbol=symbol, 
              timespan=timespan,
              orderset=orderset, 
              newstatus='canceled'
             )
  
}

###############################################################################
# R (http://r-project.org/) Quantitative Strategy Model Framework
#
# Copyright (c) 2012
# Niklas Kolster
#
# This library is distributed under the terms of the GNU Public License (GPL)
# for full details see the file COPYING
#
# $Id$
#
###############################################################################






Monday, November 5, 2012

How to calculate higher timeframe indicators on xts data


Sometimes you have higher frequency data and you need to get a slower timeframe analysis, it can be accomplished with this undocumented but real powerful feature of by.period:

getSymbols("SPY", src="yahoo")
SPY$wklyRSI <- xts:::by.period(SPY, RSI, period="weeks", n=2)


Tuesday, September 25, 2012

Quantstrat signals and indicators

In the pairtrading demo in quantstrat R package the signals are added like this: 


pairStrat <- add.signal(strategy = pairStrat, name = "sigCrossover", arguments= list(columns=c("Ratio","BBands.up"), relationship="lt"), label="cross.up") 


This line above means the Ratio is crossing down below the upper Bollinger band. This means that the first provided column is less than the second after the crossing. 

The indicators are usually from the TTR package and can be looked up there for more info on how to use them.