3

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?

FXQuantTrader
  • 6,821
  • 3
  • 36
  • 67
nesvarbu
  • 986
  • 2
  • 9
  • 24

2 Answers2

5

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

Pierre Lapointe
  • 16,017
  • 2
  • 43
  • 56
2

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

FXQuantTrader
  • 6,821
  • 3
  • 36
  • 67