[R-SIG-Finance] Asking for help using quantstrat

Bos, Roger roger.bos at rothschild.com
Fri Dec 23 17:09:58 CET 2011


My apologies, I use a function I created instead of paste, so my
reproducible function won't work without it.  Here is what needs to be
added:

"%+%" <- function(x,y) {paste(x,y,sep="")}

Thanks,

Roger

 

-----Original Message-----
From: r-sig-finance-bounces at r-project.org
[mailto:r-sig-finance-bounces at r-project.org] On Behalf Of Bos, Roger
Sent: Friday, December 23, 2011 7:26 AM
To: r-sig-finance at r-project.org
Subject: [R-SIG-Finance] Asking for help using quantstrat

Quantstrat users,

First of all many thanks to the authors of quantstrat.  It looks really
interesting.  I have been wanting to learn how to use quantstrat for a
long time and have finally gotten around to playing with it.  I thought
I understood the examples (i.e. faber, mac, and macd) well enough, but I
am having trouble with a couple aspects of the package.

First, in the examples the data.frame 'mktdata' is created
automatically.  I couldn't figure out how to make that work for me
because I am adding non-price data to the analysis (the VIX index
levels).  So I create mktdata manually.  Is that okay?

Second, I am having trouble getting the results I expect for my signals.
As a test I have created three signals: test1, test2, and test3. My
reproducible code is below.  By changing the method variable you can run
different types of tests.  faber, mac, and macd run fine, but my code in
'test' has some problems.  If you run it and look at mktdata the
test1.high and test1.low columns are as I expect.  The test2.high and
test2.low columns are also as I expect (although I would prefer 0s to
NAs, but I can replace later).  My problem is with test3.high and
test3.low.  Both columns are all zeros and I would expect the same
results as test1.  (I don't expect these signals to be any good, this is
just a learning process).

Thanks in advance for any hints that you can provide,

Roger

###############################

require(quantstrat)
library("PerformanceAnalytics")
library("zoo")
"%+%" <- function(x,y) {paste(x,y,sep="")}

firstTime <- TRUE
startDate <- '2004-01-02'
tic <- 'IVV'
fast <- 50
slow <- 200
method="test"

    endDate <- Sys.Date()
    currency("USD")
    get("USD", envir=.instrument)
    stock(tic, currency="USD", multiplier=1)
    get(tic, envir=.instrument)
    getSymbols(tic, from=startDate, to=endDate, adjust=T)
    for(i in tic){
        assign(tic, adjustOHLC(get(tic),use.Adjusted=TRUE))
    }

    ## Get VIX data from St. Luis Fed site
    getSymbols("VIXCLS",src="FRED")

    # Calculate VRP statistic
    etf <- get(tic)[, 6]
    names(etf)[1] <- "price"
    price <- as.numeric(etf$price)
    etf$ret <- c(as.numeric('NA'), price[-1] / price[-nrow(etf)] - 1)
    etf <- merge(etf, VIXCLS)
    etf$VRP <- lag(etf$VIXCLS)
    etf$High <- 25 #etf$VIXCLS + 2
    etf$Low <- 20 #etf$VIXCLS - 2
    mktdata <- merge(get(tic), etf)
    tail(mktdata)

    qs.strategy <- "qs"
    if (exists(".strategy")) suppressWarnings(rm("order_book.qs",
pos=.strategy))
    if (exists(".blotter")) suppressWarnings(rm("account.qs",
"portfolio.qs", pos=.blotter))
    suppressWarnings(rm("qs.strategy", "stratName", "initDate",
"initEq", 'start_t', 'end_t'))
    qs.strategy <- "qs"
    initPortf(qs.strategy, tic, initDate=startDate)
    initAcct(qs.strategy, portfolios=qs.strategy, initDate=startDate,
initEq=1e5)
    initOrders(portfolio=qs.strategy, initDate=startDate)
    stratName<- strategy(qs.strategy)

    if (method=='mac') {

        #Adding indicators to a strategy
        stratName <- add.indicator(strategy = stratName, name = "SMA",
arguments = list(x=quote(Cl(mktdata)), n=fast),label= "maFast" )
        stratName <- add.indicator(strategy = stratName, name = "SMA",
arguments = list(x=quote(Cl(mktdata)), n=slow),label= "maSlow")

        #Adding signals to a strategy
        stratName <- add.signal(strategy =
stratName,name="sigCrossover",arguments =
list(columns=c("maFast","maSlow"),
relationship="gte"),label="maFast.gt.maSlow")
        stratName <- add.signal(strategy =
stratName,name="sigCrossover",arguments =
list(column=c("maFast","maSlow"),relationship="lt"),label="maFast.lt.maS
low")

        #Add rules to a strategy
        stratName <- add.rule(strategy = stratName,name='ruleSignal',
arguments = list(sigcol="maFast.gt.maSlow",sigval=TRUE, orderqty=100,
ordertype='market', orderside='long'),type='enter')
        stratName <- add.rule(strategy = stratName,name='ruleSignal',
arguments = list(sigcol="maFast.lt.maSlow",sigval=TRUE, orderqty=-100,
ordertype='market', orderside='long'),type='exit')

    } else if (method=='faber') {
        # Add an indicator
        stratName <- add.indicator(strategy = stratName, name = "SMA",
arguments = list(x = quote(mktdata$IVV.Close), n=10), label="SMA10")

        # There are two signals:
        # The first is when monthly price crosses over the 10-month SMA
        stratName <- add.signal(stratName,name="sigCrossover",arguments
= list(columns=c("Close","SMA10"),relationship="gte"),label="Cl.gt.SMA")
        # The second is when the monthly price crosses under the
10-month SMA
        stratName <- add.signal(stratName,name="sigCrossover",arguments
= list(columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")

        # There are two rules:
        # The first is to buy when the price crosses above the SMA
        stratName <- add.rule(stratName, name='ruleSignal', arguments =
list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=100, ordertype='market',
orderside='long', pricemethod='market',TxnFees=-5), type='enter',
path.dep=TRUE)
        # The second is to sell when the price crosses below the SMA
        stratName <- add.rule(stratName, name='ruleSignal', arguments =
list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all',
ordertype='market', orderside='long', pricemethod='market',TxnFees=-5),
type='exit', path.dep=TRUE)

    } else if (method=='macd') {

        stratName <- add.indicator(strategy = stratName, name = "MACD",
arguments = list(x=quote(Cl(mktdata))) )

        stratName <- add.signal(strategy =
stratName,name="sigThreshold",arguments =
list(column="signal",relationship="gt",threshold=0,cross=TRUE),label="si
gnal.gt.zero")
        stratName <- add.signal(strategy =
stratName,name="sigThreshold",arguments =
list(column="signal",relationship="lt",threshold=0,cross=TRUE),label="si
gnal.lt.zero")

        stratName <- add.rule(strategy = stratName,name='ruleSignal',
arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty=100,
ordertype='market', orderside='long', threshold=NULL),type='enter')
        stratName <- add.rule(strategy = stratName,name='ruleSignal',
arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty=-100,
ordertype='stoplimit', orderside='long',
threshold=.85,tmult=TRUE),type='risk')

        stratName <- add.rule(strategy = stratName,name='ruleSignal',
arguments = list(sigcol="signal.lt.zero",sigval=TRUE, orderqty='all',
ordertype='market', orderside='long', threshold=NULL),type='exit')

    } else if (method=='test') {
        stratName <- add.indicator(strategy = stratName, name = "SMA",
            arguments = list(x = quote(mktdata$VRP), n=10),
label="VRPMA")

        stratName <- add.signal(strategy =
stratName,name="sigThreshold",arguments =
            list(column="VRPMA",
relationship="gte",threshold=25,cross=TRUE),label="test1.high")

        stratName <- add.signal(strategy =
stratName,name="sigThreshold",arguments =
            list(column="VRPMA",
relationship="lte",threshold=20,cross=TRUE),label="test1.low")

        stratName <- add.signal(strategy =
stratName,name="sigCrossover",arguments =
            list(columns=c("VRPMA","VRP"), relationship="gte"),
label="test2.high")

        stratName <- add.signal(strategy =
stratName,name="sigCrossover",arguments =
            list(columns=c("VRPMA","VRP"), relationship="lte"),
label="test2.low")

        stratName <- add.signal(strategy =
stratName,name="sigCrossover",arguments =
            list(columns=c("VRPMA","High"), relationship="gte"),
label="test3.high")

        stratName <- add.signal(strategy =
stratName,name="sigCrossover",arguments =
            list(columns=c("VRPMA","Low"), relationship="lte"),
label="test3.low")

        stratName <- add.rule(strategy = stratName, name='ruleSignal',
arguments =
            list(sigcol="VRP.low", sigval=1, orderqty=100,
ordertype='market', orderside='long', pricemethod='market',TxnFees=-5),
type='enter', path.dep=TRUE)

        stratName <- add.rule(strategy = stratName, name='ruleSignal',
arguments =
            list(sigcol="VRP.high", sigval=1, orderqty='all',
ordertype='market', orderside='long', pricemethod='market',TxnFees=-5),
type='exit', path.dep=TRUE)
    }


    #Apply the Strategy
    out <- try(applyStrategy(strategy=stratName, portfolios=qs.strategy,
mktdata=mktdata))
    tail(mktdata,50)

#    #step 5
#    #update P&L
#
updatePortf(Portfolio=qs.strategy,Dates=paste('::',as.Date(Sys.time()),s
ep=''))
#    updateAcct(name=qs.strategy, Dates=index(get(tic)))
#    sapply(X=index(get(tic)), FUN=updateEndEq, Account=qs.strategy)
#
#    acct = getAccount(qs.strategy)
#    #tail(acct$summary$End.Eq)
#    #acct$summary$End.Eq[length(acct$summary$End.Eq)]
#
#    #Trade statistics
#    tstats <- tradeStats(Portfolio=qs.strategy, Symbol=tic)
#    output <- data.frame(method, tstats$Gross.Profits,
tstats$maxDrawdown, tstats$Std.Dev.Daily.PL)
#    output
#    out
    



***************************************************************
This message is for the named person's use only. It
may\...{{dropped:15}}

_______________________________________________
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.
***************************************************************

This message is for the named person's use only. It may
contain confidential, proprietary or legally privileged
information. No right to confidential or privileged treatment
of this message is waived or lost by an error in transmission.
If you have received this message in error, please immediately
notify the the sender by e-mail, delete the message and all 
copies from your system and destroy any hard copies.  You must
not, directly or indirectly, use, disclose, distribute, 
print or copy any part of this message if you are not
the intended recipient.

****************************************************************



***************************************************************
This message is for the named person's use only. It may
contain confidential, proprietary or legally privileged
information. No right to confidential or privileged treatment
of this message is waived or lost by an error in transmission.
If you have received this message in error, please immediately
notify the the sender by e-mail, delete the message and all 
copies from your system and destroy any hard copies.  You must
not, directly or indirectly, use, disclose, distribute, 
print or copy any part of this message if you are not
the intended recipient.

Disclaimer added by CodeTwo Exchange Rules 2010	
http://www.codetwo.com	
	



More information about the R-SIG-Finance mailing list