Vad är stop loss quantstrat
[R-SIG-Finance] Stop Loss orders in quantstrat
Sanjay Mansabdarsanjay.mansabdar at yahoo.com
Tue Feb 20 10:55:22 CET 2018
Greetings, Here fryst vatten my implementation of the stop loss code based on suggestions from Brian and others that inom have received. To recap, the current implementation of the stop loss fryst vatten to compare the price midbar to the stop limit price calculated as entry price - threshold. This causes intra day whipsaws to exit positions. inom would like to model the stop loss mechanism that inom follow in my trading, which fryst vatten to compare the closing price on any day to entry price - threshold and if true then exit using a marknad beställning at open the following day. This fryst vatten a long only struktur where MACD meddelande crossing zero generates the long position taken at the Close of the next day. This fryst vatten done via the usual quantstrat functions, drawing from the macd demo code. inom also calculate the buy meddelande with cross = FALSE and team this meddelande bygd 1 day to indikera if there fryst vatten a position ( as the Stop Loss beställning needs to be position aware). This fryst vatten called 'longpos' Once the position fryst vatten taken , inom calculate an indicator SLPX that fryst vatten essentially the stop loss price. If the close on any day fryst vatten below this stop loss price then a marknad beställning fryst vatten triggered to sell out. The SLPX indicator needs to work bygd taking the buy meddelande, lagging this bygd a day as the opening trade fryst vatten taken the next day and using this calculate the stop loss price which fryst vatten entry price*(1-stop loss percent). This fryst vatten the indicator "SLPX" This updates whenever a new position fryst vatten taken else equals the previous value carried forward. inom create another meddelande that triggers when the closing price fryst vatten below the stop loss as returned bygd the SLPX indicator. This fryst vatten the meddelande "SLCondition" A sista meddelande "SLTrigger" [using sigFormula triggers if "longpos" and "SLCondition" are true simultaneously, with cross = TRUE so that this fryst vatten evaluated only the first time this happens. A Stop Loss beställning fryst vatten fired as a marknad beställning if "SLTrigger" fryst vatten set to 1. This will happen one day after. There fryst vatten also an exit condition if the MACD meddelande moves below zero (with its own signal) and the exit beställning fryst vatten set as an oco with the stop loss beställning. The code fryst vatten attached with this mail and also presented at the end of this mail. inom suspect there are much easier ways of doing this, however as an R novice, inom am not ganska sure of how else to man the indicators and signals position aware which they need to be to trigger the stop losses in this way the next day, and based on the close of the previous day, rather than on the same day and based on the low of the day. inom will appreciate any help with how to do this, if there fryst vatten an easier way. When inom run this the error inom get fryst vatten as follows. ------ applyStrategy(strategy=strat.name , portfolios=portfoli .... [TRUNCATED] Error in attr(x, "tsp") <- c(1, NROW(x), 1) : attempt to set an attribute on NULLIn addition: varning messages:1: In rm("account.st", "portfolio.st", "stock.str", "stratMACD", "initDate", : object 'stratMACD' not found2: In rm("account.st", "portfolio.st", "stock.str", "stratMACD", "initDate", : object 'start_t' not found3: In rm("account.st", "portfolio.st", "stock.str", "stratMACD", "initDate", : object 'end_t' not funnen ------ A few questions if anyone can help. 1. What am inom doing wrong? 2. fryst vatten it even possible to man the signals position aware as inom have done given that Ive seen in the documentation that they are not supposed to be path dependent (as inom imagine position awareness demands)3. If yes, fryst vatten there a way of referencing positions and prices within signals? Thanks in advance for any pointers. Quantstrat fryst vatten an excellent bit of work from my perspective and inom hope to learn enough about it to use it in my trading and to contribute to it. Sanjay ######################## Full Code: ####################################################################################### This script tries to implement a stop loss on a closing price basis.# Rules:# BTO: when MACD crosses threshold of zero from below# STC: when MACD crosses threshold of zero from above# Stop Loss: If on any day the closing price fryst vatten less than the BTO*(1-X), exit at market # on open the next day where X fryst vatten the loss tolerable###################################################################################### # libraries########################################################################### require(quantstrat) # remove old parameters ############################################################## try(rm("order_book.macd",pos=.strategy),silent=TRUE) try(rm("account.macd","portfolio.macd",pos=.blotter),silent=TRUE) try(rm("account.st","portfolio.st","stock.str","stratMACD","initDate","initEq",'start_t','end_t'),silent=TRUE) # settingup quantstrat ############################################################## stock.str='AAPL' currency('USD') stock(stock.str,currency='USD',multiplier=1) initDate<-'2009-12-31' initEq=1000000 portfolio.st<-'macd' account.st<-'macd' strat.name <- 'stratMACD' initPortf(portfolio.st,symbols=stock.str, initDate=initDate) initAcct(account.st,portfolios=portfolio.st, initDate=initDate) initOrders(portfolio=portfolio.st,initDate=initDate) strategy(strat.name,store = TRUE) # struktur parameters ################################################################## fastMA <- 12 slowMA <- 26 signalMA <- 9 maType <-"EMA" slpercent <-0.05 # Get information ########################################################################### getSymbols(stock.str,from=initDate) # anpassad Indicator Function ######################################################### # This fryst vatten a function to create an indicator that fryst vatten path dependent.# This function looks at the MACD meddelande that triggers an entry trade and then creates the appropriate stop loss# level for that entry. This will be used to create a signal SLPX<-function(OHLC,slpercent){ slpx<-rep(NA, times = nrow(OHLC)) # create the output vector and fill with NA OHLC$longlag<-lag(OHLC$signal.gt.zero.x,n=1) #lag the BTO meddelande bygd 1 dryckesställe as position taken the next day for (counter in (1:nrow(OHLC))){ slpx[counter] if (!is.na(OHLC[counter]$longlag)) { # do ingenting if the meddelande fryst vatten an NA value if(OHLC[counter]$longlag==1) { slpx[counter] = Op(OHLC[counter])*(1-slpercent) # if meddelande fryst vatten 1, then figure out operating stop loss } else { slpx[counter] = slpx[counter-1] # fryst vatten meddelande fryst vatten zero then carry forward previously calculated value } } } return(slpx)} # Add Indicator MACD ############################################################### add.indicator(strategy = strat.name, name = "MACD", arguments = list(x = quote(Cl(mktdata)), nFast=fastMA, nSlow = maSlow, nSig = signalMA, maType=maType) ) # Add BTO meddelande ###################################################################### add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "gt", threshold = 0, cross = TRUE ), label = "signal.gt.zero.x" ) # Add STC meddelande ###################################################################### add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "lt", threshold = 0, cross = TRUE ), label = "signal.lt.zero.x" ) # Add meddelande that indicates whether there fryst vatten a position due to BTO meddelande add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "gt", threshold = 0, cross = FALSE ), label = "signal.gt.zero.pos" ) # team the above meddelande bygd 1 dryckesställe as long position gets taken the next dryckesställe ############ add.indicator (strategy = strat.name, name = "lag", arguments = (list(x=quote(mktdata$signal.gt.zero.pos), n=1)), label = "longpos" ) # Add SLPX Indicator ################################################################ add.indicator( strategy = strat.name, name = "SLPX", arguments = (list(OHLC=quote(mktdata), slpercent = 0.05)), label = "SLPX") # Add meddelande to betalningsmedel whether Close on any day fryst vatten less that the stop loss level from# the indicator SLPX ############################################################### add.signal(strategy = strat.name, name = "sigComparison", arguments = list(columns=c(quote(Cl(mktdata)),"SLPX")), label = "SLCondition") # betalningsmedel whether longpos and SL condition are met simultaneously ##################### add.signal( strategy = strat.name, name = "sigFormula", arguments = list(formula = "longpos & SLCondition", cross = TRUE), label = "SLTrigger" ) # Add BTO Rule ####################################################################### add.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "signal.gt.zero.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "signal.lt.zero.x", sigval = TRUE, orderqty = 'all', prefer = "Open", replace = FALSE, ordertype = 'market', orderside = 'long', threshold = NULL, orderset = 'ocolong' ), type= "exit", label = "exitlong") # Add Stop Loss Rule [part of orderset 'ocolong'] ############################## add.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "SLTrigger", sigval = TRUE, orderqty = 'all', prefer = "Open", replace = FALSE, ordertype = 'market', orderside = 'long', threshold = NULL, orderset = 'ocolong' ), type= "exit", label = "SL") #Apply Strategy ####################################################################### applyStrategy(strategy=strat.name , portfolios=portfolio.st) # Updates ############################################################################# updatePortf(Portfolio=portfolio.st,Dates=paste('::',as.Date(Sys.time()),sep='')) # Outputs ############################################################################ chart.Posn(Portfolio=portfolio.st,Symbol=stock.str) plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA")) print ('order book') getOrderBook(portfolio.st) print('transactions') getTxns(Portfolio=portfolio.st, Symbol=stock.str) On Tuesday, February 13, 2018, 6:28:13 PM GMT+5:30, Sanjay Mansabdar <s inom have been ansträngande to implement what Brian has suggested for a simple long only macd based strategy. Given that inom am new to quantstrat, this may be ganska an elementary question, but here goes. 1. inom have a simple long only MACD based struktur that gives me entry and exit signals on T.2. On the grund os a long meddelande inom trigger a marknad beställning to buy on T+1, at the open.3. Based on this execution, inom need to set a hard stop on the position entered in #2, that fryst vatten x% below the execution price of 2, with the comparison being done at the close of each day, and if the meddelande triggers on some day D, the beställning fryst vatten executed as a marknad sell beställning on the next day D+1.My meddelande essentially says "Check to see if the closing price on any day fryst vatten less than the execution prices of the gods opening trade minus a threshold and if it fryst vatten, trigger a signal".4. This clearly needs, at any point, the value of the execution price of the marknad beställning in #2, the timestamp of #2 5.Finally the rule that triggers the marknad sell beställning described in #3 would need to know the existing position storlek as well. inom am not ganska sure how to extrakt these state variables to include in the meddelande and in the rule. Any help on this would be appreciated. Thanks in advance. On Tuesday, February 13, 2018, 12:42:07 PM GMT+5:30, Sanjay Mansabdar < inom am not sure how to reply to digest messages in the thread, so apologies in advance for errors @Brian, inom think there fryst vatten no error with the implementation as it stands of stop limit orders. However IMHO stop loss logic fryst vatten not necessarily the same thing as stop limit orders and perhaps needs to be thought of separately. inom will try and follow the rutt you have suggested. Thanks Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20180220/b891c547/attachment.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: macd_SL6.R Type: application/octet-stream Size: 7792 bytes Desc: not available URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20180220/b891c547/attachment.obj>
More resultat about the R-SIG-Finance mailing list
Tue Feb 20 10:55:22 CET 2018
Greetings, Here fryst vatten my implementation of the stop loss code based on suggestions from Brian and others that inom have received. To recap, the current implementation of the stop loss fryst vatten to compare the price midbar to the stop limit price calculated as entry price - threshold. This causes intra day whipsaws to exit positions. inom would like to model the stop loss mechanism that inom follow in my trading, which fryst vatten to compare the closing price on any day to entry price - threshold and if true then exit using a marknad beställning at open the following day. This fryst vatten a long only struktur where MACD meddelande crossing zero generates the long position taken at the Close of the next day. This fryst vatten done via the usual quantstrat functions, drawing from the macd demo code. inom also calculate the buy meddelande with cross = FALSE and team this meddelande bygd 1 day to indikera if there fryst vatten a position ( as the Stop Loss beställning needs to be position aware). This fryst vatten called 'longpos' Once the position fryst vatten taken , inom calculate an indicator SLPX that fryst vatten essentially the stop loss price. If the close on any day fryst vatten below this stop loss price then a marknad beställning fryst vatten triggered to sell out. The SLPX indicator needs to work bygd taking the buy meddelande, lagging this bygd a day as the opening trade fryst vatten taken the next day and using this calculate the stop loss price which fryst vatten entry price*(1-stop loss percent). This fryst vatten the indicator "SLPX" This updates whenever a new position fryst vatten taken else equals the previous value carried forward. inom create another meddelande that triggers when the closing price fryst vatten below the stop loss as returned bygd the SLPX indicator. This fryst vatten the meddelande "SLCondition" A sista meddelande "SLTrigger" [using sigFormula triggers if "longpos" and "SLCondition" are true simultaneously, with cross = TRUE so that this fryst vatten evaluated only the first time this happens. A Stop Loss beställning fryst vatten fired as a marknad beställning if "SLTrigger" fryst vatten set to 1. This will happen one day after. There fryst vatten also an exit condition if the MACD meddelande moves below zero (with its own signal) and the exit beställning fryst vatten set as an oco with the stop loss beställning. The code fryst vatten attached with this mail and also presented at the end of this mail. inom suspect there are much easier ways of doing this, however as an R novice, inom am not ganska sure of how else to man the indicators and signals position aware which they need to be to trigger the stop losses in this way the next day, and based on the close of the previous day, rather than on the same day and based on the low of the day. inom will appreciate any help with how to do this, if there fryst vatten an easier way. When inom run this the error inom get fryst vatten as follows. ------ applyStrategy(strategy=strat.name , portfolios=portfoli .... [TRUNCATED] Error in attr(x, "tsp") <- c(1, NROW(x), 1) : attempt to set an attribute on NULLIn addition: varning messages:1: In rm("account.st", "portfolio.st", "stock.str", "stratMACD", "initDate", : object 'stratMACD' not found2: In rm("account.st", "portfolio.st", "stock.str", "stratMACD", "initDate", : object 'start_t' not found3: In rm("account.st", "portfolio.st", "stock.str", "stratMACD", "initDate", : object 'end_t' not funnen ------ A few questions if anyone can help. 1. What am inom doing wrong? 2. fryst vatten it even possible to man the signals position aware as inom have done given that Ive seen in the documentation that they are not supposed to be path dependent (as inom imagine position awareness demands)3. If yes, fryst vatten there a way of referencing positions and prices within signals? Thanks in advance for any pointers. Quantstrat fryst vatten an excellent bit of work from my perspective and inom hope to learn enough about it to use it in my trading and to contribute to it. Sanjay ######################## Full Code: ####################################################################################### This script tries to implement a stop loss on a closing price basis.# Rules:# BTO: when MACD crosses threshold of zero from below# STC: when MACD crosses threshold of zero from above# Stop Loss: If on any day the closing price fryst vatten less than the BTO*(1-X), exit at market # on open the next day where X fryst vatten the loss tolerable###################################################################################### # libraries########################################################################### require(quantstrat) # remove old parameters ############################################################## try(rm("order_book.macd",pos=.strategy),silent=TRUE) try(rm("account.macd","portfolio.macd",pos=.blotter),silent=TRUE) try(rm("account.st","portfolio.st","stock.str","stratMACD","initDate","initEq",'start_t','end_t'),silent=TRUE) # settingup quantstrat ############################################################## stock.str='AAPL' currency('USD') stock(stock.str,currency='USD',multiplier=1) initDate<-'2009-12-31' initEq=1000000 portfolio.st<-'macd' account.st<-'macd' strat.name <- 'stratMACD' initPortf(portfolio.st,symbols=stock.str, initDate=initDate) initAcct(account.st,portfolios=portfolio.st, initDate=initDate) initOrders(portfolio=portfolio.st,initDate=initDate) strategy(strat.name,store = TRUE) # struktur parameters ################################################################## fastMA <- 12 slowMA <- 26 signalMA <- 9 maType <-"EMA" slpercent <-0.05 # Get information ########################################################################### getSymbols(stock.str,from=initDate) # anpassad Indicator Function ######################################################### # This fryst vatten a function to create an indicator that fryst vatten path dependent.# This function looks at the MACD meddelande that triggers an entry trade and then creates the appropriate stop loss# level for that entry. This will be used to create a signal SLPX<-function(OHLC,slpercent){ slpx<-rep(NA, times = nrow(OHLC)) # create the output vector and fill with NA OHLC$longlag<-lag(OHLC$signal.gt.zero.x,n=1) #lag the BTO meddelande bygd 1 dryckesställe as position taken the next day for (counter in (1:nrow(OHLC))){ slpx[counter] if (!is.na(OHLC[counter]$longlag)) { # do ingenting if the meddelande fryst vatten an NA value if(OHLC[counter]$longlag==1) { slpx[counter] = Op(OHLC[counter])*(1-slpercent) # if meddelande fryst vatten 1, then figure out operating stop loss } else { slpx[counter] = slpx[counter-1] # fryst vatten meddelande fryst vatten zero then carry forward previously calculated value } } } return(slpx)} # Add Indicator MACD ############################################################### add.indicator(strategy = strat.name, name = "MACD", arguments = list(x = quote(Cl(mktdata)), nFast=fastMA, nSlow = maSlow, nSig = signalMA, maType=maType) ) # Add BTO meddelande ###################################################################### add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "gt", threshold = 0, cross = TRUE ), label = "signal.gt.zero.x" ) # Add STC meddelande ###################################################################### add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "lt", threshold = 0, cross = TRUE ), label = "signal.lt.zero.x" ) # Add meddelande that indicates whether there fryst vatten a position due to BTO meddelande add.signal(strategy = strat.name, name = "sigThreshold", arguments = list(column = "signal.MACD.ind", relationship = "gt", threshold = 0, cross = FALSE ), label = "signal.gt.zero.pos" ) # team the above meddelande bygd 1 dryckesställe as long position gets taken the next dryckesställe ############ add.indicator (strategy = strat.name, name = "lag", arguments = (list(x=quote(mktdata$signal.gt.zero.pos), n=1)), label = "longpos" ) # Add SLPX Indicator ################################################################ add.indicator( strategy = strat.name, name = "SLPX", arguments = (list(OHLC=quote(mktdata), slpercent = 0.05)), label = "SLPX") # Add meddelande to betalningsmedel whether Close on any day fryst vatten less that the stop loss level from# the indicator SLPX ############################################################### add.signal(strategy = strat.name, name = "sigComparison", arguments = list(columns=c(quote(Cl(mktdata)),"SLPX")), label = "SLCondition") # betalningsmedel whether longpos and SL condition are met simultaneously ##################### add.signal( strategy = strat.name, name = "sigFormula", arguments = list(formula = "longpos & SLCondition", cross = TRUE), label = "SLTrigger" ) # Add BTO Rule ####################################################################### add.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "signal.gt.zero.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "signal.lt.zero.x", sigval = TRUE, orderqty = 'all', prefer = "Open", replace = FALSE, ordertype = 'market', orderside = 'long', threshold = NULL, orderset = 'ocolong' ), type= "exit", label = "exitlong") # Add Stop Loss Rule [part of orderset 'ocolong'] ############################## add.rule(strategy = strat.name, name = "ruleSignal", arguments = list( sigcol = "SLTrigger", sigval = TRUE, orderqty = 'all', prefer = "Open", replace = FALSE, ordertype = 'market', orderside = 'long', threshold = NULL, orderset = 'ocolong' ), type= "exit", label = "SL") #Apply Strategy ####################################################################### applyStrategy(strategy=strat.name , portfolios=portfolio.st) # Updates ############################################################################# updatePortf(Portfolio=portfolio.st,Dates=paste('::',as.Date(Sys.time()),sep='')) # Outputs ############################################################################ chart.Posn(Portfolio=portfolio.st,Symbol=stock.str) plot(add_MACD(fast=fastMA, slow=slowMA, signal=signalMA,maType="EMA")) print ('order book') getOrderBook(portfolio.st) print('transactions') getTxns(Portfolio=portfolio.st, Symbol=stock.str) On Tuesday, February 13, 2018, 6:28:13 PM GMT+5:30, Sanjay Mansabdar <s inom have been ansträngande to implement what Brian has suggested for a simple long only macd based strategy. Given that inom am new to quantstrat, this may be ganska an elementary question, but here goes. 1. inom have a simple long only MACD based struktur that gives me entry and exit signals on T.2. On the grund os a long meddelande inom trigger a marknad beställning to buy on T+1, at the open.3. Based on this execution, inom need to set a hard stop on the position entered in #2, that fryst vatten x% below the execution price of 2, with the comparison being done at the close of each day, and if the meddelande triggers on some day D, the beställning fryst vatten executed as a marknad sell beställning on the next day D+1.My meddelande essentially says "Check to see if the closing price on any day fryst vatten less than the execution prices of the gods opening trade minus a threshold and if it fryst vatten, trigger a signal".4. This clearly needs, at any point, the value of the execution price of the marknad beställning in #2, the timestamp of #2 5.Finally the rule that triggers the marknad sell beställning described in #3 would need to know the existing position storlek as well. inom am not ganska sure how to extrakt these state variables to include in the meddelande and in the rule. Any help on this would be appreciated. Thanks in advance. On Tuesday, February 13, 2018, 12:42:07 PM GMT+5:30, Sanjay Mansabdar < inom am not sure how to reply to digest messages in the thread, so apologies in advance for errors @Brian, inom think there fryst vatten no error with the implementation as it stands of stop limit orders. However IMHO stop loss logic fryst vatten not necessarily the same thing as stop limit orders and perhaps needs to be thought of separately. inom will try and follow the rutt you have suggested. Thanks Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20180220/b891c547/attachment.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: macd_SL6.R Type: application/octet-stream Size: 7792 bytes Desc: not available URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20180220/b891c547/attachment.obj>
More resultat about the R-SIG-Finance mailing list