Skip to content

Instantly share code, notes, and snippets.

@USMortality
Last active March 11, 2025 13:04
Show Gist options
  • Save USMortality/536782d8a7c96cf4198e762870ec28b8 to your computer and use it in GitHub Desktop.
Save USMortality/536782d8a7c96cf4198e762870ec28b8 to your computer and use it in GitHub Desktop.
Inflation Rate [USA]
library(dplyr)
library(ggplot2)
library(httr)
library(jsonlite)
library(lubridate)
library(tsibble)
sf <- 2
width <- 600 * sf
height <- 335 * sf
options(vsc.dev.args = list(width = width, height = height, res = 72 * sf))
get_data <- function(from, to) {
req <- httr::POST("https://api.bls.gov/publicAPI/v2/timeseries/data/",
httr::add_headers("Content-Type" = "application/json"),
body = paste0(
'{"seriesid": ["CUUR0000SA0"], "startyear":"',
from,
'", "endyear":"',
to,
'"}'
)
)
httr::stop_for_status(req)
data <- httr::content(req, "text") |>
jsonlite::fromJSON()
as_tibble(data$Results$series$data[[1]]) |>
mutate(year = as.integer(year)) |>
mutate(period = as.integer(substr(.data$period, 2, 3))) |>
mutate(value = as.double(.data$value)) |>
mutate(yearmonth = tsibble::yearmonth(paste0(year, "-", period))) |>
mutate(value_ref = dplyr::lead(value, 12)) |>
mutate(value_p = value / .data$value_ref - 1) |>
filter(!is.na(value_ref)) |>
select(yearmonth, value_p)
}
current_year <- year(Sys.Date())
# Load Data
df_inflation <- rbind(
get_data(current_year - 9, current_year),
get_data(current_year - 19, current_year - 10),
get_data(current_year - 29, current_year - 20),
get_data(current_year - 39, current_year - 30),
get_data(current_year - 49, current_year - 40),
get_data(current_year - 59, current_year - 50),
get_data(current_year - 69, current_year - 60),
get_data(current_year - 79, current_year - 70),
get_data(current_year - 89, current_year - 80),
get_data(current_year - 99, current_year - 90)
)
# Make Chart
chart <- ggplot(
as_tsibble(df_inflation, index = yearmonth),
aes(x = yearmonth, y = value_p)
) +
labs(
title = "Inflation Rate [USA]",
subtitle = "Source: bls.gov",
x = "Month of Year",
y = "12M Rate of Increase"
) +
geom_line(color = "#5383EC", linewidth = 1.5) +
geom_hline(yintercept = 0) +
geom_hline(aes(yintercept = 0.02), color = "#58A65C", linetype = "dashed") +
scale_y_continuous(labels = scales::percent) +
ggrepel::geom_label_repel(
data = head(df_inflation, n = 1) |> mutate(str = paste0(
yearmonth,
": ",
sprintf("%0.1f%%", value_p * 100)
)),
aes(label = str),
nudge_y = 0.1,
segment.color = "grey50",
)
ggplot2::ggsave(
filename = "chart1.png", plot = chart, width = width, height = height,
units = "px", dpi = 72 * sf, device = grDevices::png, type = c("cairo")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment