library(ggplot2)
library(quantmod) #To get the stock
library(scales)
library(dplyr)
library(tidyverse)
library(dygraphs) #To visualize
library(xts) #To make the convertion data-frame / xts format, requested by dygraphs

VIZUALIZATION WITH GGPLOT

# Let's Take the Closing Date of Ferrari Stock
FERRARI <- getSymbols("RACE",
                          return.class = "data.frame",
                          from = "2021-01-01",
                          to = "2021-07-31")
FERRARI <- RACE %>%
  mutate(Date = as.Date(row.names(.))) %>%
  select(Date, RACE.Close) %>%
  rename(Close = RACE.Close) %>%
  mutate(Company = "FERRARI")
# Let's Take the Closing Date of Toyota Stock
TOYOTA <- getSymbols("TM",
                     return.class = "data.frame",
                     from = "2021-01-01",
                     to = "2021-07-31")

TOYOTA <- TM %>%
  mutate(Date = as.Date(row.names(.))) %>%
  select(Date, TM.Close) %>%
  rename(Close = TM.Close) %>%
  mutate(Company = "TOYOTA")
# Let's bind these two time series together
time_series <- rbind(FERRARI, TOYOTA)
# After binding it into a dataframe, here's how you can visualize it:
ggplot(time_series, 
       aes(x=Date, y= Close, color=Company)) + 
  labs(title = "Comparison Stock Ferrari VS Toyota",
       subtitle = "January 2021 - July 2021  ",
       x="Month",
       y="Close Stock")+
  scale_y_continuous(labels = scales::dollar)+
  scale_x_date(date_breaks = "1 month",
               labels = date_format("%b"))+
  geom_line(size=1.5)+
  geom_smooth(size=.5)+
  theme_minimal()+
  theme(axis.title = element_text(size=10,face="bold"),
        legend.title = element_text(size=10,face="bold"))

VISUALIZATION WITH DYGRAPHS

#Ferrari Stock
FERRARI2 <- getSymbols("RACE",
                      return.class = "data.frame",
                      from = "2021-01-01",
                      to = "2021-07-31")
FERRARI2 <- RACE %>%
  mutate(Date = as.Date(row.names(.))) %>%
  select(Date, RACE.Close) %>%
  rename(Ferrari = RACE.Close)
#Toyota Stock
TOYOTA2 <- getSymbols("TM",
                     return.class = "data.frame",
                     from = "2021-01-01",
                     to = "2021-07-31")
TOYOTA2 <- TM %>%
  mutate(Date = as.Date(row.names(.))) %>%
  select(Date, TM.Close) %>%
  rename(Toyota = TM.Close)
#join the stock
Stock<-left_join(FERRARI2,TOYOTA2)
Stock=xts( x=Stock[,-1], order.by=Stock$Date)
#Interactive Visualization
dygraph(Stock, 
        main = "Comparison Stock Ferrari VS Toyota",
        ylab = "Close Stock ($)") %>% 
  dyLegend(width = 400) %>%
  dyHighlight(highlightCircleSize = 5,
              highlightSeriesBackgroundAlpha = 0.2)%>%
  dyLegend(show = "follow")%>%
  dyRangeSelector()