Skip to content

Instantly share code, notes, and snippets.

@charlie86
Last active April 28, 2020 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlie86/50e7c8bb4685d3d561fd57c0ebb50fd9 to your computer and use it in GitHub Desktop.
Save charlie86/50e7c8bb4685d3d561fd57c0ebb50fd9 to your computer and use it in GitHub Desktop.
library(scales)
library(ggrepel)
library(ggthemes)
library(tidyverse)
library(tidyquant)
library(lubridate)
stocks <- tq_get(c('FB', 'NFLX', 'AAPL', 'GOOG', 'AMZN'),
get = 'stock.prices',
from = Sys.Date() - years(1)) %>%
select(date, adjusted, symbol)
index_date <- as.Date('2020-01-02')
index_value <- stocks %>%
filter(date == index_date) %>%
select(symbol, base = adjusted)
plot_df <- stocks %>%
filter(date >= '2020-01-01') %>%
left_join(index_value, by = 'symbol') %>%
mutate(adjusted = round(adjusted / base * 100, digits = 2),
symbol = factor(symbol, levels = c('FB', 'AMZN', 'AAPL', 'NFLX', 'GOOG')))
label_values <- plot_df %>%
mutate(date_group = case_when(date == max(date) ~ 'latest',
date == index_date ~ 'first',
TRUE ~ as.character(NA))) %>%
filter(!is.na(date_group)) %>%
group_by(symbol) %>%
mutate(pct_change = (adjusted[date_group == 'latest'] - adjusted[date_group == 'first']) / adjusted[date_group == 'first']) %>%
ungroup() %>%
filter(date_group == 'latest') %>%
mutate(prefix = ifelse(as.numeric(pct_change) > 0, '+', ''),
label = paste0(symbol, ': ', prefix, scales::percent(pct_change, accuracy = 1), ' YTD'))
plot_df %>%
ggplot(aes(x = date, y = adjusted, color = symbol)) +
geom_line(size = 1) +
geom_text_repel(data = label_values, aes(label = label), size = 3, nudge_x = 30, show.legend = FALSE) +
labs(x = '', y = '', color = '',
title = 'Not all FAANGs are created equal',
subtitle = 'Netflix and Amazon are weathering COVID-19 far better than the rest of big tech',
caption = 'Data through Apr 24, 2020. Stock prices indexed to 100 as of Jan 2, 2020') +
scale_x_date(limits = c(as.Date(NA), as.Date('2020-06-01'))) +
theme_economist()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment