Strategies coded in R - Matlab, R project and Python | futures io social day trading
futures io futures trading


Strategies coded in R
Updated: Views / Replies:3,343 / 24
Created: by donedge Attachments:4

Welcome to futures io.

(If you already have an account, login at the top of the page)

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors Ė all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you donít need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.

You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

Reply
 4  
 
Thread Tools Search this Thread
 

Strategies coded in R

  #1 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received

Strategies coded in R

Hello!

I am writing a strategy Anyone know where I have to change to avoid this error? I should get a similar chart like this.


 
Code
> eq1 <- getAccount("multiAsset.bb1")$summary$End.Eq
> rt1 <- Return.calculate(eq1,"log")
> eq2 <- getAccount("multiAsset.bb2")$summary$End.Eq
> rt2 <- Return.calculate(eq2,"log")
> returns <- cbind(rt1,rt2)
> colnames(returns) <- c("SD=2", "SD=3")
> chart.CumReturns(returns,colorset = c(2,4),legend.loc = "topleft", main="BBand SD Parameter Comparison",minor.ticks=FALSE)
Error in `[.xts`(x, start.row, 1) : subscript out of bounds
 
Code
#Initialization
library(quantstrat)
startDate <- "2010-01-01"
endDate <- "2013-07-31"
symbols = c("XLF","XLP","XLE","XLY","XLV","XLI","XLB","XLK","XLU")
Sys.setenv(TZ="UTC")

getSymbols(symbols, src="yahoo", index.class=c("POSIXt","POSIXct"),
           from=startDate, to=endDate, adjust=TRUE)

#Plot time series of portfolio constituents
myTheme <- chart_theme()
myTheme$col$dn.col <- "lightblue"
myTheme$col$dn.border <- "lightgray"
myTheme$col$up.border <- "lightgray"

par(mfrow = c(3,3))
for(symbol in symbols)
{
  plot(chart_Series(get(symbol), name=symbol, theme=myTheme))
}
par(mfrow = c(1,1))

#Initialize instruments
initDate <- "2009-12-31"
initEq <- 1e6
currency("USD")
stock(symbols,currency = "USD", multiplier = 1)

#Calculate and plot Bollinger bands
args(BBands)
b <- BBands(HLC=HLC(XLF["2013"]), n=20, sd=2)
tail(b)
chart_Series(XLF["2013"], TA="add_BBands(lwd=2)", theme = myTheme, name="XLF")

#Initialize portfolio, account, and orders object
rm.strat("multiAsset.bb1")
initPortf(name="multiAsset.bb1", symbols, initDate = initDate)
initAcct(name="multiAsset.bb1", portfolios = "multiAsset.bb1", initDate = initDate, initEq = initEq)
initOrders(portfolio = "multiAsset.bb1", initDate=initDate)

#Define indicators
strategy("bbands", store = TRUE)

add.indicator("bbands", name = "BBands",
              arguments=list(HLC=quote(HLC(mktdata)), maType="SMA"), label = "BBands")

#Define signals
add.signal(strategy = "bbands", name="sigCrossover",
           arguments=list(columns=c("Close", "up"), relationship="gt"),
           label="Cl.gt.UpperBand")
add.signal(strategy = "bbands", name="sigCrossover",
           arguments=list(columns=c("Close", "dn"), relationship="lt"),
           label="Cl.lt.LowerBand")
add.signal(strategy = "bbands", name="sigCrossover",
           arguments=list(columns=c("High", "Low", "mavg"), relationship="op"),
           label="Cross.Mid")

#Add rules
add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cl.gt.UpperBand",sigval=TRUE,orderqty=-100,ordertype="market",
                        orderside=NULL),type="enter")
add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cl.lt.LowerBand",sigval=TRUE,orderqty=100,ordertype="market",
                        ordertype=NULL),type="enter")
add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cross.Mid",sigval=TRUE,orderqty="all",ordertype="market",
                        orderside=NULL), type="exit")

#Applying strategy to a multi-asset portfolio
SD=2
N=20

out <- applyStrategy(strategy = "bbands",portfolios = "multiAsset.bb1",parameters = list(sd=SD,n=N))

#Data integrity check
checkBlotterUpdate <- function(port.st,account.st,verbose=TRUE)
{
  ok <- TRUE
  p <- getPortfolio(port.st)
  a <- getAccount(account.st)
  syms <- names(p$symbols)
  port.tot <- sum(sapply(syms,FUN = function(x) eval(parse(
    text=paste("sum(p$symbols",x,"posPL.USD$Net.Trading.PL)",sep="$")))))
  port.sum.tot <- sum(p$summary$Net.Trading.PL)
  if( !isTRUE(all.equal(port.tot,port.sum.tot)) ) {
    ok <- FALSE
    if( verbose )
      print("portfolio P&L doesn't match sum of symbols P&L")
  }
  initEq <- as.numeric(first(a$summary$End.Eq))
  endEq <- as.numeric(last(a$summary$End.Eq))
  if( !isTRUE(all.equal(port.tot,endEq-initEq)) ) {
    ok <- FALSE
    if( verbose )
      print("portfolio P&L doesn't match account P&L")
  }
  if( sum(duplicated(index(p$summary))) ) {
    ok <- FALSE
    if( verbose )
      print("duplicate timestamps in portfolio summary")
  }
  if( sum(duplicated(index(a$summary))) ) {
    ok <- FALSE
    if( verbose )
      print("duplicate timestamps in account summary")
  }
  return(ok)
}
checkBlotterUpdate("multiAsset.bb1","multiAsset.bb1")

#Chart performance for one of the assets
args(chart.Posn)
chart.Posn("multiAsset.bb1", "XLB", TA="add_BBands(n=20, sd=2)", theme=myTheme)
chart.Posn("multiAsset.bb1", "XLB", TA="add_BBands(n=20, sd=2)", Dates="2010", theme=myTheme)

#Initialize portfolio, account, and orders object
rm.strat(name="multiAsset.bb2")
initPortf(name="multiAsset.bb2", symbols, initDate = initDate)
initAcct(name="multiAsset.bb2", portfolios = "multiAsset.bb2", initDate = initDate, initEq = initEq)
initOrders(portfolio = "multiAsset.bb2", initDate = initDate)

SD=3
out <- applyStrategy(strategy="bbands", portfolios="multiAsset.bb2",parameters=list(sd=SD,n=N))

updatePortf("multiAsset.bb2")
updateAcct("multiAsset.bb2")
updateEndEq("multiAsset.bb2")

checkBlotterUpdate("multiAsset.bb2","multiAsset.bb2")

eq1 <- getAccount("multiAsset.bb1")$summary$End.Eq
rt1 <- Return.calculate(eq1,"log")
eq2 <- getAccount("multiAsset.bb2")$summary$End.Eq
rt2 <- Return.calculate(eq2,"log")
returns <- cbind(rt1,rt2)
colnames(returns) <- c("SD=2", "SD=3")
chart.CumReturns(returns,colorset = c(2,4),legend.loc = "topleft", main="BBand SD Parameter Comparison",minor.ticks=FALSE)

Attached Thumbnails
Strategies coded in R-bbs.png  
Reply With Quote
The following user says Thank You to donedge for this post:
 
  #2 (permalink)
Quick Summary
Quick Summary Post

Quick Summary is created and edited by users like you... Add FAQ's, Links and other Relevant Information by clicking the edit button in the lower right hand corner of this message.

 
  #3 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received


My code is commented out..

I get error when I use that code.

When I use ' instead of " it works. I thought R is working with both? Or is this not the case?

Thanks for any help!

 
Code
strategy("bb.lim", store = TRUE)
}
#Define indicators and signals
# add.indicator("bb.lim","BBands",
#            arguments=list(HLC=quote(HLC(mktdata)),maType="SMA"),label="BBands")
# 
# add.signal("bb.lim",name="sigCrossover",
#            arguments=list(columns=c("Close","up"),relationship="gt"),label="Cl.gt.UpperBand")
# 
# add.signal("bb.lim",name="sigCrossover",
#            arguments=list(columns=c("Close","dn"),relationship="lt"),label="Cl.lt.LowerBand")
# 
# add.signal("bb.lim",name="sigCrossover",
#            arguments=list(columns=c("High","Low","mavg"),relationship="op"),label="Cross.Mid")
# 

add.indicator("bb.lim",name = "BBands",
            arguments=list(HLC=quote(HLC(mktdata)),maType='SMA'),label='BBands')

add.signal("bb.lim",name="sigCrossover",
            arguments=list(columns=c("Close","up"),relationship="gt"),label="Cl.gt.UpperBand")

add.signal("bb.lim",name="sigCrossover",
            arguments=list(columns=c("Close","dn"),relationship="lt"),label="Cl.lt.LowerBand")

add.signal("bb.lim",name="sigCrossover",
            arguments=list(columns=c("High","Low","mavg"),relationship="op"),label="Cross.Mid")

#Add rules with an order sizing function specified
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="Cl.gt.UpperBand",
#                         sigval=TRUE,
#                         orderqty=-1000,
#                         ordertype="market",
#                         orderside=NULL,
#                         osFUN="osMaxPos"),
#                         type="enter")
# 
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="C.lt.LowerBand",
#                         sigval=TRUE,
#                         orderqty=1000,
#                         ordertype="market",
#                         orderside=NULL,
#                         osFUN="osMaxPos"),
#                         type="enter")
# 
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="Cross.Mid",
#                         sigval=TRUE,
#                         orderqty="all",
#                         ordertype="market",
#                         orderside=NULL),
#                         type="exit")

add.rule("bb.lim", name='ruleSignal',
          arguments=list(sigcol="Cl.gt.UpperBand",
                        sigval=TRUE,
                        orderqty=-1000,
                        ordertype='market',
                        orderside=NULL,
                        osFUN='osMaxPos'),
                        type='enter')

add.rule("bb.lim", name='ruleSignal',
          arguments=list(sigcol="Cl.lt.LowerBand",
                        sigval=TRUE,
                        orderqty= 1000,
                        ordertype='market',
                        orderside=NULL,
                        osFUN='osMaxPos'),
                        type='enter')

add.rule("bb.lim", name='ruleSignal',
          arguments=list(sigcol="Cross.Mid",
                        sigval=TRUE,
                        orderqty= 'all',
                        ordertype='market',
                        orderside=NULL),
                        type='exit')

Reply With Quote
 
  #4 (permalink)
Elite Member
seoul, Korea
 
Futures Experience: Intermediate
Platform: Multicharts
Broker/Data: CQG, DTN IQfeed
Favorite Futures: YM 6E
 
treydog999's Avatar
 
Posts: 894 since Jul 2012
Thanks: 291 given, 1,006 received


donedge View Post
Hello!

I am writing a strategy Anyone know where I have to change to avoid this error? I should get a similar chart like this.


 
Code
> eq1 <- getAccount("multiAsset.bb1")$summary$End.Eq
> rt1 <- Return.calculate(eq1,"log")
> eq2 <- getAccount("multiAsset.bb2")$summary$End.Eq
> rt2 <- Return.calculate(eq2,"log")
> returns <- cbind(rt1,rt2)
> colnames(returns) <- c("SD=2", "SD=3")
> chart.CumReturns(returns,colorset = c(2,4),legend.loc = "topleft", main="BBand SD Parameter Comparison",minor.ticks=FALSE)
Error in `[.xts`(x, start.row, 1) : subscript out of bounds
 
Code
#Initialization
library(quantstrat)
startDate <- "2010-01-01"
endDate <- "2013-07-31"
symbols = c("XLF","XLP","XLE","XLY","XLV","XLI","XLB","XLK","XLU")
Sys.setenv(TZ="UTC")

getSymbols(symbols, src="yahoo", index.class=c("POSIXt","POSIXct"),
           from=startDate, to=endDate, adjust=TRUE)

#Plot time series of portfolio constituents
myTheme <- chart_theme()
myTheme$col$dn.col <- "lightblue"
myTheme$col$dn.border <- "lightgray"
myTheme$col$up.border <- "lightgray"

par(mfrow = c(3,3))
for(symbol in symbols)
{
  plot(chart_Series(get(symbol), name=symbol, theme=myTheme))
}
par(mfrow = c(1,1))

#Initialize instruments
initDate <- "2009-12-31"
initEq <- 1e6
currency("USD")
stock(symbols,currency = "USD", multiplier = 1)

#Calculate and plot Bollinger bands
args(BBands)
b <- BBands(HLC=HLC(XLF["2013"]), n=20, sd=2)
tail(b)
chart_Series(XLF["2013"], TA="add_BBands(lwd=2)", theme = myTheme, name="XLF")

#Initialize portfolio, account, and orders object
rm.strat("multiAsset.bb1")
initPortf(name="multiAsset.bb1", symbols, initDate = initDate)
initAcct(name="multiAsset.bb1", portfolios = "multiAsset.bb1", initDate = initDate, initEq = initEq)
initOrders(portfolio = "multiAsset.bb1", initDate=initDate)

#Define indicators
strategy("bbands", store = TRUE)

add.indicator("bbands", name = "BBands",
              arguments=list(HLC=quote(HLC(mktdata)), maType="SMA"), label = "BBands")

#Define signals
add.signal(strategy = "bbands", name="sigCrossover",
           arguments=list(columns=c("Close", "up"), relationship="gt"),
           label="Cl.gt.UpperBand")
add.signal(strategy = "bbands", name="sigCrossover",
           arguments=list(columns=c("Close", "dn"), relationship="lt"),
           label="Cl.lt.LowerBand")
add.signal(strategy = "bbands", name="sigCrossover",
           arguments=list(columns=c("High", "Low", "mavg"), relationship="op"),
           label="Cross.Mid")

#Add rules
add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cl.gt.UpperBand",sigval=TRUE,orderqty=-100,ordertype="market",
                        orderside=NULL),type="enter")
add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cl.lt.LowerBand",sigval=TRUE,orderqty=100,ordertype="market",
                        ordertype=NULL),type="enter")
add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cross.Mid",sigval=TRUE,orderqty="all",ordertype="market",
                        orderside=NULL), type="exit")

#Applying strategy to a multi-asset portfolio
SD=2
N=20

out <- applyStrategy(strategy = "bbands",portfolios = "multiAsset.bb1",parameters = list(sd=SD,n=N))

#Data integrity check
checkBlotterUpdate <- function(port.st,account.st,verbose=TRUE)
{
  ok <- TRUE
  p <- getPortfolio(port.st)
  a <- getAccount(account.st)
  syms <- names(p$symbols)
  port.tot <- sum(sapply(syms,FUN = function(x) eval(parse(
    text=paste("sum(p$symbols",x,"posPL.USD$Net.Trading.PL)",sep="$")))))
  port.sum.tot <- sum(p$summary$Net.Trading.PL)
  if( !isTRUE(all.equal(port.tot,port.sum.tot)) ) {
    ok <- FALSE
    if( verbose )
      print("portfolio P&L doesn't match sum of symbols P&L")
  }
  initEq <- as.numeric(first(a$summary$End.Eq))
  endEq <- as.numeric(last(a$summary$End.Eq))
  if( !isTRUE(all.equal(port.tot,endEq-initEq)) ) {
    ok <- FALSE
    if( verbose )
      print("portfolio P&L doesn't match account P&L")
  }
  if( sum(duplicated(index(p$summary))) ) {
    ok <- FALSE
    if( verbose )
      print("duplicate timestamps in portfolio summary")
  }
  if( sum(duplicated(index(a$summary))) ) {
    ok <- FALSE
    if( verbose )
      print("duplicate timestamps in account summary")
  }
  return(ok)
}
checkBlotterUpdate("multiAsset.bb1","multiAsset.bb1")

#Chart performance for one of the assets
args(chart.Posn)
chart.Posn("multiAsset.bb1", "XLB", TA="add_BBands(n=20, sd=2)", theme=myTheme)
chart.Posn("multiAsset.bb1", "XLB", TA="add_BBands(n=20, sd=2)", Dates="2010", theme=myTheme)

#Initialize portfolio, account, and orders object
rm.strat(name="multiAsset.bb2")
initPortf(name="multiAsset.bb2", symbols, initDate = initDate)
initAcct(name="multiAsset.bb2", portfolios = "multiAsset.bb2", initDate = initDate, initEq = initEq)
initOrders(portfolio = "multiAsset.bb2", initDate = initDate)

SD=3
out <- applyStrategy(strategy="bbands", portfolios="multiAsset.bb2",parameters=list(sd=SD,n=N))

updatePortf("multiAsset.bb2")
updateAcct("multiAsset.bb2")
updateEndEq("multiAsset.bb2")

checkBlotterUpdate("multiAsset.bb2","multiAsset.bb2")

eq1 <- getAccount("multiAsset.bb1")$summary$End.Eq
rt1 <- Return.calculate(eq1,"log")
eq2 <- getAccount("multiAsset.bb2")$summary$End.Eq
rt2 <- Return.calculate(eq2,"log")
returns <- cbind(rt1,rt2)
colnames(returns) <- c("SD=2", "SD=3")
chart.CumReturns(returns,colorset = c(2,4),legend.loc = "topleft", main="BBand SD Parameter Comparison",minor.ticks=FALSE)

I just ran your code and your problem is that the SD=2 column is all NA, also your first row in both columns is NA. The error pretty much says your XTS call is screwed up so that would be the first thing to check.

Also look at your eq1 value, it is only a single return from 2009-12-31. while eq2 is a complete series. Somewhere you screwed up your testing or saving the result. So of course you cant chart the return because your series is just NAs.

Reply With Quote
 
  #5 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received


treydog999 View Post
I just ran your code and your problem is that the SD=2 column is all NA, also your first row in both columns is NA. The error pretty much says your XTS call is screwed up so that would be the first thing to check.

Also look at your eq1 value, it is only a single return from 2009-12-31. while eq2 is a complete series. Somewhere you screwed up your testing or saving the result. So of course you cant chart the return because your series is just NAs.

Hi @treydog999

Thank you for your comments. I will check ASAP and see if I can solve it. Do you have any comments on my last post regarding the difference between " and ' ?
Thank you very much for you help!

Reply With Quote
 
  #6 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received


treydog999 View Post
I just ran your code and your problem is that the SD=2 column is all NA, also your first row in both columns is NA. The error pretty much says your XTS call is screwed up so that would be the first thing to check.

Also look at your eq1 value, it is only a single return from 2009-12-31. while eq2 is a complete series. Somewhere you screwed up your testing or saving the result. So of course you cant chart the return because your series is just NAs.

 
Code
#Add rules
add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cl.gt.UpperBand",
                        sigval=TRUE,
                        orderqty=-100,
                        ordertype="market",
                        orderside=NULL),
                        type="enter")

add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cl.lt.LowerBand",
                        sigval=TRUE,
                        orderqty=100,
                        ordertype="market",
                        ordertype=NULL) #should be orderside
                        type="enter")

add.rule("bbands", name="ruleSignal",
         arguments=list(sigcol="Cross.Mid",
                        sigval=TRUE,
                        orderqty="all",
                        ordertype="market",
                        orderside=NULL),
                        type="exit")
and I had missed to add this important code after the applyStrategy.
 
Code
updatePortf("multiAsset.bb1")
updateAcct("multiAsset.bb1")
updateEndEq("multiAsset.bb1")
Now it is running OK.
 
Code
#Initialization
library(quantstrat)
startDate <- "2010-01-01"
endDate <- "2013-07-31"
symbols = c("XLF","XLP","XLE","XLY","XLV","XLI","XLB","XLK","XLU")
Sys.setenv(TZ="UTC")

getSymbols(symbols, src="yahoo",index.class=c("POSIXt","POSIXct"),from=startDate,to=endDate,adjust=TRUE)
#Plot time series of portfolio constituents
myTheme <- chart_theme()
myTheme$col$dn.col <- "lightblue"
myTheme$col$dn.border <- "lightgray"
myTheme$col$up.border <- "lightgray"

par(mfrow = c(3,3))
for(symbol in symbols)
{
  plot(chart_Series(get(symbol), name=symbol, theme=myTheme))
}
par(mfrow = c(1,1))

#Initialize instruments
initDate <- "2009-12-31"
initEq <- 1e6
currency("USD")
stock(symbols,currency = "USD", multiplier = 1)

#Calculate and plot Bollinger bands
args(BBands)
b <- BBands(HLC=HLC(XLF["2013"]), n=20, sd=2)
tail(b)
chart_Series(XLF["2013"], TA="add_BBands(lwd=2)", theme = myTheme, name="XLF")

#Initialize portfolio, account, and orders object
rm.strat(name="multiAsset.bb1")
initPortf(name="multiAsset.bb1", symbols, initDate = initDate)
initAcct(name="multiAsset.bb1", portfolios = "multiAsset.bb1", initDate = initDate, initEq = initEq)
initOrders(portfolio = "multiAsset.bb1", initDate=initDate)

#Define indicators
strategy("bbands", store = TRUE)

# add.indicator("bbands", name = "BBands",
#               arguments=list(HLC=quote(HLC(mktdata)), maType="SMA"), label = "BBands")

add.indicator("bbands", name = "BBands",
              arguments = list(HLC = quote(HLC(mktdata)), maType='SMA'), label='BBands')

#Define signals
# add.signal("bbands", name="sigCrossover",
#            arguments=list(columns=c("Close", "up"),relationship="gt"),
#            label="Cl.gt.UpperBand")
# 
# add.signal("bbands", name="sigCrossover",
#            arguments=list(columns=c("Close", "dn"), relationship="lt"),
#            label="Cl.lt.LowerBand")
# 
# add.signal("bbands", name="sigCrossover",
#            arguments=list(columns=c("High", "Low", "mavg"), relationship="op"),
#            label="Cross.Mid")

add.signal("bbands", name="sigCrossover",
           arguments=list(columns=c("Close","up"),relationship="gt"),
           label="Cl.gt.UpperBand")
add.signal("bbands", name="sigCrossover",
           arguments=list(columns=c("Close","dn"),relationship="lt"),
           label="Cl.lt.LowerBand")
add.signal("bbands", name="sigCrossover",
           arguments=list(columns=c("High","Low","mavg"),relationship="op"),
           label="Cross.Mid")

#Add rules
# add.rule("bbands", name="ruleSignal",
#          arguments=list(sigcol="Cl.gt.UpperBand",
#                         sigval=TRUE,
#                         orderqty=-100,
#                         ordertype="market",
#                         orderside=NULL),
#                         type="enter")
# 
# add.rule("bbands", name="ruleSignal",
#          arguments=list(sigcol="Cl.lt.LowerBand",
#                         sigval=TRUE,
#                         orderqty=100,
#                         ordertype="market",
#                         orderside=NULL),
#                         type="enter")
# 
# add.rule("bbands", name="ruleSignal",
#          arguments=list(sigcol="Cross.Mid",
#                         sigval=TRUE,
#                         orderqty="all",
#                         ordertype="market",
#                         orderside=NULL),
#                         type="exit")

add.rule("bbands", name='ruleSignal',
         arguments=list(sigcol="Cl.gt.UpperBand",sigval=TRUE, orderqty=-100,
                        ordertype='market', orderside=NULL),type='enter')
add.rule("bbands", name='ruleSignal',
         arguments=list(sigcol="Cl.lt.LowerBand",sigval=TRUE, orderqty= 100,
                        ordertype='market', orderside=NULL),type='enter')
add.rule("bbands", name='ruleSignal',
         arguments=list(sigcol="Cross.Mid",sigval=TRUE, orderqty= 'all',
                        ordertype='market', orderside=NULL),type='exit')


#Applying strategy to a multi-asset portfolio
SD=2
N=20

out <- applyStrategy(strategy ="bbands",portfolios="multiAsset.bb1",parameters=list(sd=SD,n=N))

updatePortf("multiAsset.bb1")
updateAcct("multiAsset.bb1")
updateEndEq("multiAsset.bb1")

#Chart performance for one of the assets
#chart.Posn("multiAsset.bb1", "XLB", TA="add_BBands(n=20, sd=2)", theme=myTheme)
#chart.Posn("multiAsset.bb1", "XLB", TA="add_BBands(n=20, sd=2)", Dates="2010", theme=myTheme)

#Initialize portfolio, account, and orders object
rm.strat(name="multiAsset.bb2")
initPortf(name="multiAsset.bb2", symbols, initDate = initDate)
initAcct(name="multiAsset.bb2", portfolios = "multiAsset.bb2", initDate = initDate, initEq = initEq)
initOrders(portfolio = "multiAsset.bb2", initDate = initDate)

SD=3

out <- applyStrategy(strategy="bbands",portfolios="multiAsset.bb2",parameters=list(sd=SD,n=N))

updatePortf("multiAsset.bb2")
updateAcct("multiAsset.bb2")
updateEndEq("multiAsset.bb2")

eq1 <- getAccount("multiAsset.bb1")$summary$End.Eq
rt1 <- Return.calculate(eq1,"log")
eq2 <- getAccount("multiAsset.bb2")$summary$End.Eq
rt2 <- Return.calculate(eq2,"log")
returns <- cbind(rt1,rt2)
colnames(returns) <- c("SD=2", "SD=3")
chart.CumReturns(returns,colorset = c(2,4),legend.loc = "topleft", main="BBand SD Parameter Comparison",minor.ticks=FALSE)

Attached Files
Register to download File Type: r Long-short_Bollinger_Band_reversal_strategy.R (4.9 KB, 21 views)

Last edited by donedge; November 13th, 2014 at 01:00 AM.
Reply With Quote
 
  #7 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received


donedge View Post
My code is commented out..

I get error when I use that code.

When I use ' instead of " it works. I thought R is working with both? Or is this not the case?

Thanks for any help!

 
Code
strategy("bb.lim", store = TRUE)
}
#Define indicators and signals
# add.indicator("bb.lim","BBands",
#            arguments=list(HLC=quote(HLC(mktdata)),maType="SMA"),label="BBands")
# 
# add.signal("bb.lim",name="sigCrossover",
#            arguments=list(columns=c("Close","up"),relationship="gt"),label="Cl.gt.UpperBand")
# 
# add.signal("bb.lim",name="sigCrossover",
#            arguments=list(columns=c("Close","dn"),relationship="lt"),label="Cl.lt.LowerBand")
# 
# add.signal("bb.lim",name="sigCrossover",
#            arguments=list(columns=c("High","Low","mavg"),relationship="op"),label="Cross.Mid")
# 

add.indicator("bb.lim",name = "BBands",
            arguments=list(HLC=quote(HLC(mktdata)),maType='SMA'),label='BBands')

add.signal("bb.lim",name="sigCrossover",
            arguments=list(columns=c("Close","up"),relationship="gt"),label="Cl.gt.UpperBand")

add.signal("bb.lim",name="sigCrossover",
            arguments=list(columns=c("Close","dn"),relationship="lt"),label="Cl.lt.LowerBand")

add.signal("bb.lim",name="sigCrossover",
            arguments=list(columns=c("High","Low","mavg"),relationship="op"),label="Cross.Mid")

#Add rules with an order sizing function specified
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="Cl.gt.UpperBand",
#                         sigval=TRUE,
#                         orderqty=-1000,
#                         ordertype="market",
#                         orderside=NULL,
#                         osFUN="osMaxPos"),
#                         type="enter")
# 
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="C.lt.LowerBand",
#                         sigval=TRUE,
#                         orderqty=1000,
#                         ordertype="market",
#                         orderside=NULL,
#                         osFUN="osMaxPos"),
#                         type="enter")
# 
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="Cross.Mid",
#                         sigval=TRUE,
#                         orderqty="all",
#                         ordertype="market",
#                         orderside=NULL),
#                         type="exit")

add.rule("bb.lim", name='ruleSignal',
          arguments=list(sigcol="Cl.gt.UpperBand",
                        sigval=TRUE,
                        orderqty=-1000,
                        ordertype='market',
                        orderside=NULL,
                        osFUN='osMaxPos'),
                        type='enter')

add.rule("bb.lim", name='ruleSignal',
          arguments=list(sigcol="Cl.lt.LowerBand",
                        sigval=TRUE,
                        orderqty= 1000,
                        ordertype='market',
                        orderside=NULL,
                        osFUN='osMaxPos'),
                        type='enter')

add.rule("bb.lim", name='ruleSignal',
          arguments=list(sigcol="Cross.Mid",
                        sigval=TRUE,
                        orderqty= 'all',
                        ordertype='market',
                        orderside=NULL),
                        type='exit')

Found the error.
 
Code
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="C.lt.LowerBand",
#                         sigval=TRUE,
#                         orderqty=1000,
#                         ordertype="market",
#                         orderside=NULL,
#                         osFUN="osMaxPos"),
#                         type="enter")
Should of course be

 
Code
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="Cl.lt.LowerBand",
#                         sigval=TRUE,
#                         orderqty=1000,
#                         ordertype="market",
#                         orderside=NULL,
#                         osFUN="osMaxPos"),
#                         type="enter")
With that, I found out that it does not matter what is used " or ' both work. What a flexible language.

Attached Files
Register to download File Type: r Max_position_order_sizing-BBands_strategy.R (4.2 KB, 9 views)

Last edited by donedge; November 13th, 2014 at 03:48 AM.
Reply With Quote
 
  #8 (permalink)
Elite Member
seoul, Korea
 
Futures Experience: Intermediate
Platform: Multicharts
Broker/Data: CQG, DTN IQfeed
Favorite Futures: YM 6E
 
treydog999's Avatar
 
Posts: 894 since Jul 2012
Thanks: 291 given, 1,006 received


donedge View Post
Found the error.
 
Code
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="C.lt.LowerBand",
#                         sigval=TRUE,
#                         orderqty=1000,
#                         ordertype="market",
#                         orderside=NULL,
#                         osFUN="osMaxPos"),
#                         type="enter")
Should of course be

 
Code
# add.rule("bb.lim", name="ruleSignal",
#          arguments=list(sigcol="Cl.lt.LowerBand",
#                         sigval=TRUE,
#                         orderqty=1000,
#                         ordertype="market",
#                         orderside=NULL,
#                         osFUN="osMaxPos"),
#                         type="enter")
With that, I found out that it does not matter what is used " or ' both work. What a flexible language.

I think there is a difference in R between " and '. Although pertaining to strings it makes both of them a literal. Honestly I looked for an answer to this a while ago and forgot. Because 99% of the time the functionality is identical.

Reply With Quote
The following user says Thank You to treydog999 for this post:
 
  #9 (permalink)
Elite Member
Stockholm
 
Futures Experience: Advanced
Platform: NinjaTrader,Sierra Chart, Python
Broker/Data: IB
Favorite Futures: ES & Stocks
 
Posts: 86 since Apr 2013
Thanks: 80 given, 71 received

Hello!

I'm having a issue with the heatmap...

 
Code
#Heatmaps of strategy performance
library(grDevices)
z <- tapply(X=results$tradeStats$Profit.To.Max.Draw, INDEX=list(results$tradeStats$TrailingLONG,results$tradeStats$StopLossLONG),FUN=median)
x <- as.numeric(rownames(z))
y <- as.numeric(colnames(z))
filled.contour(x=x,y=y,z=z,color = heat.colors,xlab="Trailing Stop",ylab="Stop Loss")
title("Return to MaxDrawdown")
I get this error:

 
Code
> #Heatmaps of strategy performance
> library(grDevices)
> z <- tapply(X=results$tradeStats$Profit.To.Max.Draw, INDEX=list(results$tradeStats$TrailingLONG,results$tradeStats$StopLossLONG),FUN=median)
Error in split.default(X, group) : first argument must be a vector
> x <- as.numeric(rownames(z))
Error in rownames(z) : object 'z' not found
> y <- as.numeric(colnames(z))
Error in is.data.frame(x) : object 'z' not found
> filled.contour(x=x,y=y,z=z,color = heat.colors,xlab="Trailing Stop",ylab="Stop Loss")
Error in filled.contour(x = x, y = y, z = z, color = heat.colors, xlab = "Trailing Stop",  : 
  object 'x' not found
> title("Return to MaxDrawdown")
>
Please help!

The whole strat:
 
Code
#Baseline MACD strategy (Long-only MACD momentum strategy)
#Buy rule: Buy long when the MACD signal crosses above 0
#Exit rule: Sell when the MACD signal crosses below 0

#Fetch data and initialize financial instruments
library(quantstrat)

startDate <- "2010-01-01" # start of data
endDate <- "2013-07-31" # end of data
symbols = c("ITOT", "AGG", "GLD", "VNQ")
Sys.setenv(TZ="UTC") # set time zone
getSymbols(symbols, src="yahoo", index.class=c("POSIXt","POSIXct"),from=startDate, to=endDate,adjust=TRUE)

initDate <- "2009-12-31"
initEq <- 1e6
currency("USD")
stock(symbols, currency="USD",multiplier=1)

#Plot time series of portfolio constituents
myTheme<-chart_theme()
myTheme$col$dn.col<-"lightblue"
myTheme$col$dn.border <- "lightgray"
myTheme$col$up.border <- "lightgray"

par(mfrow=c(2,2))
for(symbol in symbols)
{
  plot(chart_Series(get(symbol),name=symbol))
}
par(mfrow=c(1,1))

#Fixed-dollar order sizing function
osFixedDollar <- function(timestamp,orderqty, portfolio, symbol, ruletype, ...)
{
  ClosePrice <- as.numeric(Cl(mktdata[timestamp,]))
  orderqty <- round(tradeSize/ClosePrice,-2)
  return(orderqty)
}

#Define indicators and signals
strategy("macd",store = TRUE)
add.indicator("macd", name = "MACD",arguments = list(x=quote(Cl(mktdata))),label = "osc")

add.signal("macd",name="sigThreshold",arguments = list(column="signal.osc",relationship="gt",threshold=0,cross=TRUE),label = "signal.gt.zero")
add.signal("macd",name="sigThreshold",arguments = list(column="signal.osc",relationship="lt",threshold=0,cross=TRUE),label = "signal.lt.zero")

#Long entry rule
add.rule("macd", name="ruleSignal",
         arguments=list(sigcol="signal.gt.zero",
                    sigval=TRUE,
                    replace=FALSE,
                    orderside="long",
                    ordertype="market",
                    orderqty=100,
                    osFUN="osFixedDollar",
                    orderset="ocolong"),
                    type="enter",label="LE")

#Long exit rule
add.rule("macd", name="ruleSignal",
         arguments=list(sigcol="signal.lt.zero",
                        sigval=TRUE,
                        replace=FALSE,
                        orderside="long",
                        ordertype="market",
                        orderqty="all",
                        orderset="ocolong"),
                        type="exit",label="LX")

#Data integrity check
#Verifies portfolio P&L and account summary P&L match
#Verifies no duplicate rows in summary objects

checkBlotterUpdate <- function(port.st,account.st,verbose=TRUE)
{
  ok <- TRUE
  p <- getPortfolio(port.st)
  a <- getAccount(account.st)
  syms <- names(p$symbols)
  port.tot <- sum(sapply(syms,FUN = function(x) eval(parse(
    text=paste("sum(p$symbols",x,"posPL.USD$Net.Trading.PL)",sep="$")))))
  port.sum.tot <- sum(p$summary$Net.Trading.PL)
  if( !isTRUE(all.equal(port.tot,port.sum.tot)) ) {
    ok <- FALSE
    if( verbose )
      print("portfolio P&L doesn't match sum of symbols P&L")
  }
  initEq <- as.numeric(first(a$summary$End.Eq))
  endEq <- as.numeric(last(a$summary$End.Eq))
  if( !isTRUE(all.equal(port.tot,endEq-initEq)) ) {
    ok <- FALSE
    if( verbose )
      print("portfolio P&L doesn't match account P&L")
  }
  if( sum(duplicated(index(p$summary))) ) {
    ok <- FALSE
    if( verbose )
      print("duplicate timestamps in portfolio summary")
  }
  if( sum(duplicated(index(a$summary))) ) {
    ok <- FALSE
    if( verbose )
      print("duplicate timestamps in account summary")
  }
  return(ok)
}

#Initialize portfolio/account, apply strategy and verify
rm.strat("multi.macd.nostop") # remove portfolio, account, orderbook if re-run
initPortf(name="multi.macd.nostop", symbols, initDate=initDate)
initAcct(name="multi.macd.nostop", portfolios="multi.macd.nostop",initDate=initDate, initEq=initEq)
initOrders(portfolio="multi.macd.nostop", initDate=initDate)
fastMA = 12
slowMA = 26
signalMA = 9
maType="EMA"
tradeSize <- initEq/10
out<-applyStrategy("macd" , portfolios="multi.macd.nostop",parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType),verbose=TRUE)
updatePortf("multi.macd.nostop")
updateAcct("multi.macd.nostop")
updateEndEq("multi.macd.nostop")
checkBlotterUpdate("multi.macd.nostop","multi.macd.nostop")

#Performance results with no stoploss
equity.curve <- getAccount("multi.macd.nostop")$summary$End.Eq
returns.ns <- Return.calculate(equity.curve,"log")
table.AnnualizedReturns(returns.ns)

#Performance summary with no stoploss
charts.PerformanceSummary(returns.ns,wealth.index=TRUE,colorset="blue",xlab="",main="MACD Performance (no stoploss)",minor.ticks=FALSE)

#Trade stats for MACD strategy with no stoploss
PerformanceAnalytics:::textplot(t(tradeStats("multi.macd.nostop")))

#Maximum adverse excursion for VNQ no stoploss
chart.ME("multi.macd.nostop",'VNQ',type='MAE',scale='percent')

ob <- getOrderBook("multi.macd.nostop")$multi.macd.nostop$VNQ
ob.df <- data.frame(Date=time(ob),coredata(ob),stringsAsFactors=FALSE)
ob.df$Order.Price <- round(as.numeric(ob.df$Order.Price),3)

#Order book for VNQ no stoploss
PerformanceAnalytics:::textplot(ob.df,show.rownames=F)

#Add stoploss order to MACD strategy
#Long stop loss
stopLossPercent <- 0.05

add.rule("macd",name="ruleSignal",
         arguments = list(sigcol="signal.gt.zero", sigval=TRUE,
                          replace=FALSE,
                          orderside="long",
                          ordertype="stoplimit",
                          tmult=TRUE,
                          threshold=quote(stopLossPercent),
                          orderqty="all",
                          orderset="ocolong"),
                          type="chain", parent="LE",
                          label="StopLossLong",
                          enabled=FALSE)

rm.strat("multi.macd.stop") # remove portfolio, account, orderbook if re-run
initPortf(name="multi.macd.stop", symbols, initDate=initDate)
initAcct(name="multi.macd.stop", portfolios="multi.macd.stop",initDate=initDate, initEq=initEq)
initOrders(portfolio="multi.macd.stop", initDate=initDate)
enable.rule("macd",type="chain",label="StopLoss")
out<-applyStrategy("macd" , portfolios="multi.macd.stop",parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType),verbose=TRUE)
updatePortf("multi.macd.stop")
updateAcct("multi.macd.stop")
updateEndEq("multi.macd.stop")
checkBlotterUpdate("multi.macd.stop","multi.macd.stop")

#Performance results with stoploss
equity.curve <- getAccount("multi.macd.stop")$summary$End.Eq
returns.sl <- Return.calculate(equity.curve,"log")
table.AnnualizedReturns(returns.sl)

charts.PerformanceSummary(returns.sl,wealth.index=TRUE,colorset="blue",xlab="",main="MACD Performance (with stoploss)",minor.ticks=FALSE)
PerformanceAnalytics:::textplot(t(tradeStats("multi.macd.stop")))
chart.ME("multi.macd.stop",'VNQ',type='MAE',scale='percent')

ob <- getOrderBook("multi.macd.stop")$multi.macd.stop$VNQ
ob.df <- data.frame(Date=time(ob),coredata(ob),stringsAsFactors=FALSE)
ob.df$Order.Price <- round(as.numeric(ob.df$Order.Price),3)
PerformanceAnalytics:::textplot(ob.df,show.rownames=F)

#Add trailing stop to MACD strategy
trailingStopPercent <- 0.07
add.rule("macd", name = "ruleSignal",
         arguments=list(sigcol="signal.gt.zero" , sigval=TRUE,
                        replace=FALSE,
                        orderside="long",
                        ordertype="stoptrailing",
                        tmult=TRUE,
                        threshold=quote(trailingStopPercent),
                        orderqty="all",
                        orderset="ocolong"),
                        type="chain", parent="LE",
                        label="StopTrailingLong",
                        enabled=FALSE)

#Enable trailing stop rule
rm.strat("multi.macd.trail") # remove portfolio, account, orderbook if re-run
initPortf(name="multi.macd.trail", symbols, initDate=initDate)
initAcct(name="multi.macd.trail", portfolios="multi.macd.trail",initDate=initDate, initEq=initEq)
initOrders(portfolio="multi.macd.trail", initDate=initDate)
enable.rule("macd",type="chain",labe="StopTrailingLong")
out<-applyStrategy("macd" , portfolios="multi.macd.trail",parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType),verbose=TRUE)
updatePortf("multi.macd.trail")
updateAcct("multi.macd.trail")
updateEndEq("multi.macd.trail")

checkBlotterUpdate("multi.macd.trail","multi.macd.trail")

equity.curve <- getAccount("multi.macd.trail")$summary$End.Eq
returns.tr <- Return.calculate(equity.curve,"log")
table.AnnualizedReturns(returns.tr)

charts.PerformanceSummary(returns.tr,wealth.index=TRUE,colorset="blue",xlab="",main="MACD Performance (with stoploss)",minor.ticks=FALSE)

PerformanceAnalytics:::textplot(t(tradeStats("multi.macd.trail")))
chart.ME("multi.macd.trail",'VNQ',type='MAE',scale='percent')

ob <- getOrderBook("multi.macd.trail")$multi.macd.trail$VNQ
ob <- ob[ob$Order.Status=="closed",]
ob.df <- data.frame(Date=time(ob),coredata(ob),stringsAsFactors=FALSE)
ob.df$Order.Price <- round(as.numeric(ob.df$Order.Price),3)
PerformanceAnalytics:::textplot(ob.df,show.rownames=F)

#Optimize stops
stopLossPercentRange <- seq(0.03,0.05,by=0.01)

add.distribution("macd",
                 paramset.label = "STOPOPT",
                 component.type = "chain",
                 component.label = "StopLossLong",
                 variable = list( threshold = stopLossPercentRange ),
                 label = "StopLossLONG")

#Initialize portfolio/account, apply strategy and verify
rm.strat("multi.macd.opt") # remove portfolio, account, orderbook if re-run
initPortf(name="multi.macd.opt", symbols, initDate=initDate)
initAcct(name="multi.macd.opt", portfolios="multi.macd.opt",initDate=initDate, initEq=initEq)
initOrders(portfolio="multi.macd.opt", initDate=initDate)
library(parallel)
detectCores()

if( Sys.info()['sysname'] == "Windows" )
{
  library(doParallel)
} else {
  library(doMC)
  registerDoMC(cores=detectCores())
}

#Apply strategy and verify
if( file.exists("resultsStopOpt.RData") )
{
  load("resultsStopOpt.RData")
} else {
  results <- apply.paramset("macd", paramset.label = "STOPOPT",portfolio="multi.macd.opt", account="multi.macd.opt", nsamples=0)
  save(list="results",file="resultsStopOpt.RData")
}
head(names(results),20)

#Heatmaps of strategy performance
library(grDevices)
z <- tapply(X=results$tradeStats$Profit.To.Max.Draw, INDEX=list(results$tradeStats$TrailingLONG,results$tradeStats$StopLossLONG),FUN=median)
x <- as.numeric(rownames(z))
y <- as.numeric(colnames(z))
filled.contour(x=x,y=y,z=z,color = heat.colors,xlab="Trailing Stop",ylab="Stop Loss")
title("Return to MaxDrawdown")

#Define indicators and signals
strategy("macd.opt", store=TRUE)
add.indicator("macd.opt", name = "MACD",
              arguments = list(x=quote(Cl(mktdata))),label='osc')

add.signal("macd.opt",name="sigThreshold",
           arguments=list(column="signal.osc",relationship="gt",threshold=0,cross=TRUE),
           label="signal.gt.zero")

add.signal("macd.opt",name="sigThreshold",
           arguments=list(column="signal.osc",relationship="lt",threshold=0,cross=TRUE),
           label="signal.lt.zero")

#Long entry/exit rule
add.rule("macd.opt",name='ruleSignal',
         arguments = list(sigcol="signal.gt.zero", sigval=TRUE,
                          replace=FALSE,
                          orderside='long',
                          ordertype='market',
                          orderqty=100,
                          osFUN='osFixedDollar',
                          orderset='ocolong'),
                          type='enter',
                          label='LE')

add.rule("macd.opt",name='ruleSignal',
         arguments = list(sigcol="signal.lt.zero", sigval=TRUE,
                          replace=TRUE,
                          orderside='long',
                          ordertype='market',
                          orderqty='all',
                          orderset='ocolong'),
                          type='exit',
                          label='LX')

#Long stop loss
stopLossPercent <- 0.03
add.rule("macd.opt",name='ruleSignal',
         arguments = list(sigcol="signal.gt.zero", sigval=TRUE,
                          replace=FALSE,
                          orderside='long',
                          ordertype='stoplimit',
                          tmult=TRUE,
                          threshold=quote( stopLossPercent ),
                          orderqty='all',
                          orderset='ocolong'),
                          type='chain', parent="LE",
                          label='StopLossLong',
                          enabled=TRUE)

#Trailing stop loss
trailingStopPercent <- 0.03
add.rule("macd.opt", name = 'ruleSignal',
         arguments=list(sigcol="signal.gt.zero" , sigval=TRUE,
                        replace=FALSE,
                        orderside='long',
                        ordertype='stoptrailing',
                        tmult=TRUE,
                        threshold=quote(trailingStopPercent),
                        orderqty='all',
                        orderset='ocolong'),
                        type='chain', parent="LE",
                        label='StopTrailingLong',
                        enabled=TRUE)

#Apply optimal settings
rm.strat("multi.macd.opt") # remove portfolio, account, orderbook if re-run
initPortf(name="multi.macd.opt", symbols, initDate=initDate)
initAcct(name="multi.macd.opt", portfolios="multi.macd.opt",initDate=initDate, initEq=initEq)
initOrders(portfolio="multi.macd.opt", initDate=initDate)
out <- applyStrategy("macd.opt" , portfolios="multi.macd.opt",
                   parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType),
                   verbose=TRUE)
updatePortf("multi.macd.opt")
updateAcct("multi.macd.opt")
updateEndEq("multi.macd.opt")
checkBlotterUpdate("multi.macd.opt","multi.macd.opt")

#Performance results with optimal settings
equity.curve <- getAccount("multi.macd.opt")$summary$End.Eq
returns.opt <- Return.calculate(equity.curve,"log")
table.AnnualizedReturns(returns.opt)

charts.PerformanceSummary(returns.opt,wealth.index=TRUE,colorset="blue",
                          xlab="",main="MACD Performance (with stoploss)",minor.ticks=FALSE)

PerformanceAnalytics:::textplot(t(tradeStats("multi.macd.opt")))

chart.ME("multi.macd.opt",'VNQ',type='MAE',scale='percent')

ob <- getOrderBook("multi.macd.opt")$multi.macd.opt$VNQ
ob <- ob[ob$Order.Status=="closed",]
ob.df <- data.frame(Date=time(ob),coredata(ob),stringsAsFactors=FALSE)
ob.df$Order.Price <- round(as.numeric(ob.df$Order.Price),3)
PerformanceAnalytics:::textplot(ob.df,show.rownames=F)

rets <- cbind(returns.ns,returns.sl,returns.tr,returns.opt)
colnames(rets) <- c("NoStops","StopLoss","StopAndTrail","Optimal")
charts.PerformanceSummary(rets,main="Stop Comparision")
chart.RiskReturnScatter(rets,main = "Risk Management Evolution", colorset = rich10equal)

Attached Files
Register to download File Type: r Baseline_MACD_strategy.R (14.9 KB, 9 views)
Reply With Quote
 
  #10 (permalink)
Elite Member
tel aviv
 
Futures Experience: Advanced
Platform: Multicharts, SC
Favorite Futures: es
 
Posts: 34 since Jun 2009
Thanks: 4 given, 1 received


I tried to run your code and got an error few times
the 1st was when run:
 
Code
for(symbol in symbols)
{
  plot(chart_Series(get(symbol), name=symbol, theme=myTheme))
}
par(mfrow = c(1,1))
and got the error:
Quoting 
Error in plot(chart_Series(get(symbol), name = symbol, theme = myTheme)) :
error in evaluating the argument 'x' in selecting a method for function 'plot': Error in .External.graphics(C_plot_window, xlim, ylim, log, asp, ...) :
invalid graphics state

and when got to:
 
Code
rm.strat(name="multiAsset.bb1")
I got an error:
Quoting 
Error in rm(list = paste("order_book", name, sep = "."), pos = .strategy) :
object '.strategy' not found

I will appriciate if anyone could asist on solving this
Thanks!

Reply With Quote

Reply



futures io > > > > Strategies coded in R

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)

Linda Bradford Raschke: Reading The Tape

Elite only

Adam Grimes: TBA

Elite only

NinjaTrader: TBA

January

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
SendMail() for strategies dsraider NinjaTrader Programming 34 January 17th, 2015 05:03 PM
Needed.Color coded script for ema(changes from red to green with trend)&Volume ind. Rad4633 NinjaTrader 5 October 16th, 2012 03:24 PM
Has anyone coded these indicators? solom113 NinjaTrader 10 July 21st, 2012 06:33 PM
Can a floating window be coded with Ninjascript ? trendisyourfriend NinjaTrader Programming 29 December 21st, 2010 05:02 AM
need paintbar study coded-PLEASE bobbyacim The Elite Circle 3 July 28th, 2010 03:35 PM


All times are GMT -4. The time now is 10:19 PM.

Copyright © 2017 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
All information is for educational use only and is not investment advice.
There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
no new posts
Page generated 2017-12-10 in 0.15 seconds with 20 queries on phoenix via your IP 54.221.73.186