Search code examples
rchartsxtsquantmod

How to highlight individual candles in a quantmod chart?


I could not find anything about how could I highlight individual candles in quantmod charts. Here is an example code:

library(quantmod)
getSymbols("AAPL", src="yahoo")
chart_Series(AAPL, subset="2007-01")
AAPL$show <- ifelse(as.Date(index(AAPL)) == as.Date("2007-01-09"), 1, 0)
add_TA(AAPL$show, col="red")

What I would like to do is somehow to highlight that bar on 2007-01-09. It could be different candle color, rectangle around it or maybe different background color. Any ideas how to do it?


Solution

  • One way to do this would be to change the theme colors to match the points you want to highlight. In the following code, I'm changing the up and down colors from a single name to a vector of colors that matches the length of your data. To do this, I'm using your AAPL$show vector. The reason I added "1" to the AAPL$show+1 vector is that I want to transform the 0,1 vector into 1,2. This is then used to choose between c("red","cyan").

    library(quantmod)                                                              
    getSymbols("AAPL", src="yahoo")                                                
    AAPL$show <- ifelse(as.Date(index(AAPL)) == as.Date("2007-01-09"), 1, 0)       
    
    myTheme <- chart_theme()                                                       
    myTheme$col$dn.col <- c("red","cyan")[AAPL$show+1]                             
    myTheme$col$up.col <- c("white","cyan")[AAPL$show+1]                           
    chart_Series(AAPL, subset="2007-01",theme=myTheme)                             
    
    add_TA(AAPL$show, col="red")      
    

    enter image description here