Thanks so much Garrett.  I changed the name of the variables to eliminate any similarity and now it works as expected.  Happy holidays to you too!

Roger

________________________________
From: G See [mailto:gsee000@gmail.com]
Sent: Friday, December 23, 2011 1:44 PM
To: Bos, Roger
Cc: r-sig-finance@r-project.org
Subject: Re: [R-SIG-Finance] Asking for help using quantstrat

Hi Roger,

I don't see anything wrong with creating mktdata yourself.

I believe the reason you are not getting what you expect is because sigCrossover (calls sigComparison which calls match.names which) uses grep to find "High" in the column name of your mktdata.  In your case, you have two column names that contain the text "High".  However, only the one that you want _begins_ with "High". So if you "grep"ped for "^High" only one column would be found.  In other words, you want your add.signal lines to look something like this

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

I pasted some code below to illustrate.  Let me know if you still have problems because I didn't fully test your code.

A note about how you used FinancialInstrument:  Please get in the habit of using getInstrument(tic) instead of get(tic, envir=.instrument).
In the very near future, I'm planning on moving the .instrument environment from the .GlobalEnv to the FinancialInstrument package namespace.

Happy Holidays,
Garrett

> 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")
[1] "USD"
> stock(tic, currency="USD", multiplier=1)
[1] "IVV"
> getSymbols(tic, from=startDate, to=endDate, adjust=T)
[1] "IVV"
> for(i in tic){
+    assign(tic, adjustOHLC(get(tic),use.Adjusted=TRUE))
+ }
> ## Get VIX data from St. Luis Fed site
> getSymbols("VIXCLS",src="FRED")
[1] "VIXCLS"
>
> # Calculate VRP statistic
> etf <- get(tic)[, 6]
> names(etf)[1] <- "price"
> price <- as.numeric(etf$price)
> etf$ret <- Delt(etf)
> 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)
> mktdata$VRPMA <- SMA(mktdata$VRP, n=10)
> tail(mktdata)
           IVV.Open IVV.High  IVV.Low IVV.Close IVV.Volume IVV.Adjusted  price          ret VIXCLS
2011-12-15 122.7246 122.8438 121.6512    121.84    5189787       121.84 121.84  0.003789751  25.11
2011-12-16 122.6760 123.3618 121.7318    122.03    6743232       122.03 122.03  0.001559422  24.29
2011-12-19 122.4692 122.7375 120.4517    120.73    4121423       120.73 120.73 -0.010653118  24.92
2011-12-20 122.5810 124.5388 122.5810    124.35    5773574       124.35 124.35  0.029984262  23.22
2011-12-21 124.2817 124.7885 123.1586    124.55    4721711       124.55 124.55  0.001608363  21.43
2011-12-22 125.0100 125.8100 124.7800    125.80    2249200       125.80 125.80  0.010036130  21.16
             VRP High Low  VRPMA
2011-12-15 26.04   25  20 27.366
2011-12-16 25.11   25  20 27.136
2011-12-19 24.29   25  20 26.813
2011-12-20 24.92   25  20 26.521
2011-12-21 23.22   25  20 26.030
2011-12-22 21.43   25  20 25.306
> sC <- sigCrossover( label='test3.high', data=mktdata, columns=c("VRPMA", "High"), relationship='gte')
> na.omit(sC)
     [,1]
> sC <- sigCrossover( label='test3.high', data=mktdata, columns=c("VRPMA", "^High"), relationship='gte')
> na.omit(sC)
           test3.high
2007-08-16       TRUE
2007-09-18       TRUE
2007-11-15       TRUE
2008-01-23       TRUE
2008-03-11       TRUE
2008-07-15       TRUE
2008-09-17       TRUE
2009-08-07       TRUE
2009-10-05       TRUE
2009-11-04       TRUE
2010-05-11       TRUE
2010-08-24       TRUE
2011-08-09       TRUE



On Fri, Dec 23, 2011 at 10:09 AM, Bos, Roger <roger.bos@rothschild.com<mailto:roger.bos@rothschild.com>> wrote:
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@r-project.org<mailto:r-sig-finance-bounces@r-project.org>
[mailto:r-sig-finance-bounces@r-project.org<mailto:r-sig-finance-bounces@r-project.org>] On Behalf Of Bos, Roger
Sent: Friday, December 23, 2011 7:26 AM
To: r-sig-finance@r-project.org<mailto:r-sig-finance@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<http://Std.Dev.Daily.PL>)
#    output
#    out




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

_______________________________________________
R-SIG-Finance@r-project.org<mailto: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.
***************************************************************

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


_______________________________________________
R-SIG-Finance@r-project.org<mailto: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.


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

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
www.codetwo.com<http://www.codetwo.com>


	[[alternative HTML version deleted]]

