Search code examples
rtradingquantmod

ATR() (from TTR package): subscript out of bounds, check doesn't fix


I have a data frame (raw.Delta):

                Time Open High Low Close
1 12/18/2022 6:02:29 PM    1    1   1     1
2 12/18/2022 6:04:53 PM    1   43 -17     7
3 12/18/2022 6:06:46 PM    7  130  -6    92
4 12/18/2022 6:09:01 PM   92  145  68   124
5 12/18/2022 6:11:30 PM  124  205 118   135
6 12/18/2022 6:14:41 PM  135  179 117   130

...that I am trying to call ATR on like so...

delta <- raw.Delta %>%
  mutate(dATR=ATR(c("High", "Low", 
  "Close"), n=50, maType="SMA"))

and every time I get....

Error in `mutate()`:
! Problem while computing `dATR = 
``ATR(c("High", "Low", "Close"), n = 50, maType = "SMA")`.
Caused by error in `HLC[-NROW(HLC), 3]`:
! subscript out of bounds``

...even if I try to do:

mutate(dATR=ifelse(nBar>50,ATR(c("High", 
"Low", "Close"), n=50, 
maType="SMA"),0))

it will throw the same error. I have also tried not specifying 'maType', I have tried simply using 'Close' instead of c("H","L","C"). I feel like I have tried every combination to get it to work. FYI this...

SMA(raw.Delta, n=50)

...works perfectly fine even though it also has a lookback period AND I don't even need to do a check on bar number to ensure there are enough bars in the series, it simply creates a new column in my df (when called by mutate) where the first 50 values are NA, which I believe is the expected behavior of ATR as well.

Anyway, I hope I have provided enough information for someone to be able to spot the issue. Thanks.


Solution

  • %>% passes the LHS as the first argument to ATR(). So your code is the same as ATR(raw.Delta, n = 50, maType = "SMA", c("High", "Low", "Close")), which isn't what you want.

    This should work:

    raw.Delta %>%
        mutate(dATR = ATR(.[, c("High", "Low", "Close")], n = 50, maType = "SMA"))
    
    # or use quantmod::HLC() to grab the high, low, close columns
    raw.Delta %>% mutate(dATR = ATR(HLC(.), n = 50, maType = "SMA"))