Spreads in R (Quantstrat and FinancialInstrument) - Matlab, R project and Python | futures io social day trading
futures io futures trading


Spreads in R (Quantstrat and FinancialInstrument)
Updated: Views / Replies:4,566 / 14
Created: by treydog999 Attachments:0

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
 
Thread Tools Search this Thread
 

Spreads in R (Quantstrat and FinancialInstrument)

  #1 (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

Spreads in R (Quantstrat and FinancialInstrument)

I am attempting to use R to backtest a spread (self generated, not exchange based) and use that to generate signals for a pairs trading strategy. I am using Quantstrat and Financial Instrument package to do so. I can get a strategy to run and it will test the 2 underlying futures and the spread itself. However the spread trading results are very strange, its treating it as if the spread itself was the instrument and so it makes loses 1$ per tick. Instead of executing the trade on the underlying futures.

Example: strategy using ES and YM as underlying. Generate a spread using the notional Ratio of ES/ YM. Test using bollinger bands. The spread result will be something like -10$ for the spread, and test the bollinger band system on both the underlyings.

Has anyone else figured out how to use the spread function? I have not seen any demo code for it and am really struggling. If there is interest I can try to post some reproducible code so people can play with it and see what I am talking about.

Any resources or help on using spreads in quantstrat would be great. Thanks. Hopefully some r experts here can help. @Big Mike @IlyaKipnis

Reply With Quote
 
  #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
Zurich, Switzerland
 
Futures Experience: Intermediate
Platform: R, C#
Favorite Futures: Futures
 
Posts: 53 since Dec 2013
Thanks: 73 given, 71 received


Hi Treydog,

I haven't played around with spreads in Quantstrat yet. However, did you check out the following demo? https://r-forge.r-project.org/scm/viewvc.php/pkg/quantstrat/demo/pair_trade.R?view=markup&root=blotter

Simon

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


volemont View Post
Hi Treydog,

I haven't played around with spreads in Quantstrat yet. However, did you check out the following demo? https://r-forge.r-project.org/scm/viewvc.php/pkg/quantstrat/demo/pair_trade.R?view=markup&root=blotter

Simon

Yes i have worked with this extensively. It is basically a work around inserting transactions with a custom function. So you cant do like wfo or other optimizations because its not using the underlying structure. I was attempting to use the built-in spread function to try to get those features but its really not documented at all and the trade results make no sense.

volemont View Post
Hi Treydog,

I haven't played around with spreads in Quantstrat yet. However, did you check out the following demo? https://r-forge.r-project.org/scm/viewvc.php/pkg/quantstrat/demo/pair_trade.R?view=markup&root=blotter

Simon


Reply With Quote
 
  #5 (permalink)
Elite Member
Zurich, Switzerland
 
Futures Experience: Intermediate
Platform: R, C#
Favorite Futures: Futures
 
Posts: 53 since Dec 2013
Thanks: 73 given, 71 received

Ok I assume you already searched the R-SIG-Finance archives and Stackoverflow. I propose you create a minimal working example and post it either in

a) The R-SIG-Finance mailing list
b) Stackoverflow
c) IRC #R-Finance on freenode (be patient and idle in the channel)

Users as well the quanstrat authors regularly help users on the aforementioned platforms.

HTH,
Simon


Sent from my iPhone using Tapatalk

Reply With Quote
The following user says Thank You to volemont for this post:
 
  #6 (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


volemont View Post
Ok I assume you already searched the R-SIG-Finance archives and Stackoverflow. I propose you create a minimal working example and post it either in

a) The R-SIG-Finance mailing list
b) Stackoverflow
c) IRC #R-Finance on freenode (be patient and idle in the channel)

Users as well the quanstrat authors regularly help users on the aforementioned platforms.

HTH,
Simon


Sent from my iPhone using Tapatalk

I just posted it on the R Sig Finance list and hope to get a reply. here is a copy of the code incase your intrested.

 
Code
# attempt to create a pairs trading strategy using a spread from Financial Instrument package.
# Based on a Notional Spread and Standard Devations from the rolling mean

require(quantstrat)
require(Quandl)
require(quantmod)
#### Data Prep ####

#get data from Quandl 
symb1 <- Quandl("CHRIS/CME_ES1", type = "xts", trim_start="2010-01-01", trim_end="2014-11-17")
symb2 <- Quandl("CHRIS/CME_YM1", type = "xts", trim_start="2010-01-01", trim_end="2014-11-17")

#Trim and Format  - Using settlement as Close value
symb1 <- symb1[,c(1,2,3,6)]
symb2 <- symb2[,c(1,2,3,6)]

colnames(symb1) <- c("Open", "High", "Low", "Close")
colnames(symb2) <- c("Open", "High", "Low", "Close")

#Clean data so only dates where both trades exist
merge <- cbind(symb1, symb2)
dates <- index(merge[complete.cases(merge),])
symb1<- symb1[dates]
symb2<- symb2[dates]

# -----------------------STRATEGY-------------------
#clean variables for reruns
suppressWarnings(rm("order_book.bbands",pos=.strategy))
suppressWarnings(rm("account.bbands","portfolio.bbands",pos=.blotter))
suppressWarnings(rm("account.st","portfolio.st","stock.str","stratBBands","initDate","initEq",'start_t','end_t'))

#Initial values / parameters
initDate= index(symb1)[1]-1
initEq=100000

SD = 2 # how many standard deviations
N = 20 # length of moving average

#Initialize FinancialInstrument Objects

currency('USD')

future( primary_id = "symb1",
        currency = "USD",
        tick_size = .25,
        multiplier = 50)

future( primary_id = "symb2",
        currency = "USD",
        tick_size = 1,
        multiplier = 5)

#Create Spread Series
calcRatio <- function(x) { 
  #returns the ratio of notional close prices for 2 symbols
  x1 <- get(x[1])
  x2 <- get(x[2])
  mult1 <- getInstrument(x[1])$multiplier
  mult2 <- getInstrument(x[2])$multiplier
  rat.Op <- ((mult1 * Op(x1))) / (mult2 * Op(x2))
  rat.Hi <- ((mult1 * Hi(x1))) / (mult2 * Hi(x2))
  rat.Lo <- ((mult1 * Lo(x1))) / (mult2 * Lo(x2))
  rat.Cl <- ((mult1 * Cl(x1))) / (mult2 * Cl(x2))
  ratio <- cbind(rat.Op, rat.Hi, rat.Lo, rat.Cl)
  colnames(ratio) <- c("Open", "High", "Low", "Close")
  return(ratio)
}

Ratio <- calcRatio(c("symb1", "symb2"))

#Initialize Spread (using notional ratio as hedge ratio)
spread(primary_id = "symb1.symb2",
       currency = "USD",
       members = c("symb1", "symb2"),
       memberratio = list(1, as.numeric(-Cl(Ratio))) )  

#Notional Ratio is also spread for trading
symb1.symb2 <- Ratio

#name strings
portfolio.st = 'bbands'
account.st = 'bbands'

#initialization of strategy objects ----
initPortf(portfolio.st, #portfolio Initiatlization
          symbols = c("symb1.symb2", "symb1", "symb2"),
          initDate = initDate,
          currency = "USD",
          initPosQty = 0)

initAcct(account.st, #account initialization
         portfolios = portfolio.st,
         initDate = initDate,
         initEq = initEq)

initOrders(portfolio = portfolio.st, #orders initialize 
           initDate = initDate)

addPosLimit( portfolio = portfolio.st, # add position limit rules
             symbol = 'symb1.symb2',
             timestamp = initDate,
             maxpos = 1,
             longlevels = 1,
             minpos = -1)

addPosLimit( portfolio = portfolio.st, # add position limit rules
             symbol = 'symb1',
             timestamp = initDate,
             maxpos = 2,
             longlevels = 1,
             minpos = -2)

addPosLimit( portfolio = portfolio.st, # add position limit rules
             symbol = 'symb2',
             timestamp = initDate,
             maxpos = 2,
             longlevels = 1,
             minpos = -2)

stratBBands <- strategy("bbands") # strategy object init

# Indicator
stratBBands <- add.indicator(
  strategy = stratBBands,
  name = "BBands",
  arguments = list(
    HLC = quote(HLC(mktdata)),
    n = N,
    sd = SD,
    maType = "SMA"),
  label = "BBands")

# #Indi Debug
# summary(stratBBands)
# start_t <- Sys.time()
# applyIndicators( strategy = stratBBands, mktdata = Ratio)
# end_t<-Sys.time()
# print("strat execution time:")
# print(end_t-start_t)

# Add signals:
stratBBands <- add.signal(
  strategy = stratBBands,
  name = "sigCrossover",
  arguments = list(
    columns = c("Close","up.BBands"),
    relationship = "gt"),
  label = "Cl.gt.UpperBand")

stratBBands <- add.signal(
  strategy = stratBBands,
  name = "sigCrossover",
  arguments = list(
    columns = c("Close","dn.BBands"),
    relationship = "lt"),
  label = "Cl.lt.LowerBand")

stratBBands <- add.signal(
  strategy = stratBBands,
  name = "sigCrossover",
  arguments = list(
    columns = c("High","Low", "mavg.BBands"),
    relationship = "op"),
  label = "Cross.Mid")

# #Signal Debug
# summary(stratBBands)
# start_t <- Sys.time()
# applySignals(strategy = stratBBands, mktdata = applyIndicators(strategy = stratBBands, mktdata = Ratio))
# end_t<-Sys.time()
# print("strat execution time:")
# print(end_t-start_t)

# Rules -----

#Entry

stratBBands <- add.rule ( 
  strategy = stratBBands,
  name = "ruleSignal",
  arguments = list(
    sigcol = "Cl.gt.UpperBand",
    sigval = TRUE,
    orderqty = -1,
    ordertype = "market",
    orderside = "short",
    symbol = "symb1",
    replace = TRUE,
    osFUN = osMaxPos),
  type = "enter",
  label = "ShortSpread_symb1")

stratBBands <- add.rule ( 
  strategy = stratBBands,
  name = "ruleSignal",
  arguments = list(
    sigcol = "Cl.gt.UpperBand",
    sigval = TRUE,
    orderqty = 1,
    ordertype = "market",
    orderside = "long",
    symbol = "symb2",
    replace = TRUE,
    osFUN = osMaxPos),
  type = "enter",
  label = "ShortSpread_symb2")

stratBBands <- add.rule ( 
  strategy = stratBBands,
  name = "ruleSignal",
  arguments = list(
    sigcol = "Cl.lt.LowerBand",
    sigval = TRUE,
    orderqty = 1,
    ordertype = "market",
    orderside = "long"
    symbol = "symb1",
    replace = TRUE,
    osFUN = osMaxPos),
  type = "enter",
  label = "LongSpread_symb1")

stratBBands <- add.rule ( 
  strategy = stratBBands,
  name = "ruleSignal",
  arguments = list(
    sigcol = "Cl.lt.LowerBand",
    sigval = TRUE,
    orderqty = -1,
    ordertype = "market",
    orderside = "short",
    symbol = "symb2",
    replace = TRUE,
    osFUN = osMaxPos),
  type = "enter",
  label = "LongSpread_symb2")

# Exit 
stratBBands <- add.rule( 
  strategy = stratBBands,
  name = "ruleSignal",
  arguments = list(
    sigcol = "Cross.Mid",
    sigval = TRUE,
    orderqty = "all",
    ordertype = "market",
    TxnFees = 0,
    replace = TRUE),
  type = "exit",
  label = "Exit")


summary(stratBBands)

# Strategy Execution ----
start_t<-Sys.time()
out<-try(applyStrategy(strategy=stratBBands , 
                       portfolios="bbands"))
end_t<-Sys.time()
print("strat execution time:")
print(end_t-start_t)

# update portfolio
start_t<-Sys.time()
updatePortf(Portfolio='bbands',Dates=paste('::',as.Date(Sys.time()),sep=''))
end_t<-Sys.time()
print("updatePortf execution time:")
print(end_t-start_t)

#Chart
chart.Posn(Portfolio='bbands',Symbol="symb1")
plot(add_BBands(on=1,sd=SD,n=N))
chart.Posn(Portfolio='bbands',Symbol="symb2")
plot(add_BBands(on=1,sd=SD,n=N))
chart.Posn(Portfolio='bbands',Symbol="symb1.symb2")
plot(add_BBands(on=1,sd=SD,n=N))

#Stats
book <- getOrderBook("bbands")
stats <- tradeStats("bbands")
rets <- PortfReturns("bbands")
port <- getPortfolio("bbands")

Reply With Quote
The following 2 users say Thank You to treydog999 for this post:
 
  #7 (permalink)
Elite Member
tel aviv
 
Futures Experience: Advanced
Platform: Multicharts, SC
Favorite Futures: es
 
Posts: 34 since Jun 2009
Thanks: 4 given, 1 received

did you find a solution?

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


giladbi View Post
did you find a solution?

No not really. I have talked to some of the devs for the quantstrat project. It seems like they just want you to simulate the spread as a synthetic but not actually track your underlying. The link to the pairs trading example above is as far as they will go. Because this is an injection order rather than following the actual backtesting order management.

They said that quantstrat is not made to simulate your execution environment (in this case executing the underlying). But rather to fine tune your methodology, which using the spread itself should suffice. The reason they dont like that manual inject or executing on multiple underlying is because it makes it very slow to test.

Honestly at this point i am considering making my own backtest system, probably in python because it is a faster language and that the speed is one of the bottle necks . Although there isn't as good of facilties like blotter or performance analytics. I really need the spread functionality. I can always import the returns series back to R to analyze. I am actually mapping out the architecture now.

Reply With Quote
 
  #9 (permalink)
Elite Member
tel aviv
 
Futures Experience: Advanced
Platform: Multicharts, SC
Favorite Futures: es
 
Posts: 34 since Jun 2009
Thanks: 4 given, 1 received

or you can rebuild thse code in r as an xls like format which will give you the entry/exit prices

Reply With Quote
 
  #10 (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



giladbi View Post
or you can rebuild thse code in r as an xls like format which will give you the entry/exit prices

format is not really important, since R or Python can deal with time series XTS or Pandas. using something like excels xls really just bad. Also re building something so complex is really difficult, its not just a matter of changing formats or extracting entry and exit prices. Its not even running on the underlying time series, you would need to track those indepedantly then use the rules and apply strategy functions to output orders to those underlying and track that in a completely seperate blotter object or create your own extraction format. But again the developers caution against doing something like that because of speed bottle necks. So if I have to redo so much code and developing objects, I would rather just build something from the ground up purpose built to do what I need. Trust me I am an R lover, but in this case i need speed so python will be the language of choice.

Reply With Quote

Reply



futures io > > > > Spreads in R (Quantstrat and FinancialInstrument)

Thread Tools Search this Thread
Search this Thread:

Advanced Search



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

Jigsaw Trading: TBA

Elite only

FuturesTrader71: TBA

Elite only

NinjaTrader: TBA

Jan 18

RandBots: TBA

Jan 23

GFF Brokers & CME Group: Futures & Bitcoin

Elite only

Adam Grimes: TBA

Elite only

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
R Backtesting and Optimization: Quantstrat Big Mike Matlab, R project and Python 16 February 14th, 2015 09:06 PM
WFA (walk forward analysis) Result using quantstrat R treydog999 Matlab, R project and Python 3 October 21st, 2014 11:22 AM
Preventing Look Forward Bias in Quantstrat/R treydog999 Matlab, R project and Python 4 September 8th, 2014 02:18 PM
Outright or Spreads? joeyk Bonds and Interest Rates Trading 31 July 16th, 2014 10:07 AM
Credit Spreads Trendi Options on Futures 7 January 29th, 2013 11:49 PM


All times are GMT -4. The time now is 05:31 AM.

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-16 in 0.14 seconds with 19 queries on phoenix via your IP 54.160.245.121