Thank you FXQuantTrader for introducing a beautiful and fast alternative approach to the candlestick bars in R! Awesome, concise, easy to read!
Here comes a bit improved version of FXQuantTrader's solution, which include:
- wraps it into a function
- supports lower resolution (down to 1 sec bars)
- changes candle's whiskers colour from black to proper one
- adds small horizontal line for bars with Close == Open
- adds 3rd colour (blue) to bars with Close == Open
- adds 'alpha' argument which allows you to make the whole candlesticks chart more transparent, so when you draw on top some Bollinger Bands and/or Moving Averages the bars will be less distracting (more like a background)
- a bit more comments for newbies to figure out what is going on :)
Here she comes:
library(ggplot2)
library(quantmod)
draw_candles <- function(df, title_param, alpha_param = 1){
df$change <- ifelse(df$Close > df$Open, "up", ifelse(df$Close < df$Open, "down", "flat"))
# originally the width of the bars was calculated by FXQuantTrader with use of 'periodicity()', which
# seems to work ok only with: ‘minute’,‘hourly’, ‘daily’,‘weekly’, ‘monthly’,
# ‘quarterly’, and ‘yearly’, but can not do 1 sec bars while we want arbitrary bar size support!-)
# df$width <- as.numeric(periodicity(df)[1])
# So let us instead find delta (seconds) between 1st and 2nd row and just
# use it for all other rows. We check 1st 3 rows to avoid larger "weekend gaps"
width_candidates <- c(as.numeric(difftime(df$Date[2], df$Date[1]), units = "secs"),
as.numeric(difftime(df$Date[3], df$Date[2]), units = "secs"),
as.numeric(difftime(df$Date[4], df$Date[3]), units = "secs"))
df$width_s = min(width_candidates) # one (same) candle width (in seconds) for all the bars
# define the vector of candle colours either by name or by rgb()
#candle_colors = c("down" = "red", "up" = "green", "flat" = "blue")
candle_colors = c("down" = rgb(192,0,0,alpha=255,maxColorValue=255), "up" = rgb(0,192,0,alpha=255,maxColorValue=255), "flat" = rgb(0,0,192,alpha=255,maxColorValue=255))
# Candle chart:
g <- ggplot(df, aes(x=Date))+
geom_linerange(aes(ymin=Low, ymax=High, colour = change), alpha = alpha_param) + # candle whiskerss (vertical thin lines:)
theme_bw() +
labs(title=title_param) +
geom_rect(aes(xmin = Date - width_s/2 * 0.9, xmax = Date + width_s/2 * 0.9, ymin = pmin(Open, Close), ymax = pmax(Open, Close), fill = change), alpha = alpha_param) + # cabdke body
guides(fill = FALSE, colour = FALSE) +
scale_color_manual(values = candle_colors) + # color for line
scale_fill_manual(values = candle_colors) # color for candle fill
# Handle special cases: flat bar and Open == close:
if (any(df$change == "flat")) g <- g + geom_segment(data = df[df$change == "flat",], aes(x = Date - width_s / 2 * 0.9, y = Close, yend = Close, xend = Date + width_s / 2 * 0.9, colour = change), alpha = alpha_param)
#print(g)
g
}