Search code examples
rquantmod

How to draw a calculated line on quantmod chart


I would like to draw my own calculated indicator to the quantmod chart. For example: the average high of the last 6 days. Is there a way to draw such a series on the chart? I tried the following but without success.

SPY<-getSymbols("SPY", src = 'yahoo', from = '2007-01-01', auto.assign = FALSE)
SPY$Last6DaysHigh<-(Lag(SPY$SPY.Close,k=6)+Lag(SPY$SPY.Close,k=5)+
                    Lag(SPY$SPY.Close,k=4)+Lag(SPY$SPY.Close,k=3)+
                    Lag(SPY$SPY.Close,k=2)+Lag(SPY$SPY.Close,k=1))/6

Last6DaysHigh <- xts(!as.logical(SPY[,7]),index(SPY))
chart_Series(SPY,TA="add_TA(Last6DaysHigh,on=-1)")

Solution

  • This works for me:

    library(quantmod)
    SPY <- getSymbols("SPY", auto.assign = FALSE)
    SPY$Last6DaysHigh <- rowMeans(Lag(Cl(SPY),k=1:6))
    chart_Series(SPY,TA="add_TA(SPY$Last6DaysHigh,on=-1)")
    

    I suspect the issue is related to the fact that your code attempts to plot a single point because it plots a logical vector where all but one observation is false.