Skip to content

Instantly share code, notes, and snippets.

@jkr216
Created January 23, 2022 17:38
Show Gist options
  • Save jkr216/6e4a9b8063f213c52d47162d20a49730 to your computer and use it in GitHub Desktop.
Save jkr216/6e4a9b8063f213c52d47162d20a49730 to your computer and use it in GitHub Desktop.
real-interest-rates
library(tidyverse)
library(tidyquant)
library(timetk)
library(readxl)
library(plotly)
library(scales)
library(formattable)
library(fredr)
library(broom)
### Real Interest
```{r}
ten_year_cpi_diff <-
"DGS10" %>%
tq_get(get= "economic.data", from = "1959-01-01") %>%
select(date, ten_year_daily = price) %>%
summarise_by_time(
.date_var = date,
.by = "month",
ten_year_monthly = mean(ten_year_daily, na.rm = T)/100
) %>%
left_join(
"CPIAUCSL" %>%
tq_get(get= "economic.data", from = "1959-01-01") %>%
select(date, cpi = price) %>%
mutate(
cpi_1_year_rate = cpi/lag(cpi, 12) - 1
)
) %>%
mutate(real_rates = ten_year_monthly - cpi_1_year_rate)
library(patchwork)
chart_1 <-
ten_year_cpi_diff %>%
mutate(col_pos =
if_else(real_rates > 0,
real_rates, as.numeric(NA)),
col_neg =
if_else(real_rates <= 0,
real_rates, as.numeric(NA))) %>%
ggplot(aes(x = date)) +
geom_line(aes(y = col_neg),
alpha = .85,
color = "darkred") +
geom_line(aes(y = col_pos),
alpha = .85,
color = "darkgreen") +
# geom_line(aes(y =cpi_1_year_rate),
# alpha = .85,
# color = "darkblue") +
# geom_line(aes(y =ten_year_monthly),
# alpha = .85,
# color = "darkorange") +
theme_minimal() +
scale_y_continuous(labels = percent_format(accuracy = 1),
breaks = pretty_breaks(10)) +
scale_x_date(date_breaks = "5 years",
date_labels = "%Y") +
labs( x= "", y = "", title = "Real Interest Rates: 10Y monthly less CPI monthly YoY Rate",
caption = "Source: FRED data and Author Chart")
chart_2 <-
ten_year_cpi_diff %>%
mutate(col_pos =
if_else(real_rates > 0,
real_rates, as.numeric(NA)),
col_neg =
if_else(real_rates <= 0,
real_rates, as.numeric(NA))) %>%
ggplot(aes(x = date)) +
# geom_line(aes(y = col_neg),
# alpha = .85,
# color = "darkred") +
# geom_line(aes(y = col_pos),
# alpha = .85,
# color = "darkgreen") +
geom_line(aes(y =cpi_1_year_rate),
alpha = .85,
color = "darkblue") +
geom_line(aes(y =ten_year_monthly),
alpha = .85,
color = "darkorange") +
theme_minimal() +
scale_y_continuous(labels = percent_format(accuracy = 1),
breaks = pretty_breaks(10)) +
scale_x_date(date_breaks = "5 years",
date_labels = "%Y") +
labs( x= "", y = "", title = "10Y(orange) and CPI monthly YoY Rate (blue)",
caption = "Source: FRED data and Author Chart")
chart_1/chart_2
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment