Using the input in the Note at the end, split the data into individual securities, convert to zoo and then xts, and apply ATR giving a list of xts objects, L. Then optionally convert to a long data frame using bind_rows
.
# form list of xts objects each w ATR columns added
L <- ttrc_total %>%
{ split(.[, -ncol(.)], .$category) } %>%
lapply(function(x) as.xts(read.zoo(x))) %>%
lapply(function(x) transform(x, ATR = ATR(x[, c("High","Low","Close")], n=10 ))
long <- bind_rows(lapply(L, fortify.zoo, name = "Date" ), .id = "category")
head(long)
## category Date Open High Low Close Volume tr atr trueHigh trueLow
## 1 A 1985-01-02 3.18 3.18 3.08 3.08 1870906 NA NA NA NA
## 2 A 1985-01-03 3.09 3.15 3.09 3.11 3099506 0.07 NA 3.15 3.08
## 3 A 1985-01-04 3.11 3.12 3.08 3.09 2274157 0.04 NA 3.12 3.08
## 4 A 1985-01-07 3.09 3.12 3.07 3.10 2086758 0.05 NA 3.12 3.07
## 5 A 1985-01-08 3.10 3.12 3.08 3.11 2166348 0.04 NA 3.12 3.08
## 6 A 1985-01-09 3.12 3.17 3.10 3.16 3441798 0.07 NA 3.17 3.10
Note
library(dplyr, exclude = c("filter", "lag"))
library(TTR)
library(xts)
# form input
data(ttrc)
ttrc_total <- rbind(ttrc %>% mutate(category = 'A'),
ttrc %>% mutate(category= 'B'),
ttrc %>% mutate(category= 'C'))