Candlestick charts using Quandl and Plotly

[This article was first published on R – Modern Data, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In this post we’ll show how to create candle stick charts using the new plotly 4.0 syntax. You can refer to this older post as well.

This time we’ll use the Quandl package to retrieve stock data. See here for more details.

install.packages("Quandl")
library(Quandl)
df <- Quandl("WIKI/AAPL")
df <- df[,c(1, 9:12)]

names(df) <- c("Date", "Open", "High", "Low", "Close")
df$Date <- as.Date(df$Date)

df <- df[1:1000,]

hovertxt <- Map(function(x, y)paste0(x, ":", y), names(df), df)
hovertxt <- Reduce(function(x, y)paste0(x, "<br>", y), hovertxt)

plot_ly(df, x = ~Date, xend = ~Date, hoverinfo = "none",
        color = ~Close > Open, colors = c("#00b386","#ff6666")) %>%
  
  add_segments(y = ~Low, yend = ~High, line = list(width = 1, color = "black")) %>%
  
  add_segments(y = ~Open, yend = ~Close, line = list(width = 3)) %>%
  
  add_markers(y = ~(Low + High)/2, hoverinfo = "text",
              text = hovertxt, marker = list(color = "transparent")) %>% 
  
  layout(showlegend = FALSE, 
         color = "white",
         yaxis = list(title = "Price", domain = c(0, 0.9)),
         annotations = list(
           list(xref = "paper", yref = "paper", 
                x = 0, y = 1, showarrow = F, 
                xanchor = "left", yanchor = "top",
                align = "left",
                text = paste0("<b>AAPL</b>")),
           
           list(xref = "paper", yref = "paper", 
                x = 0.75, y = 1, showarrow = F, 
                xanchor = "left", yanchor = "top",
                align = "left",
                text = paste(range(df$Date), collapse = " : "),
                font = list(size = 8))),
         plot_bgcolor = "#f2f2f2")

To leave a comment for the author, please follow the link and comment on their blog: R – Modern Data.

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.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)