RObservations #12: Making a Candlestick plot with the ggplot2 and tidyquant packages
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Candlestick plots are something you see regularly when dealing with stocks. Whether you are an investor, an analyst or even an outsider, this type of chart always in interesting to look at. In this brief blog, I’m going to share a custom function I made for making a candlestick charts using ggplot2
and the tidyquant
packages.
Sure tidyquant
has their own charting function chart_Series()
, but I wanted to create my own and give it a shot. I really like how it turned out aesthetically, if you think the same- feel free to use it!
The code
The code here is pretty straight forward. It utilizes the yahooFinance api request function made by tidyquant
and pipes it directly into home-made ggplot2
candlestick plot.
# Libraries we need library(tidyverse) library(tidyquant) # Configuring settings as per tidyquant tutorial options("getSymbols.warning4.0"=FALSE) options("getSymbols.yahoo.warning"=FALSE) # The function candleStick_plot<-function(symbol,from,to){ tq_get(symbol, from = from, to = to, warnings = FALSE) %>% mutate(greenRed=ifelse(open-close>0, "Red", "Green")) %>% ggplot()+ geom_segment(aes(x = date, xend=date, y =open, yend =close, colour=greenRed), size=3)+ theme_tq()+ geom_segment(aes(x = date, xend=date, y =high, yend =low, colour=greenRed))+ scale_color_manual(values=c("Forest Green","Red"))+ ggtitle(paste0(symbol," (",from," - ",to,")"))+ theme(legend.position ="none", axis.title.y = element_blank(), axis.title.x=element_blank(), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1), plot.title= element_text(hjust=0.5)) }
Just copy the above code and have a blast!
Testing it out
# Bitcoin Price # Time of writing this blog 9/14/2021 candleStick_plot("BTC-USD",from = '2021-07-01',to = lubridate::today())
# Bombardier Price # Time of writing this blog 9/14/2021 candleStick_plot('BBD-B.TO',from = '2021-07-01',to = lubridate::today())
Want to see more of my content?
Be sure to subscribe and never miss an update!
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.