[R-SIG-Finance] Problems using blotter and R-2.15

Joshua Ulrich josh.m.ulrich at gmail.com
Sat Jun 2 22:58:27 CEST 2012


Hi Felice,

I was able to run the code you provided below without error.  What
versions of blotter / xts are you using?  Upgrading may help; if it
does not, please provide the output from sessionInfo().  My output is
below.

Best,
--
Joshua Ulrich  |  FOSS Trading: www.fosstrading.com


R> sessionInfo()
R version 2.15.0 (2012-03-30)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=C                 LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] PerformanceAnalytics_1.0.4 blotter_0.8.4
[3] FinancialInstrument_0.14.2 quantmod_0.3-17
[5] TTR_0.21-1                 xts_0.8-7
[7] zoo_1.7-7                  Defaults_1.1-1

loaded via a namespace (and not attached):
[1] grid_2.15.0    lattice_0.20-6



On Sat, Jun 2, 2012 at 11:02 AM, Felice Bruno <felice.bruno at live.it> wrote:
>
> Hi
>
> I'm using blotter to make strategy backtesting.
>
> some days ago, I migrate to R-2.15, and tried to run the Faber example found on FOSS Trading blog.
>
> When I run the code, I receive the following message:
>
>
> Error in if (.parseISO8601(Dates)$first.time < first(index(Prices)) ||
>
>
> I found the origin of problem is the istruction:
>
>
> updatePortf(Portfolio='default', Dates=CurrentDate)
>
>
> To be sure, I tried to run using the R-2.14 version, and all was ok.
>
> Following is reported the code I use:
>
>
> # This code implements the strategy found in:
> # Faber, Mebane T., "A Quantitative Approach to Tactical Asset Allocation."
> # Journal of Risk Management (Spring 2007).
>
> # The article implements a simpler version of the 200-day SMA, opting for a
> # 10-month SMA because monthly data are more easily available in earlier
> # periods and 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.
> # NOTE: 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.
> # NOTE: For the purposes of this demo, we ignore interest and leverage.
> # 4. Taxes, commissions, and slippage are excluded.
>
> # Data:
> # This demo uses monthly data downloaded from Yahoo Finance for two ETFs: SPY and
> # IEF. These were chosen to illustrate the classic stock/bond asset portfolio.
> # Though longer serires would be preferred, data for IEF begin in mid-2002.
>
> # Load required libraries
> library(quantmod)
> library(TTR)
> library(blotter) # r-forge revision 193
> library(PerformanceAnalytics)
>
> # Set initial values
> initDate='2006-07-31'
> endDate='2008-01-31'
> initEq=100000
>
> # Set currency and instruments
> currency("USD")
> stock("IEF",currency="USD",multiplier=1)
> stock("SPY",currency="USD",multiplier=1)
>
> # Load data with quantmod
> print("Loading data")
> symbols = c("IEF", "SPY")
> getSymbols(symbols, from=initDate, to=endDate, index.class=c("POSIXt","POSIXct"))
>
> # Adjust prices for splits/dividends (thanks pg)
> #IEF = adjustOHLC(IEF)
> #SPY = adjustOHLC(SPY)
>
> # Convert data to monthly frequency (to.weekly() needs drop.time=FALSE)
> IEF = to.monthly(IEF, indexAt='endof')
> SPY = to.monthly(SPY, indexAt='endof')
>
> # Set up indicators with TTR
> print("Setting up indicators")
> IEF$SMA = SMA(Cl(IEF), 10)
> SPY$SMA = SMA(Cl(SPY), 10)
>
> # Set up a portfolio object and an account object in blotter
> initPortf(name='default', symbols=symbols, initDate=initDate)
> initAcct(name='default', portfolios='default', initDate=initDate, initEq=initEq)
> verbose = TRUE
>
> # Create trades
> for( i in 10:NROW(SPY) ) {
>  CurrentDate=time(SPY)[i]
>  equity = getEndEq(Account='default', CurrentDate)
>
>  for( symbol in symbols ) {
>    sym = get(symbol)
>    ClosePrice = as.numeric(Cl(sym[i,]))
>    Posn = getPosQty(Portfolio='default', Symbol=symbol, Date=CurrentDate)
>    UnitSize = as.numeric(trunc((equity/NROW(symbols))/ClosePrice))
>
>    # Position Entry (assume fill at close)
>    if( Posn == 0 ) {
>    # No position, so test to initiate Long position
>      if( Cl(sym[i,]) > sym[i,'SMA'] ) {
>        # Store trade with blotter
>        addTxn('default', Symbol=symbol, TxnDate=CurrentDate,
>          TxnPrice=ClosePrice, TxnQty=UnitSize, TxnFees=0, verbose=verbose)
>      }
>    } else {
>      # Have a position, so check exit
>      if( Cl(sym[i,]) < sym[i,'SMA'] ) {
>        # Store trade with blotter
>        addTxn(Portfolio='default', Symbol=symbol, TxnDate=CurrentDate,
>          TxnPrice=ClosePrice, TxnQty=-Posn, TxnFees=0, verbose=verbose)
>      }
>    }
>  } # End symbols loop
>
>  # Calculate P&L and resulting equity with blotter
>  updatePortf(Portfolio='default', Dates=CurrentDate)
>  updateAcct(name='default', Dates=CurrentDate)
>  updateEndEq(Account='default', Dates=CurrentDate)
>
> } # End dates loop
>
> # Buy and Hold cumulative equity
> buyhold = exp(cumsum( ( 0.5*ROC(Cl(IEF)) + 0.5*ROC(Cl(SPY)) )[-1] ))
>
> # Final values
> cat('Tactical Asset Allocation Return: ',(getEndEq(Account='default', Date=CurrentDate)-initEq)/initEq,'\n')
> cat('Buy and Hold Return: ',tail(buyhold,1)-1,'\n')
>
> # Plot Strategy Summary
> png(filename="20091118_blotter_strategy.png", 720, 720)
> #charts.PerformanceSummary(ROC(getAccount('default')$TOTAL$End.Eq)[-1],main="Tactical Asset Allocation")
> charts.PerformanceSummary(ROC(getAccount('default')$summary$End.Eq)[-1],main="Tactical Asset Allocation")
> dev.off()
>
> # Plot Buy and Hold Summary
> png(filename="20091118_blotter_buyhold.png", 720, 720)
> charts.PerformanceSummary(ROC(buyhold)[-1],main="Buy & Hold")
> dev.off()
>
>
> Thank you for your attention.
>
>        [[alternative HTML version deleted]]
>
> _______________________________________________
> R-SIG-Finance at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions should go.



More information about the R-SIG-Finance mailing list