[R-SIG-Finance] Ilya's Kipnis blog (quantstrat)

Bos, Roger roger.bos at rothschild.com
Tue Aug 26 19:34:02 CEST 2014


Ilya,

Thanks for your blog, it looks interesting.  I tried running the code in your latest blog entry and got an error in the applyStrategy line.

> out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
Error in `[.xts`(x, seq_len(xlen - n)) : subscript out of bounds

Here is my sessionInfo:

R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

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

other attached packages:
 [1] quantstrat_0.8.2           foreach_1.4.2
 [3] blotter_0.8.19             PerformanceAnalytics_1.1.0
 [5] FinancialInstrument_1.1.9  quantmod_0.4-0
 [7] TTR_0.22-0                 Defaults_1.1-1
 [9] Rpad_1.3.0                 formatR_0.10
[11] dplyr_0.2                  reshape2_1.4
[13] ggplot2_1.0.0              xts_0.9-7
[15] zoo_1.7-11                 XLConnect_0.2-7
[17] timeDate_3010.98           R2HTML_2.2.1
[19] RODBC_1.3-10               quadprog_1.5-5
[21] prettyR_2.0-8              MASS_7.3-33
[23] fortunes_1.5-2             corpcor_1.6.6

loaded via a namespace (and not attached):
 [1] assertthat_0.1   codetools_0.2-8  colorspace_1.2-4
 [4] digest_0.6.4     grid_3.1.1       gtable_0.1.2
 [7] iterators_1.0.7  lattice_0.20-29  magrittr_1.0.1
[10] munsell_0.4.2    parallel_3.1.1   plyr_1.8.1
[13] proto_0.3-10     Rcpp_0.11.2      rJava_0.9-6
[16] scales_0.2.4     stringr_0.6.2

Here is the complete code I tried to run (I pasted in the code for demoData.R so there is only one file (for simplicity):

require(DSTrading)
require(IKTrading)
require(quantstrat)
require(PerformanceAnalytics)

initDate="1990-01-01"
from="2003-01-01"
to="2010-12-31"
options(width=70)
verbose=TRUE

### start demoData.R
options("getSymbols.warning4.0"=FALSE)
rm(list=ls(.blotter), envir=.blotter)
initDate='1990-12-31'

currency('USD')
Sys.setenv(TZ="UTC")

symbols <- c("XLB", #SPDR Materials sector
             "XLE", #SPDR Energy sector
             "XLF", #SPDR Financial sector
             "XLP", #SPDR Consumer staples sector
             "XLI", #SPDR Industrial sector
             "XLU", #SPDR Utilities sector
             "XLV", #SPDR Healthcare sector
             "XLK", #SPDR Tech sector
             "XLY", #SPDR Consumer discretionary sector
             "RWR", #SPDR Dow Jones REIT ETF

             "EWJ", #iShares Japan
             "EWG", #iShares Germany
             "EWU", #iShares UK
             "EWC", #iShares Canada
             "EWY", #iShares South Korea
             "EWA", #iShares Australia
             "EWH", #iShares Hong Kong
             "EWS", #iShares Singapore
             "IYZ", #iShares U.S. Telecom
             "EZU", #iShares MSCI EMU ETF
             "IYR", #iShares U.S. Real Estate
             "EWT", #iShares Taiwan
             "EWZ", #iShares Brazil
             "EFA", #iShares EAFE
             "IGE", #iShares North American Natural Resources
             "EPP", #iShares Pacific Ex Japan
             "LQD", #iShares Investment Grade Corporate Bonds
             "SHY", #iShares 1-3 year TBonds
             "IEF", #iShares 3-7 year TBonds
             "TLT" #iShares 20+ year Bonds
)

#SPDR ETFs first, iShares ETFs afterwards
if(!"XLB" %in% ls()) {
  suppressMessages(getSymbols(symbols, from="2003-01-01", to="2010-12-31", src="yahoo", adjust=TRUE))
}

stock(symbols, currency="USD", multiplier=1)
### end demoData.R

#trade sizing and initial equity settings
tradeSize <- 100000
initEq <- tradeSize*length(symbols)

strategy.st <- portfolio.st <- account.st <- "Cycle_RSI_I"
rm.strat(portfolio.st)
rm.strat(strategy.st)
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate, currency='USD',initEq=initEq)
initOrders(portfolio.st, initDate=initDate)
strategy(strategy.st, store=TRUE)

#parameters
nRSI=2
RSIentry=10
RSIexit=70

nSMA=200

period=10
pctATR=.04

#indicators
add.indicator(strategy.st, name="lagATR",
              arguments=list(HLC=quote(HLC(mktdata)), n=period),
              label="atrX")
add.indicator(strategy.st, name="SMA",
              arguments=list(x=quote(Cl(mktdata)), n=nSMA),
              label="SMA")
add.indicator(strategy.st, name="CycleRSI",
              arguments=list(x=quote(Cl(mktdata)), n=nRSI),
              label="RSI")

#signals
add.signal(strategy.st, name="sigComparison",
           arguments=list(columns=c("Close", "SMA"), relationship="gt"),
           label="ClGtSMA")

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="CycleRSI.RSI", threshold=RSIentry,
                          relationship="lt", cross=FALSE),
           label="RSIltEntryThresh")

add.signal(strategy.st, name="sigAND",
           arguments=list(columns=c("ClGtSMA", "RSIltEntryThresh"),
                          cross=TRUE),
           label="longEntry")

add.signal(strategy.st, name="sigCrossover",
           arguments=list(columns=c("Close", "SMA"), relationship="lt"),
           label="exitSMA")

add.signal(strategy.st, name="sigThreshold",
           arguments=list(column="CycleRSI.RSI", threshold=RSIexit,
                          relationship="gt", cross=TRUE),
           label="longExit")

#rules
#rules
add.rule(strategy.st, name="ruleSignal",
         arguments=list(sigcol="longEntry", sigval=TRUE,
                        ordertype="market",
                        orderside="long", replace=FALSE,
                        prefer="Open", osFUN=osDollarATR,
                        tradeSize=tradeSize, pctATR=pctATR,
                        atrMod="X"),
         type="enter", path.dep=TRUE)

add.rule(strategy.st, name="ruleSignal",
         arguments=list(sigcol="longExit", sigval=TRUE,
                        orderqty="all", ordertype="market",
                        orderside="long", replace=FALSE,
                        prefer="Open"),
         type="exit", path.dep=TRUE)

add.rule(strategy.st, name="ruleSignal",
         arguments=list(sigcol="exitSMA", sigval=TRUE,
                        orderqty="all", ordertype="market",
                        orderside="long", replace=FALSE,
                        prefer="Open"),
         type="exit", path.dep=TRUE)

#apply strategy
t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st)
t2 <- Sys.time()
print(t2-t1)

#set up analytics
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1]
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)


agg.chart.ME <- function(Portfolio, Symbols, type=c("MAE", "MFE"), scale=c("cash", "percent", "tick")) {
  type=type[1]
  scale=scale[1]
  trades <- list()
  length(trades) <- length(Symbols)
  for(Symbol in Symbols) {
    trades[[Symbol]] <- pts <- perTradeStats(Portfolio=Portfolio, Symbol=Symbol, includeOpenTrade=FALSE)
  }
  trades <- do.call(rbind, trades)
  trades$Pct.Net.Trading.PL <- 100 * trades$Pct.Net.Trading.PL
  trades$Pct.MAE <- 100 * trades$Pct.MAE
  trades$Pct.MFE <- 100 * trades$Pct.MFE
  profitable <- (trades$Net.Trading.PL > 0)
  switch(scale, cash = {
    .ylab <- "Profit/Loss (cash)"
    if (type == "MAE") {
      .cols <- c("MAE", "Net.Trading.PL")
      .xlab <- "Drawdown (cash)"
      .main <- "Maximum Adverse Excursion (MAE)"
    } else {
      .cols <- c("MFE", "Net.Trading.PL")
      .xlab <- "Run Up (cash)"
      .main <- "Maximum Favourable Excursion (MFE)"
    }
  }, percent = {
    .ylab <- "Profit/Loss (%)"
    if (type == "MAE") {
      .cols <- c("Pct.MAE", "Pct.Net.Trading.PL")
      .xlab <- "Drawdown (%)"
      .main <- "Maximum Adverse Excursion (MAE)"
    } else {
      .cols <- c("Pct.MFE", "Pct.Net.Trading.PL")
      .xlab <- "Run Up (%)"
      .main <- "Maximum Favourable Excursion (MFE)"
    }
  }, tick = {
    .ylab <- "Profit/Loss (ticks)"
    if (type == "MAE") {
      .cols <- c("tick.MAE", "tick.Net.Trading.PL")
      .xlab <- "Drawdown (ticks)"
      .main <- "Maximum Adverse Excursion (MAE)"
    } else {
      .cols <- c("tick.MFE", "tick.Net.Trading.PL")
      .xlab <- "Run Up (ticks)"
      .main <- "Maximum Favourable Excursion (MFE)"
    }
  })
  .main <- paste("All trades", .main)
  plot(abs(trades[, .cols]), type = "n", xlab = .xlab, ylab = .ylab,
       main = .main)
  grid()
  points(abs(trades[profitable, .cols]), pch = 24, col = "green",
         bg = "green", cex = 0.6)
  points(abs(trades[!profitable, .cols]), pch = 25, col = "red",
         bg = "red", cex = 0.6)
  abline(a = 0, b = 1, lty = "dashed", col = "darkgrey")
  legend(x = "bottomright", inset = 0.1, legend = c("Profitable Trade",
                                                    "Losing Trade"), pch = c(24, 25), col = c("green", "red"),
         pt.bg = c("green", "red"))
}






***************************************************************
This message and any attachments are for the named person's use only.
This message 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 sender by e-mail, delete the message, any attachments 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 or any attachments if you are not
the intended recipient.



-----Original Message-----
From: r-sig-finance-bounces at r-project.org [mailto:r-sig-finance-bounces at r-project.org] On Behalf Of Daniel Cegielka
Sent: Tuesday, August 26, 2014 11:56 AM
To: Ilya Kipnis; R-Finance
Subject: Re: [R-SIG-Finance] Ilya's Kipnis blog (quantstrat)

2014-08-26 17:35 GMT+02:00 Ilya Kipnis <ilya.kipnis at gmail.com>:
>
> Daniel,
>
> Was this a response to somebody's question, or are you just sending a
> link for the purpose of knowledge? In any case, thanks.

No, I just shared a link with the group. Thanks for such an amazing blog!

Daniel

>
> -Ilya
>

_______________________________________________
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