rquantmod

Add a dot to charSeries in Quantmod R


I'm trying to mark a point on a chartSeries but below code doesn't show the point. I guess I'm not using 'points' function correctly. could anyone show me the right way to put a point on this chart please?

symb <- getSymbols("AAPL",from = "2024-02-01",src = 'yahoo',auto.assign = FALSE)
chartSeries(symb, 
            theme = chartTheme("white",dn.col = "red"),
            TA = list("addEMA(5)","addEMA(20)")
            )
points(as.Date("2024-05-20"),180, pch = 17)

enter image description here something like this


Solution

  • The x-axis is not a date, but a numeric vector ranging from 1 to 86:

    plt <- chartSeries(symb, 
                theme = chartTheme("white",dn.col = "red"),
                TA = list("addEMA(5)","addEMA(20)")
    )
    
    plt@xrange
    [1]  1 86
    

    The date range for the x-axis, from your data, is 124 days (Feb 1 - Jun 4), while May 20 is 109 days from the start. Also, the slot spacing for the x-axis is 3:

    plt@spacing
    [1] 3
    

    So, to add a point at May 20, 2024 you can do this:

    d.range <- as.numeric(diff(range(time(symb))))
    d.diff <- as.numeric(as.Date("2024-05-20") - start(symb))
    
    plt
    points(plt@xrange[2] * d.diff / d.range * plt@spacing, 180, pch=17)
    

    enter image description here