[R-SIG-Finance] quanstrat: stop trailing with variable stops size

Brian Moretta bmresearch at mac.com
Fri Oct 12 16:46:38 CEST 2012


Didn't attach file properly.

Unfortunately I think I closed this topic too soon. I've had problems getting this to work in another example so returned to this one to check. I see now that although it is operating a some sort of stop its not quite as I'd expect. e.g. first 4 trades in example are:
[1] "2007-04-04 00:00:00 GSPC 100 @ 1439.37"
[1] "2007-08-01 00:00:00 GSPC -100 @ 1465.81"
[1] "2007-09-19 00:00:00 GSPC 100 @ 1529.03"
[1] "2007-11-08 00:00:00 GSPC -100 @ 1493.63743174521"
If I go through mktdata from 2007/9/19 and track (highest price - 2*ATR) then the trade should close either 10/18 or 10/22 (depends on how high calculated). Actually 1493 is higher than Hi(GSPC) on 8/11/2007. Am I implementing wrong or is there something else amiss? Full code attached.

Brian

-------------- next part --------------
A non-text attachment was scrubbed...
Name: macd copy.R
Type: application/octet-stream
Size: 4653 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20121012/c8ef16cc/attachment.obj>
-------------- next part --------------


On 12 Oct 2012, at 15:43, Brian Moretta wrote:

> Unfortunately I think I closed this topic too soon. I've had problems getting this to work in another example so returned to this one to check. I see now that although it is operating a some sort of stop its not quite as I'd expect. e.g. first 4 trades in example are:
> [1] "2007-04-04 00:00:00 GSPC 100 @ 1439.37"
> [1] "2007-08-01 00:00:00 GSPC -100 @ 1465.81"
> [1] "2007-09-19 00:00:00 GSPC 100 @ 1529.03"
> [1] "2007-11-08 00:00:00 GSPC -100 @ 1493.63743174521"
> If I go through mktdata from 2007/9/19 and track (highest price - 2*ATR) then the trade should close either 10/18 or 10/22 (depends on how high calculated). Actually 1493 is higher than Hi(GSPC) on 8/11/2007. Am I implementing wrong or is there something else amiss? Full code attached.
> 
> Brian
> 
> <macd copy.R>
> 
> On 27 Sep 2012, at 17:31, Brian Moretta wrote:
> 
>> Jan
>> 
>> That seems to working now. Thanks for your help.
>> 
>> Brian
>> 
>> PS saw on one of the forums you may be interested in an example of Donchian breakouts for the package. Have coded one so if you are still interested let me know & I'll tidy it up & forward it.
>> 
>> On 27 Sep 2012, at 00:16, OpenTrades wrote:
>> 
>>> Hi Brian,
>>> 
>>> We have now implemented support for using an indicator column in the mktdata object as threshold values. So in your source code, I suggest that you use:
>>>> add.indicator(strat.st, name = "stopATR", arguments = list(HLC=quote(HLC(mktdata)), n=14, maType="SMA", noATR=2) )
>>> to add your ATR values, and then refer to these in the rule:
>>>> add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty='all', ordertype='stoptrailing', orderside='long', threshold='stopATR.ind.atr', tmult=FALSE, orderset='exit2'), type='risk',label='trailingexit')
>>> 
>>> Please note that you cannot pass a column of threshold values as a vector. You can also not pass the name of a function: use the indicator method instead (see above).
>>> 
>>> Hope this helps,
>>> 
>>> Jan Humme.
>>> 
>>> 
>>> 
>>> On 25-09-12 16:10, Brian Moretta wrote:
>>>> Thanks for the suggestion. Now I'm getting interesting differences.
>>>> 
>>>> If I redefine my stopATR function (below) and use quote(mktdata$stopATR) as you suggest then I get an error message:
>>>> Error in if (order.side == "long" && as.numeric(Lo(mktdataTimestamp)) <  :
>>>> missing value where TRUE/FALSE needed
>>>> This followed by two identical warnings : In max(i) : no non-missing arguments to max; returning -Inf
>>>> This is the same error as if I used quote(mktdata$stopATR.ind.atr) with my original function.
>>>> stopATR <- function(HLC, n=14, maType, noATR=2){
>>>> 	stop.atr <- -noATR * ATR(HLC=HLC, n=n, maType=maType)$atr
>>>> 	colnames(stop.atr) <- c("stopATR")
>>>> 	stop.atr
>>>> }
>>>> 
>>>> If I'm lazy & use my original stopATR function then using quote(mktdata$atr) in the add.rule runs without any error messages. However the trailing stop doesn't seem to affect anything. Even using an ATR multiple of .1 (not realistic but gives a threshold of 2-3 points on the GSPC data) gives exactly the same transactions as with the add.rule for the stop commented out. Have checked the data and some should be affected but such a tight stop.
>>>> add.indicator(strat.st, name = "stopATR", arguments = list(HLC=quote(HLC(mktdata)), n=14, maType="SMA", noATR=.1) )
>>>> add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty='all', ordertype='stoptrailing', orderside='long', threshold=quote(mktdata$atr), tmult=FALSE, orderset='exit2'), type='risk',label='trailingexit')
>>>> 
>>>> I've also tried the following definition for stopATR with quote(mktdata$atr) as in the second case and I get the same error as in the first example.
>>>> stopATR <- function(HLC, n=14, maType, noATR=2){
>>>> 	stop.atr <- -noATR * ATR(HLC=HLC, n=n, maType=maType)$atr
>>>> }
>>>> 
>>>> Not sure if I'm missing something obvious or if there is something else going on.
>>>> 
>>>> Thanks
>>>> 
>>>> Brian
>>>> 
>>>> On 22 Sep 2012, at 03:00, Brian G. Peterson wrote:
>>>> 
>>>>> why not label your stopATR indicator ouput and set the threshold to that?
>>>>> 
>>>>> quote(mktdata$stopATR)
>>>>> 
>>>>> ?
>>>>> 
>>>>> 
>>>>> On 09/21/2012 02:07 PM, Brian Moretta wrote:
>>>>>> Hi
>>>>>> 
>>>>>> I've been trying to modify the MACD example with trailing stop so that it uses a 2ATR stop rather than a fixed value or proportion. Key seems to be the threshold value. Help says
>>>>>> 
>>>>>> If threshold is not numeric or NULL it should be the character string describing a function that can calculate a threshold. Ideally this will be a column lookup on a non-path-dependent indicator calculated in advance.
>>>>>> 
>>>>>> I keep getting errors with the threshold set to something that uses a vector whether text or not. The add.rule line is (full code at end)
>>>>>> add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty='all', ordertype='stoptrailing', orderside='long', threshold=stopvalue, tmult=FALSE, orderset='exit2'), type='risk',label='trailing exit')
>>>>>> 
>>>>>> With stopvalue set to -20 it works fine. Tried stop.atr$atr, as a vector, inside quotes (help says character string) and inside quote() but to no avail. Tried similar for indicator mktdata$stopATR.ind.atr. Going through previous questions in this area I'm not sure if I'm just doing it wrong or pushing the limits of quanstrat's development, but any suggestions are welcome.
>>>>>> 
>>>>>> Thanks
>>>>>> 
>>>>>> Brian
>>>>>> 
>>>>>> require(quantstrat)
>>>>>> suppressWarnings(rm("order_book.macd",pos=.strategy))
>>>>>> suppressWarnings(rm("account.macd","portfolio.macd",pos=.blotter))
>>>>>> suppressWarnings(rm("account.st","portfolio.st","stock.str","stratMACD","initDate","initEq",'start_t','end_t'))
>>>>>> 
>>>>>> #stock.str='AAPL' # what are we trying it on
>>>>>> stock.str='GSPC'
>>>>>> getSymbols("^GSPC", src='yahoo', index.class=c("POSIXt","POSIXct"), from='2007-01-01')
>>>>>> 
>>>>>> stopATR <- function(HLC, n=14, maType, noATR=2){
>>>>>> 	stop.atr <- -noATR * ATR(HLC=HLC, n=n, maType=maType)
>>>>>> }
>>>>>> stop.atr <- -2 * ATR(HLC(get(stock.str)), n=14, maType='SMA')
>>>>>> stopvalue <- -20
>>>>>> 
>>>>>> #MA parameters for MACD
>>>>>> fastMA = 12
>>>>>> slowMA = 26
>>>>>> signalMA = 9
>>>>>> maType="EMA"
>>>>>> 
>>>>>> currency('USD')
>>>>>> stock(stock.str,currency='USD',multiplier=1)
>>>>>> 
>>>>>> initDate='2006-12-31'
>>>>>> initEq=1000000
>>>>>> portfolio.st='macd'
>>>>>> account.st='macd'
>>>>>> 
>>>>>> initPortf(portfolio.st,symbols=stock.str, initDate=initDate)
>>>>>> initAcct(account.st,portfolios=portfolio.st, initDate=initDate)
>>>>>> initOrders(portfolio=portfolio.st,initDate=initDate)
>>>>>> 
>>>>>> strat.st<-portfolio.st
>>>>>> # define the strategy
>>>>>> strategy(strat.st, store=TRUE)
>>>>>> 
>>>>>> #one indicator
>>>>>> add.indicator(strat.st, name = "MACD", arguments = list(x=quote(Cl(mktdata))) )
>>>>>> add.indicator(strat.st, name = "stopATR", arguments = list(HLC=quote(HLC(mktdata)), n=14, maType="SMA", noATR=2) )
>>>>>> 
>>>>>> #two signals
>>>>>> add.signal(strat.st,name="sigThreshold",arguments = list(column="signal",relationship="gt",threshold=0,cross=TRUE),label="signal.gt.zero")
>>>>>> add.signal(strat.st,name="sigThreshold",arguments = list(column="signal",relationship="lt",threshold=0,cross=TRUE),label="signal.lt.zero")
>>>>>> 
>>>>>> ####
>>>>>> # add rules
>>>>>> 
>>>>>> # entry
>>>>>> add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty=100, ordertype='market', orderside='long', threshold=NULL),type='enter',label='enter',storefun=FALSE)
>>>>>> 
>>>>>> #alternatives for risk stops:
>>>>>> # alternately, use a trailing order, with 2ATR stop
>>>>>> add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.gt.zero",sigval=TRUE, orderqty='all', ordertype='stoptrailing', orderside='long', threshold=stop.atr$atr, tmult=FALSE, orderset='exit2'), type='risk',label='trailingexit')
>>>>>> 
>>>>>> # exit
>>>>>> add.rule(strat.st,name='ruleSignal', arguments = list(sigcol="signal.lt.zero",sigval=TRUE, orderqty='all', ordertype='market', orderside='long', threshold=NULL,orderset='exit2'),type='exit',label='exit')
>>>>>> 
>>>>>> #end rules
>>>>>> ####
>>>>>> 
>>>>>> start_t<-Sys.time()
>>>>>> out<-try(applyStrategy(strat.st , portfolios=portfolio.st,parameters=list(nFast=fastMA, nSlow=slowMA, nSig=signalMA,maType=maType)))
>>>>>> end_t<-Sys.time()
>>>>>> print(end_t-start_t)
>>>>>> 
>>>>>> start_t<-Sys.time()
>>>>>> updatePortf(Portfolio=portfolio.st,Dates=paste('::',as.Date(Sys.time()),sep=''))
>>>>>> end_t<-Sys.time()
>>>>>> print("trade blotter portfolio update:")
>>>>>> print(end_t-start_t)
>>>>>> 
>>>>>> chart.Posn(Portfolio=portfolio.st,Symbol=stock.str)
>>>>>> plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA"))
>>>>>> 
>>>>>> 	[[alternative HTML version deleted]]
>>>>>> 
>>>>>> _______________________________________________
>>>>>> 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.
>>>>>> 
>>>>> 
>>>>> -- 
>>>>> Brian G. Peterson
>>>>> http://braverock.com/brian/
>>>>> Ph: 773-459-4973
>>>>> IM: bgpbraverock
>>>>> 
>>>>> _______________________________________________
>>>>> 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.
>>>> 
>>>> 	[[alternative HTML version deleted]]
>>>> 
>>>> _______________________________________________
>>>> 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.
>>>> 
>>> 
>>> 
>>> -- 
>>> Jan Humme - OpenTrades
>>> 
>>> WWW:     http://www.opentrades.nl
>>> Email:   jan at opentrades.nl
>>> Twitter: @opentrades
>>> 
>>> _______________________________________________
>>> 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.
>> 
>> _______________________________________________
>> 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.
> 
> 
> 
> 	[[alternative HTML version deleted]]
> 
> _______________________________________________
> 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