Skip to content

Instantly share code, notes, and snippets.

@jkr216
Created April 25, 2023 18:32
Show Gist options
  • Save jkr216/b27edc2d37602e85a5a1e86455f83b52 to your computer and use it in GitHub Desktop.
Save jkr216/b27edc2d37602e85a5a1e86455f83b52 to your computer and use it in GitHub Desktop.
```{r, include = FALSE}
library(XML)
library(tidyverse)
library(tidyquant)
library(timetk)
library(readxl)
library(plotly)
library(scales)
library(fredr)
library(Quandl)
library(riingo)
library(config)
library(here)
library(httr)
library(jsonlite)
library(patchwork)
library(cowplot)
library(gt)
library(janitor)
library(ggtext)
```
```{r}
ten_year_monthly <-
"DGS10"%>%
tq_get(get = "economic.data",
from = "1979-01-01") %>%
summarise_by_time(
.date_var = date,
.by = "month",
yield = mean(price, na.rm = T)
)
food_energy <-
tibble(
symbol = c('PFOODINDEXM', 'PNRGINDEXM'),
name = c("food_index", "energy_index")
) %>%
tq_get(get = "economic.data",
from = "2013-01-01")
food_energy_treasuries <-
ten_year_monthly %>%
left_join(
food_energy %>%
select(-symbol) %>%
pivot_wider(names_from = name,
values_from = price) %>%
mutate(food_energy_ratio = food_index/energy_index) %>%
select(date, food_energy_ratio),
by = "date"
)
```
```{r}
# * Make A Y-Axis Transformer ----
transformer_food_energy_treasuries <- food_energy_treasuries %>%
transformer_dual_y_axis(
primary_column = food_energy_ratio,
secondary_column = yield,
include_y_zero = T
)
```
```{r}
food_energy_treasuries %>%
# filter(date >= "2000-01-01") %>%
ggplot(aes(x = date)) +
geom_line(aes(y = food_energy_ratio),
color = "darkblue") +
geom_line(
aes(y = transformer_food_energy_treasuries$inv_func(yield)),
color = "darkgreen") +
theme_minimal() +
scale_y_continuous(
labels = scales::number_format(scale = 1),
name = "Food/Energy Ratio",
breaks = pretty_breaks(10),
sec.axis = sec_axis(
labels = percent_format(scale = 1,
accuracy = .1),
breaks = pretty_breaks(10),
trans = ~transformer_food_energy_treasuries$scale_func(.),
name = "10-Year Yield"
)
) +
labs( title = "<span style = 'color: darkblue;'>Food/Energy</span> v. <span style = 'color: darkgreen;'>10-Year Yield</span>",
x = "") +
scale_x_date(
date_labels = "%Y",
date_breaks = "1 years"
) +
theme(
plot.title = element_markdown(hjust = .5),
axis.text.y.right = element_text(color = "darkgreen"),
axis.title.y.right = element_text(color = "darkgreen"),
axis.title.y.left = element_text(color = "darkblue"),
axis.text.y.left = element_text(color = "darkblue")
)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment