Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Created March 26, 2020 16:43
Show Gist options
  • Save andrewheiss/194428dc0eb48e4feaf5b71719518fe4 to your computer and use it in GitHub Desktop.
Save andrewheiss/194428dc0eb48e4feaf5b71719518fe4 to your computer and use it in GitHub Desktop.
library(tidyverse)
library(tidyquant)  # For getting financial data from FRED, other places
library(scales)     # For fun things like comma() and percent()

# Get data from FRED
data_raw <- tq_get(c("ICSA",  # Initial unemployment claims
                     "USREC"),  # Recessions
                   get = "economic.data",  # Use FRED
                   from = "1967-01-07")  # From first day of data

# Wrangle the recession dates so that we just have start and end dates
recessions_raw <- data_raw %>% 
  filter(symbol == "USREC") %>% 
  mutate(recession_delta = price - lag(price))

recessions <- tibble(start = filter(recessions_raw, recession_delta == 1)$date,
                     end = filter(recessions_raw, recession_delta == -1)$date)
recessions
#> # A tibble: 7 x 2
#>   start      end       
#>   <date>     <date>    
#> 1 1970-01-01 1970-12-01
#> 2 1973-12-01 1975-04-01
#> 3 1980-02-01 1980-08-01
#> 4 1981-08-01 1982-12-01
#> 5 1990-08-01 1991-04-01
#> 6 2001-04-01 2001-12-01
#> 7 2008-01-01 2009-07-01

# Rename price to something more logical
claims <- data_raw %>% 
  filter(symbol == "ICSA") %>% 
  rename(claims = price)
head(claims)
#> # A tibble: 6 x 3
#>   symbol date       claims
#>   <chr>  <date>      <int>
#> 1 ICSA   1967-01-07 208000
#> 2 ICSA   1967-01-14 207000
#> 3 ICSA   1967-01-21 217000
#> 4 ICSA   1967-01-28 204000
#> 5 ICSA   1967-02-04 216000
#> 6 ICSA   1967-02-11 229000

# Plot from 1969 to today
full_plot <- ggplot() +
  geom_rect(data = recessions, aes(xmin = start, xmax = end, ymin = -Inf, ymax = Inf),
            fill = "#FF851B", alpha = 0.2) +
  geom_line(data = claims, aes(x = date, y = claims), size = 0.5, color = "#85144b") +
  scale_x_date(date_breaks = "5 years", date_labels = "%Y") +
  scale_y_continuous(labels = comma) +
  labs(x = NULL, y = "Initial unemployment claims",
       title = "HOLY CRAP",
       caption = "Source: Initial weekly unemployment claims (ICSA); FRED\nRecessions highlighted in orange") +
  theme_bw() +
  theme(plot.title = element_text(face = "bold"),
        panel.grid.minor.x = element_blank())
full_plot

# Plot from 2000 to today
full_plot +
  coord_x_date(xlim = c("2000-01-01", "2020-03-26")) +
  scale_x_date(date_breaks = "2 years", date_labels = "%Y")

Created on 2020-03-26 by the reprex package (v0.3.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment