wilsonfreitas / rbcb Goto Github PK
View Code? Open in Web Editor NEWR interface to Brazilian Central Bank web services
Home Page: https://wilsonfreitas.github.io/rbcb/
License: Other
R interface to Brazilian Central Bank web services
Home Page: https://wilsonfreitas.github.io/rbcb/
License: Other
https://olinda.bcb.gov.br/olinda/servico/Expectativas/versao/v1/aplicacao#!/
Estatísticas dos Sistemas de Liquidação de Títulos, Derivativos e Câmbio
https://olinda.bcb.gov.br/olinda/servico/ResumoCamaras_pt/versao/v1/documentacao
Expectativas de mercado para os principais indicadores macroeconômicos
https://olinda.bcb.gov.br/olinda/servico/Expectativas/versao/v1/documentacao
Taxas de Cambio DEPIN
https://dadosabertos.bcb.gov.br/organization/depin
Negociação de Títulos Federais no Mercado Secundário
https://dadosabertos.bcb.gov.br/dataset/negociacao-de-titulos-federais-no-mercado-secundario
Cronograma de vencimentos de títulos
https://dadosabertos.bcb.gov.br/dataset/cronograma-de-vencimentos-de-titulos
The service accepts filters by:
Example:
https://dadosabertos.bcb.gov.br/dataset?tags=inclusao-financeira
Hi there. I'm receiving the following error when trying to get market expectations. I'm using the last version from HEAD.
> rbcb::get_monthly_market_expectations("IPCA")
Error in .get_series(url) :
BCB API Request error nπo Θ possφvel abrir a conexπo
Any ideas?
The series are identified by numbers that aren't much clear or easy to remember when being used.
The series could have an alias or an alternative name and that name could be used to fetch data.
series_alias(USDBRL = 1, IPCA = 433)
get_series("USDBRL")
get_series("IPCA")
Estou tentando baixar dados usando o get_series e recebo o seguinte erro:
Error in curl::curl_fetch_memory(url, handle = handle) :
LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to www3.bcb.gov.br:443
Já troquei de rede e tentei algumas coisas, mas continua assim. Alguma ideia do que pode ser?
The get_currency
function returns a data.frame with columns bid
and ask
.
The columns should have the name of the currency: EUR.bid
and EUR.ask
.
With this feature we could return multiple series with one call.
In order to be in conformity with other packages (quantmod, tidyquant, ...) the arguments start_date
and end_date
should be replaced with from
and to
.
The implemented version should bring a deprecated warning when the old arguments were used and suggesting that the new args should be used.
Functions to change:
The new function bcb_get
should bring these new arguments.
Aproveitando, notei que o pacote foi retirado do CRAN.
Foi decisão sua? Tens alguma perspectiva de retornar?
Sei que é chato aguentar as exigências do CRAN, mas o pacote fica mais fácil de acessar, principalmente para os alunos.
I have noticed that some indexes was changed on API, but when I try to get the monthly market expectations and use "Câmbio" (the newer version of "Taxa de câmbio") as indic value and it returns the error below:
Invalid indic argument: Câmbio
Could you help me?
OBS: When I tried to use "Taxa de câmbio" as indic it returned this warning message:
Warning messages: 1: Unknown or uninitialised column: date. 2: Unknown or uninitialised column: reference_month.
And the result dataframe is empty
travis-ci accepts cron task.
Write tests to be run with cron tasks to test for eventual BCB API changes.
Hello everyone.
I can't install the package when using the command "devtools::install_github('wilsonfreitas/rbcb')". The message error is the following:
Warning messages:
1: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\gboechat\Documents\R\R-4.0.5\library\00LOCK\rlang\libs\x64\rlang.dll to C:\Users\gboechat\Documents\R\R-4.0.5\library\rlang\libs\x64\rlang.dll: Permission denied
2: In file.copy(savedcopy, lib, recursive = TRUE) :
problem copying C:\Users\gboechat\Documents\R\R-4.0.5\library\00LOCK\ellipsis\libs\x64\ellipsis.dll to C:\Users\gboechat\Documents\R\R-4.0.5\library\ellipsis\libs\x64\ellipsis.dll: Permission denied
3: In i.p(...) :
installation of package ‘C:/Users/gboechat/AppData/Local/Temp/Rtmpg9dslQ/file48f83e48396a/rbcb_0.1.6.tar.gz’ had non-zero exit status
Am I missing any extra step prior to installing it?
Kind regards,
Olá!
Estou com um erro quando busco as séries:
rbcb::get_series(c(IPCA = 433, IGPM = 189), last = 12, as = "ts")
Error in .get_series(series_url(x, start_date, end_date, last)) :
BCB API Request error cannot open the connection
O que pode ser?
Empty table is returned when trying to collect market expectations. It appears that the API is not returning data for some specific series.
In additional, the following warning is returned:
Warning messages: Unknown or uninitialised column: date.
When downloading multiple series a new tidy
argument should be interesting.
This call returns a list with two data.frames
.
x <- rbcb::get_series(c(IBOVESPA = 7, USDBRL = 1), last = 5)
We could use a tidy
argumento to return a tidy dataframe
x <- rbcb::get_series(c(IBOVESPA = 7, USDBRL = 1), last = 5, tidy = TRUE)
with the columns <date>
, <variable>
, <value>
.
The tidy
argument implies that the as
argument should be ignored, because a tibble
would always be returned.
This argument would also work with a single call instead of multiple series only.
Hello!
I'm trying to get market expectations with the rbcb package, but i came across with this message:
"Error in .get_series(url) :
BCB API Request error cannot open the connection".
Can you help me?
Once all series are indexed by dates it is easy to get all merged in the same data structure.
We can consider tibble
, xts
, data.frame
, but ts
can't.
Or instead of getting series merged the return should be a list with the series as its elements.
x <- get_series(c(1, 7, 433))
x[["1"]]
x[["7"]]
x[["433"]]
for named series
x <- get_series(c(DOL = 1, IBOV = 7, IPCA = 433))
x$DOL
x$IBOV
x$IPCA
Hello,
First of all congratulations for the package, it's excellent!
I was using the package to retrieve time series for all currencies in a loop, and I noticed that there is a problem when it comes to querying certain currencies.
The function uses the PTAX forms and the select reference (ChkMoeda) to perform the query. The problem: there are, for some 3 letter ISO codes of the currency, more than one reference in the form list for the same currency.
Exemplifying, the following query does not quote for the period, even if there is some data in the PTAX:
mxn <- get_currency ("MXN", "2018-05-21", "2018-05-22")
Error in get_currency("MXN", "2018-05-21", "2018-05-22") :
BCB API returned error: • Não existe informação para a pesquisa efetuada!•
There are two references to PESO MEXICO in the form (I imagine an old one - no / in the text - that does not work and a recent one - with / in the text - that works), and I believe that when the parser is being made to translate 'MXN' for ChkMoeda from Mexico is catching the very first entry of PESO MEXICO (no /) that does not work. If you try the PTAX form with PESO/MEXICO, it works.
It seems to me that some adjustment in the following function would solve the question:
id_list <- suppressMessages(currency_id_list())
all_currencies <- suppressMessages(get_currency_list())
x <- merge(id_list, all_currencies)
x[x$symbol == symbol,]$id[1] # <<< aqui pode ter mais de uma ocorrência. Das que mapeei que tem duas, a primeira não funciona e a segunda sim
}
I did some workarounds but it's not cool to propose as a solution. Once I get a better time window I can make a proposal for improvement!
Thanks again for the package!
We have a problem with the server when downloading market expectations (the functions of the form get_xxx_market_expectations). It writes "Error in curl::curl_fetch_memory(url, handle = handle) :
Failure when receiving data from the peer". I think it is the same issue as in
Maybe using readLines before the fromJSON function would fix it.
The get_currency function returns a data.frame or xts object with bid and ask columns. This object has no reference to the original currency symbol, so it might be lost if the assignment doesn't name the variable properly.
In order to correct that a new attribute containing the symbol must be set in the returned object.
Currently it has 2 functions
get_series
: for SGS seriesget_currency
: for currency APISince it has plans to have new interfaces implemented, a interesting approach is unify all interfaces into one single function
rbcb_get(...)
This function might be a generic and the objects represent the desired data.
Example:
rbcb_get(currecy('BRL'), start_date, end_date) # uses currency API
rbcb_get(series(IBOVESPA = 7), start_date, end_date) # uses SGS API
If in the future we have a search, the search could return these objects
brl <- rbcb_search('BRL')
rbcb_get(brl, start_date, end_date)
The 226 series refers to TR. This series has different layout and an error is being returned while fetching its data.
> rbcb::get_series(226, start_date = "2016-12-12", end_date = "2017-01-31")
Error in `[<-.data.frame`(`*tmp*`, del, value = NULL) :
missing values are not allowed in subscripted assignments of data frames
In addition: Warning message:
In eval(substitute(expr), e) : NAs introduced by coercion
This series has a different JSON.
The field datafim
.
> rbcb::get_series(226, last = 5, as = "text")
[1] "[{\"data\":\"04/12/2017\",\"datafim\":\"04/01/2018\",\"valor\":\"0.0000\"},{\"data\":\"05/12/2017\",\"datafim\":\"05/01/2018\",\"valor\":\"0.0000\"},{\"data\":\"06/12/2017\",\"datafim\":\"06/01/2018\",\"valor\":\"0.0000\"},{\"data\":\"07/12/2017\",\"datafim\":\"07/01/2018\",\"valor\":\"0.0000\"},{\"data\":\"08/12/2017\",\"datafim\":\"08/01/2018\",\"valor\":\"0.0000\"}]"
get_series function should return a ts object.
It is useful for regular time series, monthly and annually, for example.
When downloading multiple series we could use parallelisation by default.
Hello,
Recently I've updated my OS and I can't install rbcb anymore. Any other way to install it? I've tried using install.packages('rbcb') and by .tar
Tkx
Hi!
The function get_top5s_annual_market_expectations and others like this are not working.
Error in .get_series(url) :
BCB API Request error cannot open the connection
BCB alterou a forma de divulgação da Selic no sistema de expectativas de mercado. Dessa forma, a previsão mensal parou de ser divulgada. Em seu lugar, entrou expectativas por reunião. Sendo assim, a função que puxa expectativas mensais para a selic parou de funcionar.
Essa é a primeira vez que relato um problema via github. Se não fiz da forma mais adequada, peço desculpas antecipadamente.
Parabéns pelo pacote - ajuda demais!
bizdays needs a has_calendar
function
> has_calendar('actual')
# TRUE
> has_calendar('nada')
# FALSE
The calendar can be got with
> calendars()[['actual']]
# Calendar: actual
# Range: 1970-01-01 to 2071-01-01
# weekdays:
Boa tarde,
Faz alguns dias que um código (que sempre funcionou) parou de funcionar. A ideia é simples, só puxar a Selic:
end = '2022-02-01'
start = '2021-01-01'
selic_m <- rbcb::get_monthly_market_expectations("Selic",
start_date = start,
end_date = end)
Agora retorna um DF vazio. Talvez tenha a ver com o fato do BC ter mudado a estrutura da variável selic de mensal (com buracos) para "reuniões"? Saberia me dizer o que pode estar ocorrendo?
Muito obrigado!
Hey @wilsonfreitas , is it possible to retrieve metadata as BETS package does via BETS::BETSsearch()
?
It is an important feature and it would be great to have in rbcb.
As a side issue do you know why rbcb is so much faster than BETS? As discussed in here: nmecsys/BETS#17
Thank you very much.
https://olinda.bcb.gov.br/olinda/servico/Expectativas/versao/v1/aplicacao#!/
New columns:
This error appears when running the get_currency: "BCB API returned error: • Moeda não cadastrada."
Example:
brl_usd <- get_currency('USD', t_1y, t) %>%
select(-bid) %>%
rename(brl_usd = 2)
brl_eur <- get_currency('EUR', t_1y, t) %>%
select(-bid) %>%
rename(brl_eur= 2)
brl_gbp <- get_currency('GBP', t_1y, t) %>%
select(-bid) %>%
rename(brl_libra = 2)
Wilson, nao sei como entrar em contato aqui
To name time series with the get_series function the user has to use the argument name
.
rbcb::get_series(2234, "2002-01-31", as = "xts", name = "cambio")
Another way to name series that I believe is more elegant and clean is by passing a named vector with the code. Example
rbcb::get_series(c(cambio = 2234), "2002-01-31", as = "xts")
This should have the same result.
In the future the name
argument can be deprecated in favor of this new naming style.
This has a second advantage that is, get_series
can return multiple series in the future and this naming style avoid inconsistencies.
Name the returned timeseries of functions:
with an additional class named rbcbTimeSeries
, for example.
This class can used to implement methods that:
Wilson, congrats for the package. It's a fantastic initiative.
I was wondering if it would be possible to incorporate in the package BCB's data on real state prices , which are organized by BCB as the IVG-R (Índice de Valores de Garantia de Imóveis Residenciais Financiados)
I've seen a few PDF reports on this index but I couldn't find IVG-R data on their website, though. I've already sent them an email requesting them to make this data publicly available on their open data portal.
best,
Rafael H M Pereira
The option rownames which defaults to FALSE could be implemented in get_series.
This option would create data.frames with dates as rownames instead of column, following the approach similar to xts
rbcb::get_series(16122, last = 24, name = "IPCA", as = "data.frame", rownames = TRUE)
The currency API returns the bid and ask columns.
Function helpers Bid
and Ask
would help returning these series instead of using subsetting operators.
Similar to what we have in quantmod with the helpers Cl
, Op
, ...
whenever I try to use the function get_currency all I can get is:
Error in curl::curl_fetch_memory(url, handle = handle) :
Recv failure: Connection was reset
Oi Wilson,
Seguinte, estou usando o rbcb mas desde ontem só retorna o seguinte erro:
Error in curl::curl_fetch_memory(url, handle = handle) :
SSL certificate problem: unable to get local issuer certificate
Imagino que o problema é no lado do BCB. Por acaso sabes como solucionar?
Segue meu código:
`
get.cdi.anual <- function(first.date = '2000-01-01', last.date = Sys.Date()) {
require(rbcb)
require(tidyverse)
cat('\nFetching CDI Anual')
my.code <- c(value = 4391)
df.cdi <- get_series(my.code, start_date = first.date,
end_date = last.date) %>%
mutate(series = 'CDI')
return(df.cdi)
}
`
This call returns zeros results, the layout might has changed.
rbcb::search_series("cambio")
# 0 results
# Pagination 1 / 1
Error in .get_series(url) :
BCB API Request error cannot open the connection to 'https://olinda.bcb.gov.br/olinda/servico/Expectativas/versao/v1/odata/ExpectativasMercadoAnuais?%24filter=%28Indicador%20eq%20%27PIB%20Total%27%29&%24format=application%2Fjson&%24orderby=Data%20desc&%24select=Indicador%2CIndicadorDetalhe%2CData%2CDataReferencia%2CMedia%2CMediana%2CDesvioPadrao%2CCoeficienteVariacao%2CMinimo%2CMaximo%2CnumeroRespondentes%2CbaseCalculo'
Instead of start_date
and end_date
a date range specification should be created, very similar to what we have with xts
.
References:
Hi there.
Has anyone experienced the error below while installing this through devtools::install_github?
* installing *source* package 'rbcb' ...
** using staged installation
** R
Error in parse(outFile) :
C:/Users/raphael.coelho/AppData/Local/Temp/RtmpQJB2Lr/R.INSTALL3210597b5558/rbcb/R/rbcb_olinda_get_currencies.R:16:224: '>' inesperado
15: as.Date(end_date), "%m/%d/%Y")
16: "https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoMoedaPeriodo(moeda=@moeda,dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)?%%40moeda='%s'&%%40dataInicial='%
^
ERROR: unable to collate and parse R files for package 'rbcb'
get_currency returns currencies quoted in BRL, but it is more usual USD quoted currencies.
An argument could be added to define the reference currency: BRL or USD (at first).
rbcb::get_currency(symbol, start_date, end_date, as, reference = c("USD", "BRL"))
The get_series arguments start_date and end_date only work when they are set together, but they are optional in the API.
For end_date there is a possible workaround, that is set Sys.Date() when this argument is necessary.
But, for start_date I have the date 1900-01-01 as a possible workaround.
It is annoying to remember these codes used in the get_series
.
Maybe creating aliases would help with that.
These aliases can be create according to the use of the function get_series
.
On the other hand they can be created manually.
The can be stored in the current directory or in the user home directory.
The cache system can be implemented the say way I did in rb3 package, using tempdir
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.