[R-SIG-Finance] bbands demo
Stephen Choularton
stephen at organicfoodmarkets.com.au
Thu Apr 21 07:45:24 CEST 2011
Hi
I've been playing around with bbands demo but I cannot got it working.
I think the problem is that on the same day the close both fell below
the upper boundary and below the mean and the second got ignored.
Can anyone help me to get this code to do what it should be doing?
code;
# btest.R
# code to backtest spread trading based on cointegration and reversion
to mean ('cir')
# ok, what I will do is to see if I can write a rule that goes short if
price is above two standard deviations and goes below and closes at
average and vice versa.
require(quantstrat)
try(rm("order_book.cir",pos=.strategy),silent=TRUE)
try(rm("account.cir","portfolio.cir",pos=.blotter),silent=TRUE)
try(rm("account.st","portfolio.st","stock.str","s","initDate","initEq",'start_t','end_t'),silent=TRUE)
# some things to set up here
stock.str='IBM' # what are we trying it on
SD = 2 # how many standard deviations, traditionally 2
N = 20 # how many periods for the moving average
currency('USD')
stock(stock.str,currency='USD',multiplier=1)
initDate='2011-01-31' # use a short period for eyeballing
initEq=1000000
portfolio.st='cir'
account.st='cir'
initPortf(portfolio.st,symbols=stock.str, initDate=initDate)
initAcct(account.st,portfolios='cir', initDate=initDate)
initOrders(portfolio=portfolio.st,initDate=initDate)
s <- strategy("cir")
####### INDICATOR #######
#s <- add.indicator(strategy = s, name = "SMA", arguments = list(x =
quote(Cl(mktdata)), n=10), label="SMA10")
# thus puts dn mavg up pctB onto the mktdata table
#this adds a col of data to the table
s <- add.indicator(strategy = s, name = "BBands", arguments = list(HLC =
quote(HLC(mktdata)), sd=SD, n=N, maType=quote(SMA)))
#if you wanted to manually apply a signal function for demonstration
#cbind(IBM.mod,sigComparison(label="Close.gt.Open",data=IBM.inds,columns=c("Close","Open"),">"))
#cbind(IBM.mod,sigComparison(label="Adjusted.gt.SMA",data=IBM.inds,columns=c("Adjusted","SMA10"),">"))
####### SIGNALS #######
#do it properly and add it to the strategy:
#s<- add.signal(s,name="sigComparison",arguments =
list(data=quote(mktdata),columns=c("Close","Open"),relationship="gt"),label="Cl.gt.Op")
# what does this do?
# this then add further cols which contain signals
# it adds a col named eg label="Cl.gt.UpperBand" which contains a 1 when
it is triggered
# lets try
############### kill s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("Close","up"),relationship="gt"),label="Cl.gt.UpperBand")
############### lets see if we can find it coming down through the top
band ##############
s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("Close","up"),relationship="lt"),label="Cl.lt.UpperBand")
############### kill s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("Close","dn"),relationship="lt"),label="Cl.lt.LowerBand")
############### lets see if we can find it coming up through the bottom
band ##############
s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("Close","dn"),relationship="gt"),label="Cl.gt.LowerBand")
#s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("Low","up"),
relationship="gt"),label="Lo.gt.UpperBand")
#s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("High","dn"),
relationship="lt"),label="Hi.lt.LowerBand")
#s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("Close","mavg"),relationship="op"),label="Cross.Mid")
s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("High","Low","mavg"),relationship="op"),label="Cross.Mid")
s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("Close","mavg"),relationship="lt"),label="Cross.Mid.Down")
s<- add.signal(s,name="sigCrossover",arguments =
list(data=quote(mktdata),columns=c("Close","mavg"),relationship="gt"),label="Cross.Mid.Up")
#IBM.sigs<-applySignals(s,mktdata=IBM.inds)
# you can review the strategy by uncommenting this s
####### RULES #######
# lets add some rules
# what does this do?
# this then uses a signal to effect a trade in accordance with the rule.
# go short on down through top barrier
##### SHORT
s <- add.rule(s,name='ruleSignal', arguments =
list(data=quote(mktdata),sigcol="Cl.lt.UpperBand",sigval=TRUE,
orderqty=-100, ordertype='market', orderside='short',
threshold=NULL),type='enter')
##### LONG
s <- add.rule(s,name='ruleSignal', arguments =
list(data=quote(mktdata),sigcol="Cl.gt.LowerBand",sigval=TRUE, orderqty=
100, ordertype='market', orderside='long', threshold=NULL),type='enter')
s <- add.rule(s,name='ruleSignal', arguments =
list(data=quote(mktdata),sigcol="Cross.Mid.Down",sigval=TRUE, orderqty=
'all', ordertype='market', orderside='short', threshold=NULL),type='exit')
#s <- add.rule(s,name='ruleSignal', arguments =
list(data=quote(mktdata),sigcol="Cross.Mid.Up",sigval=TRUE, orderqty=
'all', ordertype='market', orderside='long', threshold=NULL),type='exit')
#s <- add.rule(s,name='ruleSignal', arguments =
list(data=quote(mktdata),sigcol="Cross.Mid",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='s' , portfolios='cir'))
# look at the order book
#getOrderBook('cir')
end_t<-Sys.time()
end_t-start_t
updatePortf(Portfolio='cir',Dates=paste('::',as.Date(Sys.time()),sep=''))
chart.Posn(Portfolio='cir',Symbol=stock.str)
plot(add_BBands(on=1,sd=SD,n=N))
#get/save some data
write.table(mktdata, 'C:/Elliot btest/mktdata.csv', col.name=TRUE,
row.names=FALSE, sep=',')
print ('order book')
getOrderBook(portfolio.st)
print('transactions')
getTxns(Portfolio=portfolio.st, Symbol=stock.str)
print('account')
getAccount(portfolio.st)
# end
--
Stephen Choularton Ph.D., FIoD
More information about the R-SIG-Finance
mailing list