Atividade 8 sobre análise de semtimentos da ata do Copom de Julho de 2024

Instalando /carregando pacotes

if(!require("pacman")) install.packages("pacman")
## Carregando pacotes exigidos: pacman
## Carregando pacotes exigidos: pacman
pacman::p_load(
  "tidytext",
  "pdftools",
  "stopwords",
  "textdata",
  "dplyr",
  "tidyr",
  "lubridate",
  "magrittr",
  "knitr",
  "ggplot2",
  "ggthemes",
  "jsonlite",
  "purrr",
  "stringr",
  "scales",
  "forcats"
)

criando um objeto para armazenar o link para o arquivo (www) usamos a função pdf_text do pacote pdftools para ler cada página do arquivo PDF transformar os dados em um vetor de caracteres de tamanho igual ao número de páginas.

# URL da ata do COPOM de julho de 2024de 2021
www <- "https://www.bcb.gov.br/content/copom/copomminutes/MINUTES%20264.pdf"

# Ler arquivo PDF convertendo para caracter
raw_copom_last <- pdftools::pdf_text(www)

Tratamento de dados para remoção de caracteres e texto nõa utilizado na análise

copom_last_clean <- dplyr::tibble(
  text = unlist(strsplit(raw_copom_last, "\r"))
) %>% 
  dplyr::mutate(
    meeting = "May 2021", 
    page = dplyr::row_number(),
    text = gsub("\n", "", text)
  )

Text mining - Criar tokens

copom_last <- copom_last_clean %>% 
              tidytext::unnest_tokens(word, text)

# Contar palavras
copom_last %>%
             dplyr::count(word, sort = TRUE) %>% 
             dplyr::slice_head(n = 6) %>% 
            knitr::kable()
word n
the 273
of 135
and 90
in 61
inflation 51
to 49

Remover “stop words” usando como base o objeto stop_words proveniente do pacote tidytext e, antes, removemos também números que foram apontados como “palavras”:

copom_last_sw <- copom_last %>%
  
  # Remover palavras comuns (stop words)
  dplyr::anti_join(stop_words)%>%
  
  # Remover números
  dplyr::mutate(word = gsub("[^A-Za-z ]", "", word)) %>%
  # Contar palavras
  dplyr::count(word, sort = TRUE) %>% 
  dplyr::filter(word != "")
## Joining with `by = join_by(word)`
## Joining with `by = join_by(word)`
copom_last_sw %>% 
  dplyr::slice_head(n = 6) %>% 
  knitr::kable()
word n
inflation 51
monetary 30
committee 29
policy 28
rate 24
scenario 23

Classificação bing: palavras rotuladas em positivo e negativo. Obter análise de sentimento das palavras com base em uma biblioteca

copom_last_sw %>%
  dplyr::inner_join(tidytext::get_sentiments("bing")) %>% 
  dplyr::slice_head(n = 10) %>% 
  knitr::kable()
## Joining with `by = join_by(word)`
word n sentiment
challenging 8 negative
risks 8 negative
commitment 5 positive
inflationary 5 negative
diligent 4 positive
easing 4 positive
slowed 4 negative
adverse 3 negative
risk 3 negative
sustainability 3 positive
## Joining with `by = join_by(word)`

Análise de sentimento final da ata de Julho de 2024

copom_sentiment <- copom_last %>%
  dplyr::inner_join(tidytext::get_sentiments("bing")) %>%
  dplyr::count(meeting, page, sentiment) %>%
  tidyr::pivot_wider(
          id_cols = c(meeting, page),
          names_from = sentiment, 
          values_from = n,
          values_fill = 0
                     ) %>%
  dplyr::mutate(sentiment = positive - negative)
## Joining with `by = join_by(word)`
# Gerar gráfico
copom_sentiment %>% 
  ggplot2::ggplot(ggplot2::aes(page, sentiment, fill = sentiment > 0)) +
  ggplot2::geom_col(show.legend = FALSE) +
  ggplot2::scale_fill_manual(values = c("#B22222", "#008000")) +
  ggplot2::labs(
              x = "Página da ata",
              y = "Sentimento",
              title = "Análise de sentimento da Ata do COPOM - Julho de 2024",
              subtitle = "Bing lexicon",
              caption = paste0("Elaboração: analisemacro.com.br\nDados: ", www)
               )