Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@
^\.github$
^doc$
^Meta$
^\.Rhistory$
^\.RData$
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: brfinance
Title: Simplified Access to Brazilian Financial and Macroeconomic Data
Version: 0.5.0.900
Version: 0.6.0.900
Authors@R:
person(given = "João Paulo", family = "dos Santos Pereira Barbosa", email = "[email protected]",role = c("aut", "cre"))
Description: It offers simplified access to Brazilian macroeconomic and financial indicators selected from official sources, such as the 'IBGE' (Brazilian Institute of Geography and Statistics) via the 'SIDRA' API and the 'Central Bank of Brazil' via the 'SGS' API. It allows users to quickly retrieve and visualize data series such as the unemployment rate and the Selic interest rate. This package was developed for data access and visualization purposes, without generating forecasts or statistical results. For more information, see the official APIs: <https://sidra.ibge.gov.br/> and <https://dadosabertos.bcb.gov.br/dataset/>.
Expand Down
3 changes: 3 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ export(get_gdp_growth)
export(get_inflation_rate)
export(get_selic_rate)
export(get_unemployment)
export(plot_cdi_rate)
export(plot_exchange_rate)
export(plot_inflation_rate)
export(plot_selic_rate)
export(plot_series_comparison)
export(plot_unemployment)
37 changes: 19 additions & 18 deletions R/get_cdi_rate.R
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@
#' @param labels Logical indicating whether to add variable labels using the `labelled`
#' package. Labels provide descriptive text for each column when available.
#'
#' @return A data.frame with CDI rate. Columns depend on the `language` parameter:
#' - English (`language = "eng"`): `date` (Date), `cdi_rate` (numeric, % per year)
#' - Portuguese (`language = "pt"`): `data_referencia` (Date), `taxa_cdi` (numeric, % ao ano)
#' @return A data.frame with columns:
#' \describe{
#' \item{date}{Reference date}
#' \item{value}{Daily CDI rate (% per day)}
#' \item{value_annualized}{Annualized CDI rate (% per year, 252 business days)}
#' }
#'
#' @note
#' **Series information**: This function uses SGS series 12, which represents the
Expand Down Expand Up @@ -79,7 +82,7 @@ get_cdi_rate <- function(start_date = NULL,

# === FUNCTION BODY ===
# Declare global variables for dplyr operations
value <- cdi_rate <- NULL
value <- cdi_rate <- value_annualized <- NULL

# Use internal function to download data (SGS series 12 = CDI rate)
data <- .get_sgs_series(
Expand All @@ -91,33 +94,31 @@ get_cdi_rate <- function(start_date = NULL,
# Process the data
data <- data |>
dplyr::arrange(date) |>
dplyr::mutate(
value_annualized = ((1+value/100)^252-1)*100
) |>
dplyr::select(
date,
cdi_rate = value # Rename for clarity
value,
value_annualized
)

# Translation to Portuguese if needed
if (language == "pt") {
data <- data |>
dplyr::rename(
data_referencia = date,
taxa_cdi = cdi_rate
)
}

# Add labels if requested and package is available
# === VARIABLE LABELS ===
if (isTRUE(labels) && requireNamespace("labelled", quietly = TRUE)) {

if (language == "pt") {
data <- labelled::set_variable_labels(
data,
data_referencia = "Data de referencia",
taxa_cdi = "Taxa CDI (% ao ano) - Certificado de Deposito Interbancario"
date = "Data de referencia",
value = "Taxa CDI diaria (% ao dia)",
value_annualized = "Taxa CDI anualizada (% ao ano, 252 dias uteis)"
)
} else {
data <- labelled::set_variable_labels(
data,
date = "Reference date",
cdi_rate = "CDI rate (% per year) - Interbank Deposit Certificate"
value = "Daily CDI rate (% per day)",
value_annualized = "Annualized CDI rate (% per year, 252 business days)"
)
}
}
Expand Down
27 changes: 13 additions & 14 deletions R/get_exchange_rate.R
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ get_exchange_rate <- function(start_date = NULL,
stop("'labels' must be a single logical value (TRUE or FALSE)", call. = FALSE)
}

# Set default start_date if NULL (last 30 days by default for CDI)
if (is.null(start_date)) {
start_date <- Sys.Date() - 30 # Last 30 days
}

# === FUNCTION BODY ===

# Set default start_date if NULL (last 30 days by default for exchange rate)
if (is.null(start_date)) {
start_date <- Sys.Date() - 30 # Last 30 days
Expand All @@ -87,31 +94,23 @@ get_exchange_rate <- function(start_date = NULL,
dplyr::arrange(date) |>
dplyr::select(
date,
exchange_rate = value # Rename for clarity
value
)

# Translation to Portuguese if needed
if (language == "pt") {
data <- data |>
dplyr::rename(
data_referencia = date,
taxa_cambio = exchange_rate
)
}

# Add labels if requested and package is available
# === VARIABLE LABELS ===
if (isTRUE(labels) && requireNamespace("labelled", quietly = TRUE)) {

if (language == "pt") {
data <- labelled::set_variable_labels(
data,
data_referencia = "Data de referencia",
taxa_cambio = "Taxa de cambio (R$/US$) - comercial, venda"
date = "Data de referencia",
value = "Taxa de cambio (R$/US$) - comercial, venda"
)
} else {
data <- labelled::set_variable_labels(
data,
date = "Reference date",
exchange_rate = "Exchange rate (R$/US$) - commercial, selling"
value = "Exchange rate (R$/US$) - commercial, selling"
)
}
}
Expand Down
62 changes: 16 additions & 46 deletions R/get_gdp_growth.R
Original file line number Diff line number Diff line change
Expand Up @@ -55,85 +55,55 @@ get_gdp_growth <- function(start_date = "2000-01-01",
language = "eng",
labels = TRUE) {

# Validate 'language' parameter
# === PARAMETER VALIDATION ===
if (!is.character(language) || length(language) != 1) {
stop("'language' must be a single character string ('eng' or 'pt')", call. = FALSE)
}

language <- tolower(language)
if (!language %in% c("eng", "pt")) {
stop("'language' must be either 'eng' (English) or 'pt' (Portuguese)", call. = FALSE)
stop("'language' must be either 'eng' or 'pt'", call. = FALSE)
}

# Validate 'labels' parameter
if (!is.logical(labels) || length(labels) != 1) {
stop("'labels' must be a single logical value (TRUE or FALSE)", call. = FALSE)
}

# Note: 'start_date' and 'end_date' are validated in the internal function
# .normalize_date() which handles NULLs and various date formats
# === FUNCTION BODY ===
value <- NULL

# Declare global variables for dplyr operations
value <- gdp_nominal <- gdp_growth <- data_referencia <- crescimento_pib <- NULL


# Use internal function to download data
# Download nominal GDP series (SGS 2010)
data <- .get_sgs_series(
series_id = 2010, # GDP nominal code
series_id = 2010,
start_date = start_date,
end_date = end_date
)

# Process the data
# Compute quarterly growth rate
data <- data |>
dplyr::arrange(date) |>
dplyr::mutate(
gdp_nominal = as.numeric(value),
gdp_growth = (gdp_nominal / dplyr::lag(gdp_nominal) - 1) * 100
value = (as.numeric(value) / dplyr::lag(as.numeric(value)) - 1) * 100
) |>
dplyr::select(
date,
gdp_growth,
gdp_nominal
)

# Note: date filtering is already applied in .get_sgs_series
# No need for additional filtering here

# Translation to Portuguese if needed
if (language == "pt") {
data <- data |>
dplyr::rename(
data_referencia = date,
crescimento_pib = gdp_growth,
pib_nominal = gdp_nominal
)
}
dplyr::select(date, value)

# Add labels if requested
if (isTRUE(labels) && requireNamespace("labelled", quietly = TRUE)) {
if (tolower(language) == "pt") {

if (language == "pt") {
data <- labelled::set_variable_labels(
data,
data_referencia = "Trimestre de referencia",
crescimento_pib = "Crescimento do PIB real (%)",
pib_nominal = "PIB nominal (R$ milhoes)"
date = "Trimestre de referencia",
value = "Crescimento do PIB (%)"
)
} else {
data <- labelled::set_variable_labels(
data,
date = "Reference quarter",
gdp_growth = "GDP growth rate (%)",
gdp_nominal = "Nominal GDP (R$ millions)"
date = "Reference quarter",
value = "GDP growth rate (%)"
)
}
}

# Remove gdp_nominal column from final result (keep only growth rate)
if (tolower(language) == "pt") {
data <- dplyr::select(data, data_referencia, crescimento_pib)
} else {
data <- dplyr::select(data, date, gdp_growth)
}

return(data)
}
100 changes: 33 additions & 67 deletions R/get_inflation_rate.R
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@
#' - `ytd_inflation` (numeric): Year-to-date accumulated inflation (%)
#' - `twelve_month_inflation` (numeric): 12-month accumulated inflation (%)
#' - Portuguese (`language = "pt"`):
#' - `data_referencia` (Date): Mês de referência
#' - `inflacao_mensal` (numeric): Variação mensal do IPCA (%)
#' - `inflacao_acumulada_ano` (numeric): Inflação acumulada no ano (%)
#' - `inflacao_12_meses` (numeric): Inflação acumulada nos últimos 12 meses (%)
#' - `data_referencia` (Date): Mes de referencia
#' - `inflacao_mensal` (numeric): Variacao mensal do IPCA (%)
#' - `inflacao_acumulada_ano` (numeric): Inflacao acumulada no ano (%)
#' - `inflacao_12_meses` (numeric): Inflacao acumulada nos ultimos 12 meses (%)
#'
#' @note
#' **Default Period**: When `start_date = NULL`, defaults to `"2020-01-01"`, providing
Expand Down Expand Up @@ -95,96 +95,62 @@ get_inflation_rate <- function(start_date = "2012-01-01",

# === FUNCTION BODY ===
# Declare global variables for dplyr operations
value <- monthly_inflation <- year <- ytd_inflation <- twelve_month_inflation <- NULL
value <- monthly_inflation <- ytd_inflation <- twelve_month_inflation <- year <- NULL

# Calculate start date for download (12 months earlier for 12-month inflation calculation)
# First normalize the user's start_date
# === DATE NORMALIZATION ===
start_date_norm <- .normalize_date(start_date, is_start = TRUE)
end_date_norm <- .normalize_date(end_date, is_start = FALSE)

# Download starting 12 months earlier than requested
download_start_date <- start_date_norm - months(12)
download_start_date_str <- format(download_start_date, "%Y-%m-%d")
download_start <- start_date_norm - lubridate::period(months = 12)

# Use internal function to download data (SGS series 433 = IPCA monthly)
# We need to pass the earlier start date for calculations
data_full <- .get_sgs_series(
series_id = 433, # Código do IPCA mensal
start_date = download_start_date_str,
end_date = end_date
# === DOWNLOAD DATA (IPCA mensal SGS 433) ===
data <- .get_sgs_series(
series_id = 433,
start_date = format(download_start, "%Y-%m-%d"),
end_date = end_date
)

# Process the data - keep your original variable names
data <- data_full |>
# === PROCESS DATA ===
data <- data |>
dplyr::arrange(date) |>
dplyr::mutate(
monthly_inflation = as.numeric(value),
year = lubridate::year(date)
value = as.numeric(value),
year = lubridate::year(date)
) |>
dplyr::select(date, monthly_inflation, year)

# Filter for end_date (if provided) - already handled in .get_sgs_series but double-check
if (!is.null(end_date)) {
end_date_norm <- .normalize_date(end_date, is_start = FALSE)
data <- data |>
dplyr::filter(date <= end_date_norm)
}

# Year-to-date accumulated inflation (your original calculation)
data <- data |>
dplyr::group_by(year) |>
dplyr::mutate(
ytd_inflation = (cumprod(1 + monthly_inflation / 100) - 1) * 100
ytd_inflation = (cumprod(1 + value / 100) - 1) * 100
) |>
dplyr::ungroup()

# 12-month accumulated inflation (your original calculation)
data <- data |>
dplyr::arrange(date) |>
dplyr::ungroup() |>
dplyr::mutate(
twelve_month_inflation = sapply(
seq_along(monthly_inflation),
seq_along(value),
function(i) {
if (i < 12) return(NA_real_)
(prod(1 + monthly_inflation[(i-11):i] / 100) - 1) * 100
(prod(1 + value[(i - 11):i] / 100) - 1) * 100
}
)
)

# Filter to show only the requested period (remove the extra 12 months)
data <- data |>
dplyr::filter(date >= start_date_norm)

# Remove year column from final output (not in your original output)
data <- dplyr::select(data, -year)

# Translate column names if language = "pt" (your original logic)
if (language == "pt") {
data <- data |>
dplyr::rename(
data_referencia = date,
inflacao_mensal = monthly_inflation,
inflacao_acumulada_ano = ytd_inflation,
inflacao_12_meses = twelve_month_inflation
)
}
) |>
dplyr::filter(date >= start_date_norm & date <= end_date_norm) |>
dplyr::select(date, value, ytd_inflation, twelve_month_inflation)

# Add labels if requested (your original logic)
# === LABELS ===
if (isTRUE(labels) && requireNamespace("labelled", quietly = TRUE)) {
if (language == "pt") {
data <- labelled::set_variable_labels(
data,
data_referencia = "Mes de referencia",
inflacao_mensal = "Variacao mensal do IPCA (%)",
inflacao_acumulada_ano = "Inflacao acumulada no ano (%)",
inflacao_12_meses = "Inflacao acumulada nos ultimos 12 meses (%)"
date = "Mes de referencia",
value = "Inflacao mensal IPCA (%)",
ytd_inflation = "Inflacao acumulada no ano (%)",
twelve_month_inflation = "Inflacao acumulada em 12 meses (%)"
)
} else {
data <- labelled::set_variable_labels(
data,
date = "Reference month",
monthly_inflation = "Monthly IPCA variation (%)",
ytd_inflation = "Year-to-date accumulated inflation (%)",
twelve_month_inflation = "12-month accumulated inflation (%)"
date = "Reference month",
value = "Monthly IPCA inflation (%)",
ytd_inflation = "Year-to-date inflation (%)",
twelve_month_inflation = "12-month inflation (%)"
)
}
}
Expand Down
Loading