Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
nesvarbu Avatar asked Oct 31 '25 21:10

nesvarbu


2 Answers

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

like image 153
Pierre Lapointe Avatar answered Nov 02 '25 11:11

Pierre Lapointe


xts has readily available tools for this. If you pass in an xts containing data of logical type, you can include vertical line markers very quickly in a one liner (after calling chart_Series):

x_vline <- xts(TRUE, as.Date("2007-01-09"))
add_TA(x_vline, on = -1, col = "lightblue", border='red')
# Or, if you understand what's going on, replace the above with it all packaged together:
# add_TA(xts(TRUE, as.Date("2007-01-09")), on = -1, col = "lightblue", border='red')

enter image description here

Use on = 1 to plot in front of the candle, on =-1 to plot behind the candle. Other params should be self explanatory.

Note that you add multiple vertical markers too, spanning multiple bars if you like (to shade regions neatly). e.g. : Using x_vline <- xts(rep(TRUE, 3), as.Date(c("2007-01-09", "2007-01-24", "2007-01-25"))) gives: enter image description here

like image 40
FXQuantTrader Avatar answered Nov 02 '25 10:11

FXQuantTrader