# Set the default language of date in R
Sys.setlocale("LC_TIME", "English")

# Setup and load packages
knitr::opts_knit$set(progress = TRUE)
if (!require("pacman")) install.packages("pacman")
pacman::p_load(
  "rmarkdown",
  "highcharter",
  "tidyverse",
  "flexdashboard",
  "htmlwidgets",
  "gt",
  "scales",
  "colorspace",
  "magrittr",
  "htmltools",
  "sparkline",
  "rlist"
  )

# Colors for the plots
colors <- c(
  blue   = "#282f6b",
  red    = "#b22200",
  yellow = "#eace3f",
  green  = "#224f20",
  purple = "#5f487c",
  orange = "#b35c1e"
  )
colors_extra <- c(
  colors,
  turquoise  = "#419391",
  green_two  = "#839c56",
  light_blue = "#3b89bc"
  )

# Load funcitons
c("hc_plot_ft", "hc_theme_ft", "gt_sparkline", "utils") %>%
  paste0("./R/", ., ".R") %>% 
  purrr::walk(~source(.x))
# Load RDATA files
c("econ_activity", "fiscal", "inflation", "monetary", "labor") %>%
  paste0("./inst/extdata/", ., ".Rdata") %>% 
  purrr::map( ~ load(.x, .GlobalEnv))

Overview {data-orientation=rows data-icon="fa-signal"}

Row

GDP growth (r gdp_growth$date - IBGE)

big_number_gdp <- gdp_growth %>%
  pull(value) %>%
  valueBox(
    value = .,
    icon  = "fa-chart-line",
    color =  dplyr::case_when(
      gdp_growth$value <= 0 ~ colors[2],
      gdp_growth$value > 0 ~ colors[1])
    )
big_number_gdp

Inflation 12-months (r format(ipca_yoy$date, "%b '%y") - IBGE)

big_number_inflation <- ipca_yoy %>%
  pull(value) %>%
  valueBox(
    value = .,
    icon  = "fa-usd",
    color =  dplyr::case_when(
      ipca_yoy$value > inflation_target$value ~ colors[2],
      ipca_yoy$value < 0 ~ colors[3],
      ipca_yoy$value < inflation_target$value ~ colors[1],
      ipca_yoy$value == inflation_target$value ~ colors[5])
    )
big_number_inflation

Unemployment rate (r tail(unemployment$date, 1) - IBGE)

unemployment %>%
  slice_tail() %>%
  mutate(unemployment_rate = paste0(unemployment_rate, "%")) %>%
  pull(unemployment_rate) %>% 
  valueBox(
    value = .,
    icon = "fa-users",
    color = dplyr::case_when(
      mean(unemployment$unemployment_rate) < tail(unemployment$unemployment_rate, 1) ~ colors[2],
      mean(unemployment$unemployment_rate) > tail(unemployment$unemployment_rate, 1) ~ colors[4],
      TRUE ~ colors[5]
      )
    )

Primary Deficit (r format(tail(primary_deficit$date, 1), "%b '%y") - STN)

primary_deficit %>%
  filter(date == max(date)) %>%
  mutate(value = paste0(value, "%")) %>%
  pull(value) %>% 
  valueBox(
    value = .,
    icon = "fa-area-chart",
    color = dplyr::case_when(
      tail(primary_deficit$value, 1) < 0 ~ colors[2],
      tail(primary_deficit$value, 1) > 0 ~ colors[1],
      tail(primary_deficit$value, 1) == 0 ~ colors[5])
    )

SELIC target rate (r format(selic$date, "%b '%y") - COPOM/BCB)

big_number_selic <- selic %>%
  pull(value) %>%
  valueBox(
    value = .,
    icon  = "fa-percentage",
    color = colors[5]
    )
big_number_selic

Row {.tabset}

GDP growth

gdp_trend <- gdp_growth_sector %>%
  hchart("column", hcaes(x = date, y = value, group = sector), color = colors[1:4]) %>%
  hc_plot_ft(
    title     = "GDP growth by sectors",
    subtitle  = "Accumulated growth rate in 4 quarters",
    source    = "IBGE",
    range     = FALSE,
    navigator = FALSE
    )
gdp_trend

Inflation trend

inflation_trend <- hchart(
  ipca_trend, "column", hcaes(x = date, y = `Month over Month (%)`),
       color = colors[1], name = "Month over Month", showInLegend = TRUE
  ) %>%
  hc_add_series(
    ipca_trend, "line", hcaes(x = date, y = `Year over Year (%)`),
    color = colors[2], name = "Year over Year", showInLegend = TRUE
  ) %>% 
  hc_plot_ft(
    title     = "Inflation trend (IPCA)",
    subtitle  = "Monthly and accumulated variation in 12 months (%)",
    source    = "IBGE",
    navigator = FALSE
    )
inflation_trend

Unemployment rate

unemployment_trend <- unemployment %>%
  hchart(
    "area", hcaes(x = date, y = unemployment_rate), color = colors[1],
    name = "Unemployment rate", fillOpacity = 0.1) %>%
  hc_plot_ft(
    title     = "Unemployment rate",
    subtitle  = "Quarterly data (PNADC-T)",
    source    = "IBGE",
    range     = FALSE,
    navigator = FALSE
    )
unemployment_trend

Unemployment by states

unemployment_map <- hcmap(
  map               = "countries/br/br-all",
  data              = unemployment_states,
  joinBy            = "woe-name",
  value             = "unemployment_rate",
  name              = "Unemployment rate",
  download_map_data = TRUE,
  dataLabels        = list(
    enabled = TRUE,
    format  = "{point.name}"
    ),
  mapNavigation = list(
    enabled       = TRUE,
    buttonOptions = list(
      verticalAlign = "bottom"
      )
    )
  ) %>% 
  hc_title(text = "Unemployment rate by states") %>% 
  hc_subtitle(text = paste0(
      "Quarterly data, updated until ", unemployment_states$date[1], " (PNADC-T)"
      )
      ) %>%
  hc_credits(enabled = TRUE, text = "Source: IBGE", style = list(fontSize = "12px"))
unemployment_map

Primary deficit trend

primary_deficit_trend <- primary_deficit %>%
  hchart(
    "area", hcaes(x = date, y = value), color = colors[1],
    name = "Primary Deficit", fillOpacity = 0.1
    ) %>%
  hc_plot_ft(
    title     = "Central Government Primary Deficit",
    subtitle  = "Accumulated in 12 months (% GDP)",
    source    = "STN and IBGE",
    navigator = FALSE
    )
primary_deficit_trend

Real interest rates

real_interest_rate_trend <- real_interest_rate %>%
  hchart(
    "area", hcaes(x = date, y = value, group = variable),
    color = colors[1:2], fillOpacity = 0.1
    ) %>%
  hc_plot_ft(
    title     = "Real interest rates",
    subtitle  = "In % p.a.",
    source    = "B3, BCB and IBGE",
    navigator = FALSE
    )
real_interest_rate_trend

Exchange rate

exchange_rate <- currencies %>%
  gt() %>%
  tab_header(
    title = gt::html("<b>Exchange rate performance</b>")
    ) %>%
  tab_source_note(
    gt::html("Source: BCB")) %>%
  tab_footnote(
    footnote = footnote_currency,
    locations = cells_column_labels(columns = vars(value))
    ) %>%
  tab_footnote(
    footnote = "MoM: monthly percentage change",
    locations = cells_column_labels(columns = vars(mom))
    ) %>%
  tab_footnote(
    footnote = "YTD: percentage change in the year",
    locations = cells_column_labels(columns = vars(ytd))
    ) %>% 
  tab_footnote(
    footnote = "YoY: accumulated in 12 months percentage change against the same period of the previous year",
    locations = cells_column_labels(columns = vars(yoy))
    ) %>%
  tab_options(
    data_row.padding = px(2)
    ) %>%
  text_transform(
    locations = cells_body(columns = vars(flag)),
    fn = function(x){
      map_chr(x, ~ gt::local_image(
        filename = .x,
        height = 25
      ))
    }
    ) %>%
  fmt_currency(
    columns = vars(value),
    currency = "BRL",
    incl_space = TRUE
    ) %>%
  fmt_percent(
    columns = vars(mom, ytd, yoy),
    scale_values = FALSE
    ) %>%
  cols_align(
    align = "center",
    columns = vars(flag)
    ) %>%
  cols_label(
    flag     = "",
    currency = "Currency",
    value    = "CUR/BRL",
    mom      = "MoM",
    ytd      = "YTD",
    yoy      = "YoY",
    spark    = "Trend"
    ) %>%
  tab_style(
    style = cell_text(weight = "bold"),
    locations = cells_column_labels(TRUE)
    ) %>%
  data_color(
    columns = 5:7,
    colors = scales::col_numeric(
      colorspace::diverge_hcl(n = 20, palette = "Blue-Red 3"),
      reverse = TRUE,
      domain = c(-max_abs(currencies[5:7]), max_abs(currencies[5:7]))
      )
    ) %>%
  gt_sparkline(spark, "spark") %>%
  gt:::as.tags.gt_tbl() %>% 
  htmltools::attachDependencies(htmlwidgets::getDependency("sparkline"))
exchange_rate

Ibovespa index

ibovespa_candle <- highchart(type = "stock") %>%
  hc_yAxis_multiples(create_yaxis(2, height = c(2, 1), turnopposite = TRUE)) %>%
  hc_add_series(ibovespa, yAxis = 0, name = "Ibovespa") %>%
  hc_add_series(
    ibovespa$BVSP.Volume,
    color = "gray",
    yAxis = 1,
    name  = "Volume",
    type  = "column"
    ) %>%
  hc_title(text = "Ibovespa index") %>%
  hc_credits(enabled = TRUE, text = "Source: B3", style = list(fontSize = "12px")) %>%
  hc_rangeSelector(selected = 1, inputEnabled = FALSE) %>%
  hc_add_theme(theme_fortietwo) %>%
  hc_plotOptions(
    candlestick = list(
      color   = unname(colors[2]),
      upColor = unname(colors[4])
      )
    )
ibovespa_candle

Economic activity {data-navmenu="Sections" data-icon="fa-chart-line"}

Column {data-width=375}

GDP growth in 4 quarters (r gdp_growth$date - IBGE)

big_number_gdp

GDP at current prices in 4 quarters (r gdp_cur_prices$date - IBGE)

gdp_cur_prices %>%
  pull(value) %>%
  valueBox(
    value = .,
    icon  = "fa-dollar-sign",
    color = "#224f20"
    )

Cielo retail index (r format(icva$date, "%B, %Y") - ICVA)

icva %>%
  pull(value) %>%
  valueBox(
    value = .,
    icon  = "fa-store",
    color =  ifelse(. < 0, "#b22200", "#282f6b")
    )

Vehicle production (r format(vehicle$date, "%B, %Y") - ANFAVEA)

vehicle %>%
  pull(value) %>%
  valueBox(
    value = .,
    icon  = "fa-car",
    color = "#5f487c"
    )

Installed Capacity Utilization Level (r format(nuci$date, "%B, %Y") - FGV)

gauge(
  value  = nuci$value,
  min    = 0,
  max    = 100,
  symbol = "%",
  gaugeSectors(
    success = c(85, 100),
    warning = c(50, 85),
    danger  = c(0, 50),
    colors = c("#224f20", "#b35c1e", "#b22200")
    )
  )

Column {data-width=575}

GDP trend {.no-title}

gdp_trend

IBC-Br trend {.no-title}

ibc_growth %>%
  hchart("line", hcaes(x = date, y = yoy, group = variable), color = colors) %>%
  hc_plot_ft(
    title     = "IBC-Br growth by region",
    subtitle  = "Accumulated growth rate in 12 months",
    source    = "BCB",
    navigator = FALSE
    )

Column {data-width=500 .tabset}

GDP approaches

gdp_measures %>%
  gt(rowname_col = "sector") %>%
  tab_source_note(footnote_gdp) %>% 
  tab_source_note("Source: IBGE") %>%
  tab_footnote(
    footnote = "Growth rate for the quarter versus the immediately preceding quarter",
    locations = cells_column_labels(columns = vars(`Quarter over Quarter`))
    ) %>% 
  tab_footnote(
    footnote = "Quarterly growth rate (compared to the same period of the previous year)",
    locations = cells_column_labels(columns = vars(`Year over Year`))
    ) %>% 
  tab_footnote(
    footnote = "Accumulated growth rate over the year (compared to the same period of the previous year)",
    locations = cells_column_labels(columns = vars(`Year to Date`))
    ) %>% 
  tab_footnote(
    footnote = "Growth rate accumulated in 4 quarters (compared to the same period of the previous year)",
    locations = cells_column_labels(columns = vars(`Accumulated in 4 Quarters`))
    ) %>%
  data_color(
    columns = 2:5,
    colors = scales::col_numeric(
      colorspace::diverge_hcl(n = 20, palette = "Blue-Red 3"),
      reverse = TRUE,
      domain = c(-max_abs(gdp_measures[2:5]), max_abs(gdp_measures[2:5]))
      )
    ) %>%
  fmt_percent(columns = 2:5, scale_values = FALSE, decimals = 1) %>%
  cols_width(2:5 ~ px(125)) %>% 
  tab_options(
    column_labels.font.weight = "bold",
    stub.font.weight = "bold",
    footnotes.padding = 3,
    data_row.padding = 6
    )

Retail (PMC)

pmc %>%
  hchart("line", hcaes(x = date, y = value, group = variable), color = colors[1:4]) %>%
  hc_plot_ft(
    title    = "Retail trade index: PMC/IBGE",
    subtitle = "Monthly percentage change (compared to the same month in the previous year)",
    source   = "IBGE"
    )

Services (PMS)

pms %>%
  hchart("line", hcaes(x = date, y = value, group = variable), color = colors[1:2]) %>%
  hc_plot_ft(
    title    = "Revenue and volume of services index: PMS/IBGE",
    subtitle = "Monthly percentage change (compared to the same month in the previous year)",
    source   = "IBGE"
    )

Industry (PIM-PF)

pim %>%
  hchart("line", hcaes(x = date, y = value, group = variable), color = colors[1:4]) %>%
  hc_plot_ft(
    title    = "Industrial production: PIM-PF/IBGE",
    subtitle = "Monthly percentage change (compared to the same month in the previous year)",
    source   = "IBGE"
    )

Inflation {data-navmenu="Sections" data-icon="fa-hand-holding-usd"}

Column {data-width=350}

Inflation over 12 months (r format(ipca_yoy$date, "%B, %Y") - IPCA/IBGE)

big_number_inflation

Inflation target for (r inflation_target$date - CMN/BCB)

inflation_target %>% 
  mutate(value = paste0(value, "%")) %>%
  pull(value) %>%
  valueBox(
    value = .,
    icon = "fa-bullseye",
    color = "#5f487c"
    )

Diffusion index (IPCA) {.no-title}

ipca_diffusion %>%
  hchart(
    "area", hcaes(x = date, y = value, group = variable),
    color = colors[1], fillOpacity = 0.1) %>%
  hc_plot_ft(
    title    = "Diffusion index - IPCA",
    subtitle = "",
    source   = "BCB"
    )

Column {data-width=550}

Inflation trend {.no-title}

inflation_trend

Inflation by metropolitan region {.no-title}

ipca_region %>%
  hchart("column", hcaes(x = date, y = value, group = region), color = colors) %>%
  hc_plot_ft(
    title    = "Inflation by metropolitan region - IPCA",
    subtitle = "Monthly percentage change",
    source   = "IBGE",
    navigator = FALSE
    ) %>%
  hc_rangeSelector(selected = 0)

Column {data-width=450 .tabset}

CPI components

ipca_groups %>%
  gt(rowname_col = "Group") %>%
  tab_source_note(footnote_ipca_groups) %>% 
  tab_source_note("Source: IPCA/IBGE") %>%
  tab_footnote(
    footnote = "Month over Month: monthly percentage change",
    locations = cells_column_labels(columns = vars(`MoM`))
    ) %>% 
  tab_footnote(
    footnote = "Year to Date: percentage change accumulated in the year",
    locations = cells_column_labels(columns = vars(`YTD`))
    ) %>% 
  data_color(
    columns = 2:3,
    colors = scales::col_numeric(
      colorspace::diverge_hcl(n = 20, palette = "Blue-Red 3"),
      reverse = TRUE,
      domain = c(-max_abs(ipca_groups[2:3]), max_abs(ipca_groups[2:3]))
      )
    ) %>%
  fmt_percent(columns = 2:3, scale_values = FALSE, decimals = 1) %>%
  cols_width(2:3 ~ px(130)) %>%
  cols_width(1 ~ px(180)) %>%
  tab_options(
    column_labels.font.weight = "bold",
    stub.font.weight          = "bold",
    footnotes.padding         = 3,
    data_row.padding          = 6
    )

CPI cores

ipca_cores %>%
  hchart("line", hcaes(x = date, y = value, group = variable), color = colors[1:5]) %>%
  hc_plot_ft(
    title    = "CPI cores (IPCA)",
    subtitle = "Monthly percentage change",
    source   = "BCB"
    )

IGP trend

igp %>%
  hchart("line", hcaes(x = date, y = value, group = variable), color = colors[1:3]) %>%
  hc_plot_ft(
    title    = "General Price Index (IGP)",
    subtitle = "Monthly percentage change",
    source   = "FGV"
    )

Labor market {data-navmenu="Sections" data-icon="fa-users"}

Column {data-width=375}

# Employed (r big_numbers$date - IBGE)

big_numbers %>% 
  pull(employed) %>% 
  valueBox(
    value = .,
    icon = "fa-users",
    color = "#282f6b"
    )

# Unemployed (r big_numbers$date - IBGE)

big_numbers %>% 
  pull(unemployed) %>% 
  valueBox(
    value = .,
    icon = "fa-user-times",
    color = "#b22200"
    )

Employment by category {.no-title}

highchart() %>%
  hc_chart(type = "item") %>% 
  hc_title(text = "Employment by category") %>%
  hc_subtitle(
    text = paste0("In millions of employees, updated until ", employment_category$date[1])
    ) %>%
  hc_credits(enabled = TRUE, text = "Source: IBGE", style = list(fontSize = "12px")) %>%
  hc_legend(labelFormat = '{name} <span style="opacity: 0.4">{y}</span>') %>%
  hc_series(
    list(
      name = "Employees",
      keys = c("name", "y", "color"),
      data = {
        employment_category %>%
          select(-date) %>%
          mutate(color = colors) %>%
          unname() %>%
          transpose(.names = NULL)
        },
      dataLabels = list(
        enabled = TRUE,
        format = "{point.name} million"
      ),
      center = c("50%", "88%"),
      size = "50%"
    )
  )

Column {data-width=500}

Unemployment rate {.no-title}

unemployment_trend

Unemployment rate by gender and color {.no-title}

unemployment_gender_color %>%
  hchart("column", hcaes(x = color, y = unemployment_rate, group = gender), color = colors[1:2]) %>%
  hc_plot_ft(
    title     = "Unemployment rate by gender and color",
    subtitle  = paste0(
      "Quarterly data, updated until ", unemployment_gender_color$date[1], " (PNADC-T)"
      ),
    source    = "IBGE",
    range     = FALSE,
    navigator = FALSE
    )

Column {data-width=500 .tabset}

Unemployment by states

unemployment_map

Occupation

occupation_level %>%
  hchart(
    "line", hcaes(x = date, y = value, group = gender), color = colors[1:3]) %>%
  hc_plot_ft(
    title     = "Labor force occupation level",
    subtitle  = "Quarterly data (PNADC-T)",
    source    = "IBGE",
    range     = FALSE,
    navigator = FALSE
    )

Participation

participation_rate %>%
  hchart(
    "line", hcaes(x = date, y = value, group = gender), color = colors[1:3]) %>%
  hc_plot_ft(
    title     = "Labor force participation rate",
    subtitle  = "Quarterly data (PNADC-T)",
    source    = "IBGE",
    range     = FALSE,
    navigator = FALSE
    )

Income

income %>%
  hchart(
    "line", hcaes(x = date, y = value, group = age), color = colors) %>%
  hc_plot_ft(
    title     = "Average real income from work, by age group",
    subtitle  = "Quarterly data (PNADC-T)",
    source    = "IBGE",
    range     = FALSE,
    navigator = FALSE
    ) %>%
  hc_yAxis(labels = list(format = "R$ {value:,.0f}"))

Gini

gini %>%
  hchart(
    "bar", hcaes(x = states, y = value), color = colors[1], name = "Gini") %>%
  hc_plot_ft(
    title     = "Gini index by states",
    subtitle  = paste0(
      "Quarterly data, updated until ", gini$date[1], " (PNADC-T)"
      ),
    source    = "IBGE",
    range     = FALSE,
    navigator = FALSE
    ) %>%
  hc_yAxis(labels = list(format = "{value}"))

Fiscal policy {data-navmenu="Sections" data-icon="fa-gavel"}

Column {data-width=450}

Central Government Primary Deficit {.no-title}

primary_deficit_trend

Central Government Net Revenue and Total Expenditure {.no-title}

revenue_spending %>%
  hchart("line", hcaes(x = date, y = value, group = variable), color = colors[1:2]) %>%
  hc_plot_ft(
    title    = "Central Government Net Revenue and Total Expenditure",
    subtitle = "Accumulated in 12 months and deflated by the IPCA index (% GDP)",
    source   = "STN and IBGE",
    navigator = FALSE
    )

Column {data-width=450}

Detailed accounts of Central Government Income and Expenditure {.no-title}

highchart() %>%
  hc_add_series(
    type = "treemap",
    layoutAlgorithm = "squarified",
    allowDrillToNode = TRUE,
    levels = list(
      list(level = 1, 
           dataLabels = list(enabled = TRUE, style = list(fontSize = "20px")), 
             borderWidth = 3
           ),
      list(level = 2, dataLabels = list(enabled = TRUE), borderWidth = 2),
      list(level = 3, dataLabels = list(enabled = TRUE), borderWidth = 1)
    ),
    tooltip = list(valueDecimals = 2, valuePrefix = "R$ "),
    data = list(
      data = list(
        # LEVEL I
        list(
          id = unique(revenue_spending_detail$group_1)[1] %>%
            stringr::str_replace_all("[[:blank:]]", "_") %>% stringr::str_to_lower(),
          name = unique(revenue_spending_detail$group_1)[1],
          color = unname(colors[1])
          ),
        list(
          id = unique(revenue_spending_detail$group_1)[2] %>%
            stringr::str_replace_all("[[:blank:]]", "_") %>% stringr::str_to_lower(),
          name = unique(revenue_spending_detail$group_1)[2],
          color = unname(colors[2])
          ),
        list(
          id = unique(revenue_spending_detail$group_1)[3] %>%
            stringr::str_replace_all("[[:blank:]]", "_") %>% stringr::str_to_lower(),
          name = unique(revenue_spending_detail$group_1)[3],
          color = unname(colors[3])
          )
        )
      ) %>%
      rlist::list.append(
        # LEVEL II
        {revenue_spending_detail %>%
            select("name" = group_2, "parent" = group_1, value) %>%
            mutate(parent = stringr::str_replace_all(parent, "[[:blank:]]", "_") %>%
                     stringr::str_to_lower()) %>%
            group_by(name, parent) %>%
            summarise(value = sum(value), .groups = "drop") %>%
            mutate(id = stringr::str_replace_all(name, "[[:blank:]]", "_") %>%
                     stringr::str_to_lower()) %>%
            transpose()
        },
        # LEVEL III
        {revenue_spending_detail %>%
            select("name" = group_3, "parent" = group_2, value) %>%
            mutate(parent = stringr::str_replace_all(parent, "[[:blank:]]", "_") %>%
                     stringr::str_to_lower()) %>%
            transpose()
        }
      ) %>%
      flatten()
    ) %>% 
   hc_plot_ft(
    title     = "Detailed Central Government Accounts",
    subtitle  = sprintf(
      "Accumulated in 12 months and deflated by the IPCA index, R$ million (%s)",
      revenue_spending_detail$date[1]
      ),
    source    = "STN and IBGE",
    range     = FALSE,
    navigator = FALSE
    )

Single Account balance {.no-title}

single_account %>% 
  hchart(
    "area", hcaes(x = date, y = value, group = variable),
    color = colors[4], fillOpacity = 0.1) %>%
  hc_plot_ft(
    title    = "Single Account balance",
    subtitle = "Deflated by the IPCA index, R$ million",
    source    = "BCB and IBGE",
    navigator = FALSE
    ) %>%
  hc_yAxis(labels = list(format = "R$ {value:,.0f}"))

Column {data-width=450 .tabset}

Debt Stock

debt_stock %>% 
  hchart(
    "area", hcaes(x = date, y = value, group = variable),
    color = colors[2], fillOpacity = 0.1) %>%
  hc_plot_ft(
    title    = "Federal Public Debt Stock",
    subtitle = "Deflated by the IPCA index, R$ billion",
    source   = "BCB and IBGE"
    ) %>%
  hc_yAxis(labels = list(format = "R$ {value:,.0f}"))

Government Securities Portfolio

gov_portfolio %>% 
  hchart(
    "pie", hcaes(y = value, name = variable, color = colors_extra[1:8]),
    name = "Government Securities") %>%
  hc_plot_ft(
    title     = "Details of the National Treasury Securities portfolio",
    subtitle  = sprintf("R$ billion (%s)", gov_portfolio$date_my[1]),
    source    = "BCB",
    range     = FALSE,
    navigator = FALSE
    ) %>%
  hc_tooltip(
    pointFormat =  '<b>R$ {point.value:,.0f}</b>'
  ) %>% 
  hc_plotOptions(
    pie = list(
      allowPointSelect = TRUE,
      cursor = 'pointer'
    )
  )

Rating

htmltools::div(
  style = "height:600px; overflow-y: scroll",
  rating %>%
  gt() %>%
  tab_header(title = html(
    "<span style='color:black'><b>Debt Risk Rating History</b></span>")
    ) %>%
  tab_source_note(
    html("<span style='color:black'>Source: STN</span>")
    ) %>%
  cols_hide(columns = vars("Action")) %>%
  tab_style(
    style     = list(cell_text(color = "black")),
    locations = cells_body(columns = vars(
      `Last update`, `Agency`, `Foreign currency`, `Local currency`))
    ) %>%
  tab_style(
    style     = list(cell_fill(color = "#cae9ff")),
    locations = cells_body(columns = vars(
      `Last update`, `Agency`, `Foreign currency`, `Local currency`))
    ) %>%
  tab_style(
    style     = list(cell_text(weight = "bold")),
    locations = cells_body(columns = vars(`Agency`))
    ) %>%
  tab_style(
    style     = list(cell_text(color = "black")),
    locations = cells_column_labels(vars(
      `Last update`, `Agency`, `Foreign currency`, `Local currency`))
    ) %>%
  tab_options(
    column_labels.font.weight         = "bold",
    stub.font.weight                  = "bold",
    footnotes.padding                 = 3,
    data_row.padding                  = 6,
    heading.background.color          = "#cae9ff",
    table.font.color                  = "black",
    table.border.top.color            = "black",
    column_labels.border.bottom.color = "black",
    column_labels.border.bottom.width = px(3),
    table.background.color            = "#cae9ff",
    table_body.hlines.color           = "black",
    table.border.bottom.color         = "black",
    heading.border.bottom.color       = "black",
    footnotes.border.bottom.color     = "black",
    table_body.border.bottom.color    = "black",
    container.overflow.y              = TRUE
    )
  )

Monetary policy {data-navmenu="Sections" data-icon="fa-percentage"}

Column {data-width=325}

SELIC Target rate in r format(selic$date, "%B, %Y") (COPOM/BCB)

big_number_selic

Inflation target for r inflation_target$date (CMN)

inflation_target %>% 
  mutate(value = paste0(value, "%")) %>%
  pull(value) %>%
  valueBox(
    value = .,
    icon  = "fa-bullseye",
    color = "#5f487c"
    )

Inflation expectations {.no-title}

inflation_expec %>%
  hchart(
    "area", hcaes(x = date, y = value, group = variable),
    color = colors[1], fillOpacity = 0.1) %>%
  hc_plot_ft(
    title     = "Market inflation expectations for the next 12 months",
    subtitle  = "For the IPCA index, end of the month",
    source    = "BCB"
    ) %>%
  hc_tooltip(xDateFormat = "%B %Y")

Column {data-width=500}

Short-term interest rates {.no-title}

interest_rate %>%
  hchart("line", hcaes(x = date, y = value, group = variable), color = colors[1:3]) %>%
  hc_plot_ft(
    title     = "Short-term interest rates",
    subtitle  = "Nominal rates, end of the month, in % p.a.",
    source    = "BCB",
    navigator = FALSE
    )

Real interest rates {.no-title}

real_interest_rate_trend

Column {data-width=500 .tabset}

Exchange rate

exchange_rate

Interest rate expectations

selic_expec %>%
  hchart(
    "area", hcaes(x = date, y = value, group = variable),
    color = colors[1], fillOpacity = 0.1
    ) %>%
  hc_plot_ft(
    title     = glue::glue("Interest rate expectations for {selic_expec$reference_date[1]}"),
    subtitle  = "SELIC target rate expectations of the last business day of the month, for the end of the year",
    source    = "BCB"
    ) %>%
  hc_tooltip(xDateFormat = "%B %Y")

Yield curve

ettj %>%
  hchart(
    "area", hcaes(x = date_ref, y = value, group = variable),
    color = colors[1], fillOpacity = 0.1
    ) %>%
  hc_plot_ft(
    title     = "Yield curve (ETTJ IPCA)",
    subtitle  = glue::glue("Term Structure of the Interest Rate, consulted on {ettj$date_query[1]} (% p.a./252)"),
    source    = "Anbima",
    range = FALSE
    ) %>% 
  hc_tooltip(xDateFormat = "%B %d, %Y")

Ibovespa

ibovespa_candle

EMBI+

embi %>%
  hchart(
    "area", hcaes(x = date, y = value, group = variable),
    color = colors[1], fillOpacity = 0.1
    ) %>%
  hc_plot_ft(
    title     = "EMBI+ Risk-Brasil",
    subtitle  = "Daily index (base point)",
    source    = "JP Morgan"
    ) %>%
  hc_yAxis(labels = list(format = "{value:,.0f}")) %>%
  hc_tooltip(xDateFormat = "%B %d, %Y")

About {data-icon="fa-file-alt"}

About {.no-title}

This dashboard aims to facilitate the monitoring of macroeconomic data on the Brazilian economy, including the main indicators of:

The indicators are updated daily and come from public data sources. I hope this tool can be useful for you!

If you find any errors or have any suggestions, feel free to contact me: fernando@fortietwo.com


Last update: r format(Sys.Date(), "%B %d, %Y").
GitHub repo: https://github.com/schoulten/macroview


Author: Fernando da Silva
I am an economist passionate about macroeconomics with 3 years of experience in analyzing the economic scenario. I do data analysis with time series and microdata using the power of R for automation. My work helps people to understand the economic scenario and make decisions.

Website: https://fortietwo.com/
GitHub: https://www.github.com/schoulten
LinkedIn: https://www.linkedin.com/in/schoulten/



schoulten/macroview documentation built on Jan. 4, 2023, 3:54 a.m.