Skip to content

Instantly share code, notes, and snippets.

@chalg
Created October 4, 2021 01:22
Show Gist options
  • Save chalg/a36cb1becec225a3f4adaea45738c9d6 to your computer and use it in GitHub Desktop.
Save chalg/a36cb1becec225a3f4adaea45738c9d6 to your computer and use it in GitHub Desktop.
Gather Manufacturing PMIs to display via gt()
# Libraries ----
library(tidyverse)
library(tidyquant)
library(timetk)
library(formattable)
library(scales)
# library(fredr)
library(gt)
quandl_api_key("your-api-key-here")
# Manufacturing PMIs ----
# PMI index itself comes in a different format to the components, so pull in
# separately, wrangle and bind rows later.
pmi_manual <-
tribble(
~symbol, ~title,
"ISM/MAN_PMI", "PMI"
)
pmi_components_manual <-
tribble(
~symbol, ~title,
"ISM/MAN_NEWORDERS", "New Orders",
"ISM/MAN_PROD", "Production",
"ISM/MAN_EMPL", "Employment",
"ISM/MAN_DELIV", "Deliveries",
"ISM/MAN_INVENT", "Inventory",
"ISM/MAN_BACKLOG", "Backlog",
"ISM/MAN_IMPORTS", "Imports",
"ISM/MAN_EXPORTS", "Exports",
"ISM/MAN_PRICES", "Prices"
)
pmi_comps <-
pmi_components_manual %>%
tq_get(get = "quandl", from = "2018-01-01")
pmi_subset <-
pmi_comps %>%
select(title,
pmi_code = symbol,
date,
value = index)
pmi <- pmi_manual %>%
tq_get(get = "quandl", from = "2018-01-01")
pmi <- pmi %>%
select(title,
pmi_code = symbol,
date,
value = pmi)
pmi_prepared <- pmi %>%
bind_rows(pmi_subset)
pmi_for_chart <- pmi_prepared %>%
group_by(pmi_code) %>%
mutate(year_change = value / lag(value, 12) - 1 %>% formattable::percent(digits = 2),
percent_label = scales::percent(round(year_change, 2)),
`series name` = title) %>%
drop_na() %>%
ungroup() %>%
select( `series name`, date, year_change) %>%
pivot_wider(names_from = `series name`, values_from = year_change) %>%
mutate(date = as.yearmon(date, "%Y %m")) %>%
arrange(desc(date))
col_vars <-
colnames(pmi_for_chart[,-1])
pmi_gt_tbl <- pmi_for_chart %>%
filter(date >= "2019-08-01") %>%
gt(rowname_col = "date") %>%
data_color(
columns = col_vars,
colors = scales::col_numeric(
colorspace::diverge_hcl(n = 20, palette = "Blue-Yellow 3"), # %>% rev(),
domain = c(-0.7, 1.6))) %>%
tab_source_note(html("Source: quandl")) %>%
tab_header("Institute for Supply Management PMI Index Changes (YoY)") %>%
tab_options(
data_row.padding = px(1),
table.font.size = 12
) %>%
cols_width(
everything() ~ px(80)
)
pmi_gt_tbl
# Save gt table as PNG
pmi_gt_tbl %>%
gtsave(
"pmi_index_yoy.png",
path = "images"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment