Contexto

Pessoal, estou trabalhando com a Profa Graziella Magalhães (UFJF) e com o Lucas Adriano Silva (doutorando, UFV) em um projeto sobre mineração.

Uma das minhas tarefas para esta semana em relação ao projeto é coletar os preços de 4 minérios e olhar como estes preços se comportam. Os minérios:

Esses são exatamente os 4 minérios mais importantes (em valor) no Brasil. E, por isso, vou olhar como andam os preços mundiais desses 4 minérios.

A gente vai seguir exatamente o roteiro de sempre:

  1. Carregar os pacotes
  2. Baixar os dados
  3. Olhar os dados e fazer os gráficos

Pacotes

O pacote que faz o download automático dos dados do Fundo Monetário Internacional (FMI, em inglês a sigla é IMF) é o imf.data, para instalá-lo a gente usa o imf.data.

Os materiais para saber como usar o ifm.data estão aqui e aqui.

library(loadinstall)

packages <- c("ggplot2", "ggrepel", "ggthemes", 
  "tidyr", "tidyverse", "imf.data", "stringr", "scales")

lapply(packages, dynamic_require)
## [[1]]
## [1] "ggplot2"     "loadinstall" "stats"       "graphics"    "grDevices"  
## [6] "utils"       "datasets"    "methods"     "base"       
## 
## [[2]]
##  [1] "ggrepel"     "ggplot2"     "loadinstall" "stats"       "graphics"   
##  [6] "grDevices"   "utils"       "datasets"    "methods"     "base"       
## 
## [[3]]
##  [1] "ggthemes"    "ggrepel"     "ggplot2"     "loadinstall" "stats"      
##  [6] "graphics"    "grDevices"   "utils"       "datasets"    "methods"    
## [11] "base"       
## 
## [[4]]
##  [1] "tidyr"       "ggthemes"    "ggrepel"     "ggplot2"     "loadinstall"
##  [6] "stats"       "graphics"    "grDevices"   "utils"       "datasets"   
## [11] "methods"     "base"       
## 
## [[5]]
##  [1] "lubridate"   "forcats"     "stringr"     "dplyr"       "purrr"      
##  [6] "readr"       "tibble"      "tidyverse"   "tidyr"       "ggthemes"   
## [11] "ggrepel"     "ggplot2"     "loadinstall" "stats"       "graphics"   
## [16] "grDevices"   "utils"       "datasets"    "methods"     "base"       
## 
## [[6]]
##  [1] "imf.data"    "lubridate"   "forcats"     "stringr"     "dplyr"      
##  [6] "purrr"       "readr"       "tibble"      "tidyverse"   "tidyr"      
## [11] "ggthemes"    "ggrepel"     "ggplot2"     "loadinstall" "stats"      
## [16] "graphics"    "grDevices"   "utils"       "datasets"    "methods"    
## [21] "base"       
## 
## [[7]]
##  [1] "imf.data"    "lubridate"   "forcats"     "stringr"     "dplyr"      
##  [6] "purrr"       "readr"       "tibble"      "tidyverse"   "tidyr"      
## [11] "ggthemes"    "ggrepel"     "ggplot2"     "loadinstall" "stats"      
## [16] "graphics"    "grDevices"   "utils"       "datasets"    "methods"    
## [21] "base"       
## 
## [[8]]
##  [1] "scales"      "imf.data"    "lubridate"   "forcats"     "stringr"    
##  [6] "dplyr"       "purrr"       "readr"       "tibble"      "tidyverse"  
## [11] "tidyr"       "ggthemes"    "ggrepel"     "ggplot2"     "loadinstall"
## [16] "stats"       "graphics"    "grDevices"   "utils"       "datasets"   
## [21] "methods"     "base"

Dados

O “list_datasets()” vai listar todas as bases de dados existentes. O ponto é que são muitas! Para baixar exatamente a base de dados desejada, você tem que saber qual o nome dela no site do Fundo Monetário Internacional.

bases<-list_datasets()
#olhei e sei que preciso da base PCPS
pcps <- load_datasets("PCPS")

## isso é para saber para quais áreas a base está disponível
pcps$dimensions$ref_area
##   Value                     Description
## 1   W00 All Countries, excluding the IO
#descobri que o meu código é W00

##isso é para saber qual o meu código
pcps$dimensions$commodity
##              Value
## 1            PRAWM
## 2            PAGRI
## 3          PALLFNF
## 4         PEXGMETA
## 5         PALLMETA
## 6            PALUM
## 7         POILAPSP
## 8          PBANSOP
## 9            PBARL
## 10           PBEEF
## 11           PBEVE
## 12         POILBRE
## 13           PCERE
## 14          PCHROM
## 15           PCOAL
## 16         PCOALAU
## 17         PCOALSA
## 18           PCOBA
## 19           PCOCO
## 20           PCOIL
## 21           PCOFF
## 22        PCOFFOTM
## 23        PCOFFROB
## 24         PEXGALL
## 25           PCOPP
## 26         PMAIZMT
## 27        PCOTTIND
## 28           PMILK
## 29            PDAP
## 30         POILDUB
## 31            PNRG
## 32           PENTM
## 33           PFERT
## 34           PSALM
## 35        PFSHMEAL
## 36          PFANDB
## 37           PFOOD
## 38           PGASO
## 39           PGOLD
## 40          PGNUTS
## 41          PLOGSK
## 42         PSAWMAL
## 43           PHARD
## 44        PHEATOIL
## 45           PHIDE
## 46           PINDU
## 47         PIORECR
## 48           PLAMB
## 49           PLEAD
## 50          PCHANA
## 51           PLITH
## 52         PNGASJP
## 53           LMICS
## 54        PMANGELE
## 55           PMEAT
## 56           PMETA
## 57         PLMMODY
## 58           PNGAS
## 59         PNGASEU
## 60         PNGASUS
## 61           PNICK
## 62          PAPPLE
## 63          PNFUEL
## 64           POATS
## 65         POLVOIL
## 66          PORANG
## 67          PPALLA
## 68           PPOIL
## 69           PPLAT
## 70         PPOTASH
## 71          PPOULT
## 72          PPMETA
## 73        PPROPANE
## 74           PROIL
## 75         PREODOM
## 76        PRICENPQ
## 77           PRUBB
## 78           PSEAF
## 79           PSHRI
## 80        PSILLUMP
## 81         PSILVER
## 82         PLOGORE
## 83         PSAWORE
## 84           PSOFT
## 85           PSORG
## 86           PSMEA
## 87           PSOYB
## 88           PSOIL
## 89           PSUGA
## 90        PSUGAISA
## 91        PSUGAUSA
## 92           PSUNO
## 93           PPORK
## 94          PTEASL
## 95            PTEA
## 96       PTEAINDIA
## 97         PTEAMOM
## 98           PTIMB
## 99            PTIN
## 100          PURAN
## 101          PUREA
## 102       PVANPENT
## 103          PVOIL
## 104        PTOMATO
## 105        PWHEAMT
## 106          PWOOL
## 107         PWOOLC
## 108         PWOOLF
## 109        POILWTI
## 110          PZINC
## 111 All_Indicators
##                                                                      Description
## 1                             Primary Commodity Prices, Agr. Raw Material Index 
## 2                                          Primary Commodity Prices, Agriculture
## 3                                           Primary Commodity Prices, All index 
## 4                             Primary Commodity Prices, All Metals EX GOLD Index
## 5                                     Primary Commodity Prices, All Metals Index
## 6                                             Primary Commodity Prices, Aluminum
## 7                                Primary Commodity Prices, APSP crude oil($/bbl)
## 8                                             Primary Commodity Prices, Bananas 
## 9                                               Primary Commodity Prices, Barley
## 10                                               Primary Commodity Prices, Beef 
## 11                                    Primary Commodity Prices, Beverages index 
## 12                                        Primary Commodity Prices, Brent Crude 
## 13                                       Primary Commodity Prices, Cereal  index
## 14                                            Primary Commodity Prices, Chromium
## 15                                         Primary Commodity Prices, Coal index 
## 16                                     Primary Commodity Prices, Coal, Australia
## 17                                 Primary Commodity Prices, Coal, South Africa 
## 18                                             Primary Commodity Prices, Cobalt 
## 19                                               Primary Commodity Prices, Cocoa
## 20                                        Primary Commodity Prices, Coconut Oil 
## 21                                       Primary Commodity Prices, Coffee index 
## 22                         Primary Commodity Prices, Coffee, Other Mild Arabica 
## 23                                   Primary Commodity Prices, Coffee, Robustas 
## 24          Primary Commodity Prices, Commodities for Index: All, excluding Gold
## 25                                             Primary Commodity Prices, Copper 
## 26                                               Primary Commodity Prices, Corn 
## 27                                             Primary Commodity Prices, Cotton 
## 28                                Primary Commodity Prices, Dairy Products, Milk
## 29                                Primary Commodity Prices, Diammonium phosphate
## 30                                        Primary Commodity Prices, Dubai Crude 
## 31                                       Primary Commodity Prices, Energy index 
## 32                       Primary Commodity Prices, Energy Transition Metal Index
## 33                                          Primary Commodity Prices, Fertilizer
## 34                                               Primary Commodity Prices, Fish 
## 35                                          Primary Commodity Prices, Fish Meal 
## 36                             Primary Commodity Prices, Food and beverage index
## 37                                         Primary Commodity Prices, Food index 
## 38                                           Primary Commodity Prices, Gasoline 
## 39                                               Primary Commodity Prices, Gold 
## 40                                         Primary Commodity Prices, Groundnuts 
## 41                       Primary Commodity Prices, Hard Logs, Import Price Japan
## 42                    Primary Commodity Prices, Hard Sawnwood, Dark Red Meranti 
## 43                                     Primary Commodity Prices, Hardwood index 
## 44                                        Primary Commodity Prices, Heating Oil 
## 45                                              Primary Commodity Prices, Hides 
## 46                         Primary Commodity Prices, Industrial Materials index 
## 47                                            Primary Commodity Prices, Iron Ore
## 48                                               Primary Commodity Prices, Lamb 
## 49                                               Primary Commodity Prices, Lead 
## 50                                   Primary Commodity Prices, Legumes, Chickpea
## 51                                             Primary Commodity Prices, Lithium
## 52                                          Primary Commodity Prices, LNG, Asia 
## 53  Primary Commodity Prices, Low and Middle Income Commodity Index (World Bank)
## 54                                           Primary Commodity Prices, Manganese
## 55                                         Primary Commodity Prices, Meat Index 
## 56                                        Primary Commodity Prices, Metal index 
## 57                                          Primary Commodity Prices, Molybdenum
## 58                                  Primary Commodity Prices, Natural gas index 
## 59                                    Primary Commodity Prices, Natural gas, EU 
## 60                       Primary Commodity Prices, Natural Gas, US Henry Hub Gas
## 61                                             Primary Commodity Prices, Nickel 
## 62                             Primary Commodity Prices, Non-Citrus Fruit, Apple
## 63                                     Primary Commodity Prices, Non-Fuel index 
## 64                                                Primary Commodity Prices, Oats
## 65                                          Primary Commodity Prices, Olive Oil 
## 66                                             Primary Commodity Prices, Orange 
## 67                                           Primary Commodity Prices, Palladium
## 68                                           Primary Commodity Prices, Palm Oil 
## 69                                            Primary Commodity Prices, Platinum
## 70                                Primary Commodity Prices, Potassium Fertilizer
## 71                                            Primary Commodity Prices, Poultry 
## 72                         Primary Commodity Prices, Precious Metals Price Index
## 73                                             Primary Commodity Prices, Propane
## 74                                       Primary Commodity Prices, Rapeseed Oil 
## 75                                 Primary Commodity Prices, Rare Earth Elements
## 76                                     Primary Commodity Prices, Rice, Thailand 
## 77                                             Primary Commodity Prices, Rubber 
## 78                                      Primary Commodity Prices, Seafood index 
## 79                                             Primary Commodity Prices, Shrimp 
## 80                                             Primary Commodity Prices, Silicon
## 81                                              Primary Commodity Prices, Silver
## 82                                          Primary Commodity Prices, Soft Logs 
## 83               Primary Commodity Prices, Soft Sawnwood, Average of Softwoods, 
## 84                                     Primary Commodity Prices, Softwood index 
## 85                                            Primary Commodity Prices, Sorghum 
## 86                                       Primary Commodity Prices, Soybean Meal 
## 87                                           Primary Commodity Prices, Soybeans 
## 88                                       Primary Commodity Prices, Soybeans Oil 
## 89                                        Primary Commodity Prices, Sugar index 
## 90                               Primary Commodity Prices, Sugar, No. 11, World 
## 91                                  Primary Commodity Prices, Sugar, No. 16, US 
## 92                                      Primary Commodity Prices, Sunflower Oil 
## 93                                              Primary Commodity Prices, Swine 
## 94                                       Primary Commodity Prices, Tea, Colombo 
## 95                                        Primary Commodity Prices, Tea, Kenyan 
## 96                                       Primary Commodity Prices, Tea, Kolkata 
## 97                                       Primary Commodity Prices, Tea, Mombasa 
## 98                                       Primary Commodity Prices, Timber index 
## 99                                                Primary Commodity Prices, Tin 
## 100                                           Primary Commodity Prices, Uranium 
## 101                                               Primary Commodity Prices, Urea
## 102                                           Primary Commodity Prices, Vanadium
## 103                               Primary Commodity Prices, Vegetable oil index 
## 104                                 Primary Commodity Prices, Vegetables, Tomato
## 105                                             Primary Commodity Prices, Wheat 
## 106                                        Primary Commodity Prices, Wool index 
## 107                                      Primary Commodity Prices, Wool, Coarse 
## 108                                        Primary Commodity Prices, Wool, Fine 
## 109                                         Primary Commodity Prices, WTI Crude 
## 110                                              Primary Commodity Prices, Zinc 
## 111                                                               All Indicators
## como tem muito código, vou gerar um objeto com os códigos 
#codigos<-pcps$dimensions$commodity

#PGOLD
#PALUM
#PIORECR
#PCOPP

b1<-pcps$get_series(freq="M", ref_area = "W00", commodity =  c("PGOLD","PCOPP", "PIORECR", "PALUM"), unit_measure = "IX")


## Preciso mudar os nomes 
names(b1) <- c("time", "ouro", "bauxita", "cobre", "ferro")

#Preciso colocar a base no formato long
b2 <- tidyr::pivot_longer(b1, cols = -time, names_to = "variavel", values_to = "valor")

b3 <- b2 %>%
  filter(time>"1999-12")

Descobrir os códigos só é um pouco chato, mas é pouco. E, depois que você pegar a manha, vai que vai.
Outra coisa, pense que você só vai precisar pegar estes códigos uma vez, depois é só ir mudando para as bases desejadas.

Gráficos e alguns comentários

Agora sim consigo fazer os gráficos que preciso.

#transformando time em data
b3$time <- as.Date(paste0(b3$time, "-01"), format = "%Y-%m-%d")

b3$valor<-as.numeric(b3$valor)

ggplot(b3, aes(x = time, y = valor, color = as.factor(variavel))) + geom_line() + geom_point() +  labs(x = "", y = "Indice", color = "") +  theme_minimal()  

Uma versão mais bonita do gráfico.

ggplot(b3, aes(x = time, y = valor, color = variavel)) +
  geom_line(size = 1.05) +
  geom_point(size = 1.2) +
  labs(x = "", y = "Index", color = "") +
  theme_minimal() +
  scale_x_date(labels = date_format("%Y"), breaks = date_breaks("2 years")) +
  theme(axis.text.x = element_text(angle = 0, hjust = 1)) +
  scale_color_manual(
    values = c(
      "ouro" = "gold",
      "cobre" = "#b87333",
      "bauxita" = "gray80",
      "ferro" = "gray35"
    ),
    labels = c(
      "ouro" = "Gold",
      "cobre" = "Copper",
      "bauxita" = "Aluminum",
      "ferro" = "Iron"
    )
  )
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

A gente tem um grande aumento na CFEM, “royalties da mineração” em 2017, e precisávamos olhar se o aumento não foi guiado por preços. Não parece, 2016-2018, na verdade, é o vale dos preços. Mas se a gente olhar só para o ferro (o minério mais importante nas exportações brasileiras), parece que há sim um aumento bem razoável pós-2017. O índice sai de 100 para 180 entre 2017 e 2019, e em 2021 chega a valores maiores do que 300.

Outros preços com a mesma base

Eu não achei a base “amigável”, a forma de procurar os preços é bem enjoada. Daí, fiquei pensando se não é só falta de prática.

Vou olhar os dados dos preços de:

  • milho, açúcar, soja

  • café, trigo, algodão

  • petróleo

Essa parte é só para vocês saberem que basta saber o código de uma commodity que é possível baixar os preços.

#petroleo POILAPSP
#milho PMAIZMT
#cafe PCOFF
#algodao PCOTTIND
#soja PSOYB
#trigo  PWHEAMT
# PSUGA
#c("POILAPSP", "PMAIZMT", "PCOFF", "PCOTTIND", "PSOYB", "PWHEAMT", "PSUGA")

pcps <- load_datasets("PCPS")
lista<-pcps$dimensions$commodity

d1<-pcps$get_series(freq="M", ref_area = "W00", commodity =  c("POILAPSP", "PMAIZMT", "PCOFF", "PCOTTIND", "PSOYB", "PWHEAMT", "PSUGA"), unit_measure = "USD")

d2 <- tidyr::pivot_longer(d1, cols = -TIME_PERIOD, names_to = "variavel", values_to = "valor")

d3<-d2%>%filter(TIME_PERIOD>"1990-12")
d3$time <- as.Date(paste0(d3$TIME_PERIOD, "-01"), format = "%Y-%m-%d")

d3$valor<-as.numeric(d3$valor)

d3 <- d3 %>% filter(variavel=="M.W00.PMAIZMT.USD")

ggplot(d3, aes(x = time, y = valor, color = as.factor(variavel))) + geom_line() + geom_point() +  labs(x = "", y = "Indice", color = "") +  theme_minimal()  

SIDRA

Parece feio, mas funciona.

A primeira coisa que você precisa é ter a library do Sidra

sidrar

A segunda coisa que você precisa é saber qual a tabela quer!

Isso você vai encontrar no site do Sidra.

Essa é uma amostra (site).

O passo a passo para pegar o código da tabela a gente vai fazer na monitoria.

library(sidrar)
inf =
'/t/1737/n1/all/v/2266/p/all/d/v2266%2013' %>%
get_sidra(api=.) 
## All others arguments are desconsidered when 'api' is informed
#https://apisidra.ibge.gov.br/values/t/1737/n1/all/v/63/p/all/d/v63%202
inf2 =
'/t/1737/n1/all/v/63/p/all/d/v63%202' %>%
get_sidra(api=.) 
## All others arguments are desconsidered when 'api' is informed