Column

Including Mortgage Crisis

After Mortgage Crisis

Column

Forecasting the next 24 months with GluonTS DeepAR Algorithm

---
title: "A glance at Freddie Mac and the variables that might drive 
it"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    source_code: embed
    theme:
      version: 5
      bootswatch: minty
      base_font: Baskerville Old Face
      heading_font:
        google: Bricolage Grotesque
      code_font:
        google: Roboto Mono
---
<!-- Making titles centered and bold with inline css -->
```{css, echo=FALSE}
.chart-title {
  text-align: center;
  font-weight: bold;
  }
```
```{r setup, include=FALSE}
library(tidyverse)
library(tidyquant)

#Federal Home Loan Mortgage Corporation (FMCC)
df_fmcc <- 
  tq_get("FMCC",
         from = "2000-01-01",
         to = "2023-09-01") %>% 
  tq_transmute(select = close,
               mutate_fun = to.monthly) %>% 
  mutate(date = as.Date(date)) %>% 
  rename(fmcc = close)

#FED fund rates
df_fed <- 
  read_csv("https://raw.githubusercontent.com/mesdi/blog/main/fedfunds.csv") %>% 
  mutate(DATE = parse_date(DATE, "%m/%d/%Y")) %>% 
  janitor::clean_names()
  

#Treasury Yield 10 Years (^TNX)
df_tnx <- 
  tq_get("^TNX",
         from = "2000-01-01",
         to = "2023-09-01") %>% 
  tq_transmute(select = close,
               mutate_fun = to.monthly) %>% 
  mutate(date = as.Date(date)) %>% 
  rename(tnx = close)

#Merging all the data into a data frame
df_merged <- 
  df_fmcc %>% 
  left_join(df_tnx) %>% 
  left_join(df_fed) 
```
Column
--------------------------------------
### Including Mortgage Crisis 
```{r}
library(dygraphs)

dygraph(df_merged) %>% 
  dySeries("fmcc", label = "FMCC") %>% 
  dySeries("tnx", label = "TNX") %>% 
  dySeries("fedfunds", label = "FED") %>% 
  dyOptions(stackedGraph = TRUE, drawGrid = FALSE) %>%
  dyShading(from = "2007-1-1", 
            to = "2009-1-1",
            color = "#FF7276") %>% 
  dyAnnotation("2008-1-1",
               text = "Mortgage Crisis",
               attachAtBottom = TRUE,
               tooltip = "",
               width = 100,
               height = 20) 
```
### After Mortgage Crisis 
```{r}
library(dygraphs)

  df_merged %>% 
  filter(year(date) > 2009) %>%
  dygraph() %>% 
  dySeries("fmcc", label = "FMCC") %>% 
  dySeries("tnx", label = "TNX") %>% 
  dySeries("fedfunds", label = "FED") %>%
  dyOptions(stackedGraph = TRUE, drawGrid = FALSE)  
```
Column 
----------------------------------
### <span style = 'color:red;'>Forecasting</span> the next 24 months with GluonTS DeepAR Algorithm
```{r}
library(modeltime.gluonts)
library(timetk)
library(tidymodels)
library(plotly)
library(ragg)


#Adding id column for deep_ar function
df_deepar <- 
  df_merged %>% 
  pivot_longer(-date, names_to = "vars") %>% 
  mutate(vars = toupper(vars))
  

#Making fitted a GluonTS DeepAR Model
model_fit <- deep_ar(
  id = "vars",
  freq = "M",
  prediction_length = 24,
  lookback_length = 48,
  epochs = 5
) %>%
    set_engine("gluonts_deepar") %>%
    fit(value ~ vars + date, df_deepar)


#Future dataset for 24 months ahead
df_future <- 
  df_deepar %>% 
  group_by(vars) %>% 
  future_frame(.length_out = 24) %>% 
  ungroup()
  
#Forecasting data frame
df_fc <- 
  modeltime_table(
    model_fit
) %>%
  modeltime_forecast(
    new_data    = df_future,
    actual_data = df_deepar %>% filter(year(date) > 2009),
    keep_data   = TRUE
  ) %>%
  group_by(vars) 

#Comparing forecasting plots
df_fc %>%
  plot_modeltime_forecast(
    .conf_interval_show = FALSE, 
    .facet_ncol = 1, 
    .facet_scales = "free_y",
    .interactive = TRUE,
    .legend_show = FALSE,
    .title = ""
  ) %>% 
  #customizing the hoverinfo texts of the traces(lines)
  style(text = glue::glue("FED FUNDS\n{.$x$data[[1]]$x}\n{round(.$x$data[[1]]$y, 2)}"), traces = 1) %>% 
  style(text = glue::glue("FED FUNDS\n{.$x$data[[4]]$x}\n{round(.$x$data[[4]]$y, 2)}"), traces = 4) %>% 
  style(text = glue::glue("FMCC\n{.$x$data[[2]]$x}\n{round(.$x$data[[2]]$y, 2)}"), traces = 2) %>% 
  style(text = glue::glue("FMCC\n{.$x$data[[5]]$x}\n{round(.$x$data[[5]]$y, 2)}"), traces = 5) %>% 
  style(text = glue::glue("TNX\n{.$x$data[[3]]$x}\n{round(.$x$data[[3]]$y, 2)}"), traces = 3) %>% 
  style(text = glue::glue("TNX\n{.$x$data[[6]]$x}\n{round(.$x$data[[6]]$y, 2)}"), traces = 6) %>% 
  #setting font family for tooltip label
  style(hoverlabel = list(
    font = list(
      family = "Baskerville Old Face", 
      size = 20))) %>% 
  #setting font family for the plot
  layout(font = list(family = "Baskerville Old Face",
                     size = 20),
         hoverlabel = list(align = "left")) %>% 
  #Remove plotly buttons from the mode bar
  config(displayModeBar = FALSE)
```