Hi
OK, I have found this in the manual:
For the purposes of backtesting, and compatibility with the trade
accounting in blotter, this function will not allow a transaction to
cross your current position through zero. The accounting rules for
realizing gains in such cases are more complicated than we wish to
support. Also, many brokers will break, revise, or split such
transactions for the same reason. If you wish to do a "stop and reverse"
system, first stop (flatten), and then reverse (initiate a new position).
So now I know why I couldn't model short positions. is this correct?
Being able to go short is a pretty common sort of action.
I had a look at the bbands demo and it appeared to go long and short and
specified NULL as the ordertype rather than long or short. That got rid
of my warning that I was going short, but it didn't produce any short
trades.
Any help most welcome.
##########################################################
Original posting:
Hi
I'm trying to money the bbands demo to by it on the S&P/ ASX 200.
I think the Symbol is ^AXJO and I can get the info I want using it.
I have amended the code as follows:
# bbands
require(quantstrat)
try(rm("order_book.bbands",pos=.strategy),silent=TRUE)
try(rm("account.bbands","portfolio.bbands",pos=.blotter),silent=TRUE)
try(rm("account.st","portfolio.st","stock.str","stratBBands","initDate","initEq",'start_t','end_t'),silent=TRUE)
# some things to set up here
stock.str='^AXJO' # what are we trying it on
# we'll pass these
SD = 2 # how many standard deviations, traditionally 2
N = 20 # how many periods for the moving average, traditionally 20
currency('AUD')
stock(stock.str,currency='AUD',multiplier=1)
initDate='2006-12-31'
initEq=1000000
portfolio.st='bbands'
account.st='bbands'
initPortf(portfolio.st,symbols=stock.str, initDate=initDate)
initAcct(account.st,portfolios='bbands', initDate=initDate)
initOrders(portfolio=portfolio.st,initDate=initDate)
stratBBands <- strategy("bbands")
#one indicator
stratBBands <- add.indicator(strategy = stratBBands, name = "BBands",
arguments = list(HLC = quote(HLC(mktdata)), maType='SMA'))
#add signals:
stratBBands <- add.signal(stratBBands,name="sigCrossover",arguments =
list(columns=c("Close","up"),relationship="gt"),label="Cl.gt.UpperBand")
stratBBands <- add.signal(stratBBands,name="sigCrossover",arguments =
list(columns=c("Close","dn"),relationship="lt"),label="Cl.lt.LowerBand")
stratBBands <- add.signal(stratBBands,name="sigCrossover",arguments =
list(columns=c("High","Low","mavg"),relationship="op"),label="Cross.Mid")
# lets add some rules
stratBBands <- add.rule(stratBBands,name='ruleSignal', arguments =
list(sigcol="Cl.gt.UpperBand",sigval=TRUE, orderqty=-100,
ordertype='market', orderside=NULL, threshold=NULL),type='enter')
stratBBands <- add.rule(stratBBands,name='ruleSignal', arguments =
list(sigcol="Cl.lt.LowerBand",sigval=TRUE, orderqty= 100,
ordertype='market', orderside=NULL, threshold=NULL),type='enter')
stratBBands <- add.rule(stratBBands,name='ruleSignal', arguments =
list(sigcol="Cross.Mid",sigval=TRUE, orderqty= 'all',
ordertype='market', orderside=NULL, threshold=NULL),type='exit')
#alternately, to exit at the opposite band, the rules would be...
#stratBBands <- add.rule(stratBBands,name='ruleSignal', arguments =
list(data=quote(mktdata),sigcol="Lo.gt.UpperBand",sigval=TRUE, orderqty=
'all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
#stratBBands <- add.rule(stratBBands,name='ruleSignal', arguments =
list(data=quote(mktdata),sigcol="Hi.lt.LowerBand",sigval=TRUE, orderqty=
'all', ordertype='market', orderside=NULL, threshold=NULL),type='exit')
#TODO add thresholds and stop-entry and stop-exit handling to test
getSymbols(stock.str,from=initDate)
start_t<-Sys.time()
out<-try(applyStrategy(strategy=stratBBands ,
portfolios='bbands',mktdata='AXJO',
parameters=list(sd=SD,n=N),verbose=TRUE) )
# look at the order book
#getOrderBook('bbands')
end_t<-Sys.time()
print("strat execution time:")
print(end_t-start_t)
Time difference of 32.271 secs
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.Posn(Portfolio='bbands',Symbol=stock.str)
plot(add_BBands(on=1,sd=SD,n=N))
###############################################################################
# R (http://r-project.org/) Quantitative Strategy Model Framework
#
# Copyright (c) 2009-2010
# Peter Carl, Dirk Eddelbuettel, Brian G. Peterson, Jeffrey Ryan, and
Joshua Ulrich
#
# This library is distributed under the terms of the GNU Public
License (GPL)
# for full details see the file COPYING
#
# $Id: bbands.R 374 2010-08-17 18:43:35Z braverock $
#
###############################################################################
I get my prices with thus
getSymbols(stock.str,from=initDate)
[1] "AXJO"
but note the hat has been dropped!
and just afterwards I get thIs:
rategy=stratBBands , portfolios='bbands',
parameters=list(sd=SD,n=N),verbose=TRUE) )
Error in get(symbol) : object '^AXJO' not found
I've looked at the notes for applyStrategy and I've tried specifically
referring to AXJO like this:
out<-try(applyStrategy(strategy=stratBBands ,
portfolios='bbands',mktdata='AXJO',
parameters=list(sd=SD,n=N),verbose=TRUE) )
Error in get(symbol) : object '^AXJO' not found
but I still get the message.
Can anyone advise me how to resolve this?
'For the purposes of backtesting, and compatibility with the trade
accounting in blotter, this function will not allow a transaction to
cross your current position through zero. The accounting rules for
realizing gains in such cases are more complicated than we wish to
support. Also, many brokers will break, revise, or split such
transactions for the same reason. If you wish to do a "stop and reverse"
system, first stop (flatten), and then reverse (initiate a new position).'
So now I know why I couldn't model short positions. is this correct?
Being able to go short is a pretty common sort of action.
Yes, being able to go short is a pretty 'common sort of action'. I do
it every day across multiple instrument classes, currencies, and
millions of dollars of net portfolio position (after converting back to
USD).
Note that the bbands demo *as written* initiates short positions without
any problem. See attached pdf. That would likely suggest to anyone
writing code that modified the working demo that the problem was likely
in their code, not the package...
Do you not understand the documentation?
First flatten your position (get to zero) then initiate a short
position. stop. then reverse.
So, in the bbands demo, you would set up:
- a long entry entry at the lower band
- a long exit at the mid or upper band
- a short entry at the upper band
- a short exit at the mid or the lower band
The demo does that with three rules and using the orderside=NULL
convenience, but I could easily have left only the mid-cross rule as
orderside NULL and the other appropriate rules as 'long' and 'short'.
In a non-toy strategy, you'd probably also want to do something like
addPosLimit to set how many signals you'll respond to. Try one long and
one short to start.
I had a look at the bbands demo and it appeared to go long and short and
specified NULL as the ordertype rather than long or short. That got rid
of my warning that I was going short, but it didn't produce any short
trades.
Any help most welcome.
I had a look at the bbands demo and it appeared to go long and short and
specified NULL as the ordertype rather than long or short. That got rid
of my warning that I was going short, but it didn't produce any short
trades.
I've modified your broken code. Updated R code and PDF attached. It
goes short, as expected. The P&L is awful, also as expected.
Please take more time to debug your code in the future.
- Brian