I am using the following article:
to create the Average True Range Trailing Stop indicator in R. I have tried various ways to do this, including for loops, pmin and creating a lagging time series, and nothing seems to work.
Could you help me out please?
Why are you trying to create it? It's available in the TTR package in the function ATR
.
UPDATE (after reading the question more closely). I'm not exactly sure this is the solution, but I hope it helps you in the right direction.
library(quantmod)
getSymbols("AMD", from="2005-11-01", to="2006-08-01")
AMD$stopLongATR <- -3.5*ATR(HLC(AMD),5)[,"atr"]
AMD$stopShortATR <- 3.5*ATR(HLC(AMD),5)[,"atr"]
chartSeries(AMD, TA=NULL)
addTA(runMax(Cl(AMD)+AMD$stopLongATR,10), on=1)
addTA(runMin(Cl(AMD)+AMD$stopShortATR,10), on=1)
UPDATE #2:
I missed the trailing stop logic in the article. This code replicates it more closely. Note that the coredata
calls are necessary because trail
is path-dependent and we need to compare yesterday's values with today's. xts/zoo operations merge by index before the operation, so we need to drop the index before comparing.
AMD$trail <- 0
AMD$AMD.lagCl <- lag(Cl(AMD))
for(i in 6:NROW(AMD)) {
trail1 <- coredata(AMD$trail[i-1])
if(Cl(AMD)[i] > trail1 && AMD$AMD.lagCl[i] > trail1) {
AMD$trail[i] <- max(trail1,coredata(Cl(AMD)[i]+AMD$stopLongATR[i]))
} else
if(Cl(AMD)[i] < trail1 && AMD$AMD.lagCl[i] < trail1) {
AMD$trail[i] <- min(trail1,coredata(Cl(AMD)[i]+AMD$stopShortATR[i]))
} else
if(Cl(AMD)[i] > trail1) {
AMD$trail[i] <- coredata(Cl(AMD)[i]+AMD$stopLongATR[i])
} else {
AMD$trail[i] <- coredata(Cl(AMD)[i]+AMD$stopShortATR[i])
}
}
chartSeries(AMD)
addTA(AMD$trail, on=1)