Visualizing Stock Price of Multiple Companies Over Time

In this tutorial, we will learn how to visualize stock prices of multiple companies over time. Stock data is a great example of time series data, where we have stock price of a company for a period of time. First, we will show how to get stock price for multiple companies of interest and use ggplot2 to make a simple line plot to see the price over time.

Let us load the packages needed.

library(tidyquant)
library(tidyverse)
theme_set(theme_bw(16))

Since we are interested in multiple companies’ stock price, let us create a vector containing the ticker names of the companies.

tickers <- c("MSFT","FB","AAPL")

We can use tidyquant’s tq_get() function to get the stock prices of multiple companies in the same was as a single company.

stock_df <- tq_get(tickers,
                          get = "stock.prices",
                          from = "2015-01-01",
                          to = "2021-12-31")
stock_df %>% head()
## # A tibble: 6 × 8
##   symbol date        open  high   low close   volume adjusted
##   <chr>  <date>     <dbl> <dbl> <dbl> <dbl>    <dbl>    <dbl>
## 1 MSFT   2015-01-02  46.7  47.4  46.5  46.8 27913900     41.2
## 2 MSFT   2015-01-05  46.4  46.7  46.2  46.3 39673900     40.8
## 3 MSFT   2015-01-06  46.4  46.8  45.5  45.7 36447900     40.2
## 4 MSFT   2015-01-07  46.0  46.5  45.5  46.2 29114100     40.7
## 5 MSFT   2015-01-08  46.8  47.8  46.7  47.6 29645200     41.9
## 6 MSFT   2015-01-09  47.6  47.8  46.9  47.2 23944200     41.6

To make the line plot or time series plot for multiple companies, we specify color argument and specify the ticker names to plot different companies in different color.

stock_df %>%
  ggplot(aes(x=date, y=adjusted,  color=symbol))+
  geom_line()
ggsave("multi_company_stock_prices_over_time.png")
Visualizing Multiple Companies Stock Price Over Time
Visualizing Multiple Companies Stock Price Over Time

We can further customize the colors using scale_color_brewer() as another layer with a specific palette of interest.

stock_df %>%
  ggplot(aes(x=date, y=adjusted,  color=symbol))+
  geom_line(size=1)+
  scale_color_brewer(palette = "Set2")
ggsave("customizing_colors_stock_prices_over_time.png")
Customizing Colors: Multiple Stock Price Over Time

Leave a comment

Your email address will not be published. Required fields are marked *

Exit mobile version