[prev in list] [next in list] [prev in thread] [next in thread] 

List:       r-sig-finance
Subject:    [R-SIG-Finance] Fwd: blotter, quantstrat: initDate without effect?
From:       Andreas Voellenklee <wotuzu17 () gmail ! com>
Date:       2011-10-28 5:12:12
Message-ID: CAKC0BhmOWvFuw7YwQPPnZ8gyzKFjeodJwZ=-Om0_BkgoL43JSg () mail ! gmail ! com
[Download RAW message or body]

Hi,
I spend the last couple of days trying out the functionality of the
TradeAnalytics packages. There are some observations that I would like
to share. I use RStudio as GUI and derived the attached code from a
demo example.

1) since the trading system operates with moving averages, I download
data prior the start of applying the strategy to have all moving
averages calculated at the start time. But although the Portfolio,
Account and Orders get initialized at the beginning of 2002, the
execution of the strategy seems to start from the beginning of 2001

2) the getSymbols command returns a warning I don't understand:

Warning message:
In if (as.character(sc[[1]]) != calling.fun) return() :
 the condition has length > 1 and only the first element will be used:

This is my sessionInfo:

> sessionInfo()
R version 2.13.1 (2011-07-08)
Platform: i686-pc-linux-gnu (32-bit)

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

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

other attached packages:
[1] PerformanceAnalytics_1.0.3.2 quantstrat_0.5.6
blotter_0.8.4                FinancialInstrument_0.7.5
[5] quantmod_0.3-17              Defaults_1.1-1
TTR_0.21-0                   xts_0.8-2
[9] zoo_1.7-5

loaded via a namespace (and not attached):
[1] grid_2.13.1     lattice_0.19-30 tools_2.13.1


Regards,
Andreas

["STRAT_MACROSS.R" (text/x-r-source)]

# Script to evaluate Moving Average strategies
# (and to experiment with R's finance packages')
# 20111026 Va
require(quantstrat)
require(PerformanceAnalytics)

# rebuild empty environment if RStudio's "Clear All"" has been used
.instrument <- new.env()
.blotter <- new.env()
.strategy <- new.env()
    
# clean up workspace if script has run before
suppressWarnings(rm("order_book.MA",pos=.strategy))
suppressWarnings(rm("account.MA","portfolio.MA",pos=.blotter))
suppressWarnings(rm("symbols","account.st","portfolio.st","stratMA","retrieveDate","initDate","stopDate","initEq",'start_t','end_t'))


# define testparameters
symbols     <- c("AAPL")
retrieveDate<- '2001-01-01'  # retrieve older data to allow calculation of MA prior \
to start of trading initDate    <- '2002-01-01'  # date to start trading strategy
stopDate    <- '2005-12-31'  # stop retrieving data and applying strategy
initEq      <- 10000         # initial funds
account.st  <- "MA"
portfolio.st<- "MA"
maShort     <- 10
maLong      <- 90

# defining Financial Instruments
FinancialInstrument::currency('USD')
for (symbol in symbols)
  FinancialInstrument::stock(symbol,currency='USD',multiplier=1)

# get Market Data and adjust prices
for(symbol in symbols)
#  quantmod::getSymbols(symbol,from=retrieveDate,to=stopDate,index.class=c("POSIXt","POSIXct"))
  quantmod::getSymbols(symbol,from=retrieveDate,to=stopDate)
  base::assign(symbol, adjustOHLC(get(symbol),use.Adjusted=TRUE))

# initialize Portfolio, Account and Orders
blotter::initPortf(portfolio.st,symbols=symbols, initDate=initDate)
blotter::initAcct(account.st,portfolios=portfolio.st,initDate=initDate,initEq=initEq,currency='USD')
 quantstrat::initOrders(portfolio=portfolio.st,initDate=initDate)

stratMA <- quantstrat::strategy(portfolio.st)

stratMA <- quantstrat::add.indicator(strategy = stratMA, name = "SMA", arguments = \
list(x=quote(Cl(mktdata)), n=maShort),label= "maShort" ) stratMA <- \
quantstrat::add.indicator(strategy = stratMA, name = "SMA", arguments = \
list(x=quote(Cl(mktdata)), n=maLong),label= "maLong")

stratMA <- quantstrat::add.signal(strategy = stratMA,name="sigCrossover",arguments = \
list(columns=c("maShort","maLong"), relationship="gte"),label="maShort.gt.maLong") \
stratMA <- quantstrat::add.signal(strategy = stratMA,name="sigCrossover",arguments = \
list(column=c("maShort","maLong"),relationship="lt"),label="maShort.lt.maLong")

stratMA <- quantstrat::add.rule(strategy = stratMA,name='ruleSignal', arguments = \
list(sigcol="maShort.gt.maLong",sigval=TRUE, orderqty=100, ordertype='market', \
orderside='long'),type='enter') stratMA <- quantstrat::add.rule(strategy = \
stratMA,name='ruleSignal', arguments = list(sigcol="maShort.lt.maLong",sigval=TRUE, \
orderqty=-100, ordertype='market', orderside='long'),type='exit')

# applying strategy
out<-try(quantstrat::applyStrategy(strategy=stratMA , portfolios=portfolio.st))

# update portfolio
blotter::updatePortf(Portfolio=portfolio.st,Dates=paste('::',as.Date(Sys.time()),sep=''))


# show chart
blotter::chart.Posn(Portfolio=portfolio.st,Symbol=symbols[1])
#add_SMA(n=maShort , on=1,col='blue')
#add_SMA(n=maLong , on=1,col='green')

# calculate daily returns
dailyreturns <- blotter::PortfReturns(account.st, Portfolios=portfolio.st, \
method=c("contribution"))

# PerformanceAnalysis chart
PerformanceAnalytics::charts.PerformanceSummary(dailyreturns)



_______________________________________________
R-SIG-Finance@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.

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic