Quantcast
Channel: R-bloggers
Viewing all articles
Browse latest Browse all 12080
↧

New Package GetITRData

$
0
0

(This article was first published on R and Finance, and kindly contributed to R-bloggers)

Downloading Quarterly Financial Reports from Bovespa –

Financial statements of companies traded at B3 (formerly Bovespa), the Brazilian stock exchange, are available in its website. Accessing the data for a single company is straightforwardd. In the website one can find a simple interface for accessing this dataset. An example is given here. However, gathering and organizing the data for a large scale research, with many companies and many quarters, is painful. Quarterly reports must be downloaded or copied individually and later aggregated. Changes in the accounting format thoughout time can make this process slow, unreliable and irreproducible.

Package GetITRData provides a R interface to all financial statements available in the website. It not only downloads the data but also organizes it in a tabular format and allows the use of inflation indexes. Users can simply select companies and a time period to download all available data. Several information about current companies, such as sector and available quarters are also at reach. The main purpose of the package is to make it easy to access quarterly financial statements in large scale research, facilitating the reproducibility of corporate finance studies with Bovespa data.

Installation

The package is available in CRAN (release version) and in Github (development version). You can install any of those with the following code:

# Release version in CRAN install.packages('GetITRData') # Development version in Githubdevtools::install\_github('msperlin/GetITRData') 

How to use GetITRData

The starting point of GetITRData is to find the official names of companies in Bovespa. Function gitrd.search.company serves this purpose. Given a string (text), it will search for a partial matches in companies names. As an example, let’s find the official name of Petrobras, one of the largest companies in Brazil:

library(GetITRData)gitrd.search.company('petrobras')## ## Reading info file from github## Found 24012 lines for 603 companies  [Actives =  457  Inactives =  146 ]## Last file update:  2017-09-19## ## Found 1 companies:## PETROBRAS | situation = ATIVO | first date = 1998-09-30 | last date - 2017-06-30

Its official name in Bovespa records is PETROBRAS. Data for quarterly statements is available from 1998 to 2017. The situation of the company, active or canceled, is also given. This helps verifying the availability of data.

The content of all available quarterly statements can be accessed with function gitrd.get.info.companies. It will read and parse a .csv file from my github repository. This will be periodically updated for new quarterly statements. Let’s try it out:

df.info <- gitrd.get.info.companies()## ## Reading info file from github## Found 24012 lines for 603 companies  [Actives =  457  Inactives =  146 ]## Last file update:  2017-09-19str(df.info)## Classes 'tbl_df', 'tbl' and 'data.frame':    24012 obs. of  10 variables:##  $ id.company  : int  16330 16330 16330 16330 16330 16330 16330 16330 16330 16330 ...##  $ name.company: chr  "521 PARTICIPAÇÕES S/A" "521 PARTICIPAÇÕES S/A" "521 PARTICIPAÇÕES S/A" "521 PARTICIPAÇÕES S/A" ...##  $ main.sector : chr  NA NA NA NA ...##  $ sub.sector  : chr  NA NA NA NA ...##  $ segment     : chr  NA NA NA NA ...##  $ id.file     : int  47368 42591 40601 37569 32706 30654 27521 22269 20368 17649 ...##  $ dl.link     : chr  "http://www.rad.cvm.gov.br/enetconsulta/frmDownloadDocumento.aspx?CodigoInstituicao=2&NumeroSequencialDocumento=47368" "http://www.rad.cvm.gov.br/enetconsulta/frmDownloadDocumento.aspx?CodigoInstituicao=2&NumeroSequencialDocumento=42591" "http://www.rad.cvm.gov.br/enetconsulta/frmDownloadDocumento.aspx?CodigoInstituicao=2&NumeroSequencialDocumento=40601" "http://www.rad.cvm.gov.br/enetconsulta/frmDownloadDocumento.aspx?CodigoInstituicao=2&NumeroSequencialDocumento=37569" ...##  $ id.date     : Date, format: "2015-03-31" "2014-09-30" ...##  $ id.type     : chr  "after 2011" "after 2011" "after 2011" "after 2011" ...##  $ situation   : chr  "ATIVO" "ATIVO" "ATIVO" "ATIVO" ...

This file includes several information that are gathered from Bovespa: names of companies, sectors, dates quarterly statements and, most importantly, the links to download the files. The resulting dataframe can be used to filter and gather information for large scale research such as downloading financial data for a specific sector.

Downloading financial information for ONE company

All you need to download financial data with GetITRData are the official names of companies, which can be found with gitrd.search.company, the desired starting and ending dates and the type of financial information (individual or consolidated). Let’s try it for PETROBRAS:

name.companies <- 'PETROBRAS'first.date <- '2005-01-01'last.date  <- '2006-01-01'type.statements <- 'individual'df.reports <- gitrd.GetITRData(name.companies = name.companies,                                first.date = first.date,                               last.date = last.date,                               type.info = type.statements)## ## Reading info file from github## Found 24012 lines for 603 companies  [Actives =  457  Inactives =  146 ]## Last file update:  2017-09-19## ## Downloading data for 1 companies## Type of financial statements: individual## First Date: 2005-01-01## Laste Date: 2006-01-01## Inflation index: none## ## Downloading none data using BETS Done## ## ## WARNING: For quarters before 2009, the cash flow statements are not available## ## Starting processing stage:## PETROBRAS##  Available quarters: 2005-09-30  2005-06-30  2005-03-31## ## ## Processing PETROBRAS, Quarter = 2005-09-30   Downloading | Reading file## Processing PETROBRAS, Quarter = 2005-06-30   Downloading | Reading file## Processing PETROBRAS, Quarter = 2005-03-31   Downloading | Reading file## Warning in max.default(structure(numeric(0), class = "Date"), na.rm =## FALSE): no non-missing arguments to max; returning -Inf

The resulting object is a tibble, a data.frame type of object that allows for list columns. Let’s have a look in its content:

str(df.reports)## Classes 'tbl_df', 'tbl' and 'data.frame':    1 obs. of  10 variables:##  $ company.name: chr "PETROBRAS"##  $ company.code: int 9512##  $ type.info   : chr "individual"##  $ min.date    : Date, format: "2005-03-31"##  $ max.date    : Date, format: "2005-09-30"##  $ n.quarters  : int 3##  $ assets      :List of 1##   ..$ :Classes 'tbl_df', 'tbl' and 'data.frame': 191 obs. of  5 variables:##   .. ..$ acc.number  : chr  "1" "1.01" "1.01.01" "1.01.01.01" ...##   .. ..$ acc.desc    : chr  "Ativo Total" "Ativo Circulante" "Disponibilidades" "Caixa e Bancos" ...##   .. ..$ acc.value   : int  147026464 41052623 15146496 1498194 13648302 9450575 3488650 4955111 1090180 -83366 ...##   .. ..$ ref.date    : Date, format: "2005-09-30" ...##   .. ..$ company.name: chr  "PETROBRAS" "PETROBRAS" "PETROBRAS" "PETROBRAS" ...##  $ liabilities :List of 1##   ..$ :Classes 'tbl_df', 'tbl' and 'data.frame': 160 obs. of  5 variables:##   .. ..$ acc.number  : chr  "2" "2.01" "2.01.01" "2.01.01.01" ...##   .. ..$ acc.desc    : chr  "Passivo Total" "Passivo Circulante" "Empréstimos e Financiamentos" "Financiamentos" ...##   .. ..$ acc.value   : int  147026464 44603494 1154258 1039841 114417 0 5205735 7429086 1156875 935603 ...##   .. ..$ ref.date    : Date, format: "2005-09-30" ...##   .. ..$ company.name: chr  "PETROBRAS" "PETROBRAS" "PETROBRAS" "PETROBRAS" ...##  $ income      :List of 1##   ..$ :Classes 'tbl_df', 'tbl' and 'data.frame': 100 obs. of  5 variables:##   .. ..$ acc.number  : chr  "3.01" "3.02" "3.03" "3.04" ...##   .. ..$ acc.desc    : chr  "Receita Bruta de Vendas e/ou Serviços" "DeduçÔes da Receita Bruta" "Receita Líquida de Vendas e/ou Serviços" "Custo de Bens e/ou Serviços Vendidos" ...##   .. ..$ acc.value   : int  37870949 -9778549 28092400 -15030559 13061841 -4270217 -1221668 -895230 -899 -894331 ...##   .. ..$ ref.date    : Date, format: "2005-09-30" ...##   .. ..$ company.name: chr  "PETROBRAS" "PETROBRAS" "PETROBRAS" "PETROBRAS" ...##  $ df.cashflow :List of 1##   ..$ :'data.frame': 0 obs. of  5 variables:##   .. ..$ acc.desc    : Named list()##   .. ..$ acc.value   : logi ##   .. ..$ acc.number  : chr ##   .. ..$ company.name: chr ##   .. ..$ ref.date    :Class 'Date'  num(0) ##   .. ..- attr(*, "na.action")=Class 'omit'  Named int [1:3] 1 2 3##   .. .. .. ..- attr(*, "names")= chr [1:3] "1" "2" "3"

Object df.reports only has one row since we only asked for data of one company. The number of rows increases with the number of companies, as we will soon learn with the next example. All financial statements for the different quarters are available within df.reports. For example, the income statements for all desired quarters of PETROBRAS are:

df.income.long <- df.reports$income[[1]]str(df.income.long)## Classes 'tbl_df', 'tbl' and 'data.frame':    100 obs. of  5 variables:##  $ acc.number  : chr  "3.01" "3.02" "3.03" "3.04" ...##  $ acc.desc    : chr  "Receita Bruta de Vendas e/ou Serviços" "DeduçÔes da Receita Bruta" "Receita Líquida de Vendas e/ou Serviços" "Custo de Bens e/ou Serviços Vendidos" ...##  $ acc.value   : int  37870949 -9778549 28092400 -15030559 13061841 -4270217 -1221668 -895230 -899 -894331 ...##  $ ref.date    : Date, format: "2005-09-30" "2005-09-30" ...##  $ company.name: chr  "PETROBRAS" "PETROBRAS" "PETROBRAS" "PETROBRAS" ...

The resulting dataframe is in the long format, ready for processing. In the long format, financial statements of different quarters are stacked. In the wide format, we have the columns as dates and rows as account names/ids. If you want the wide format, which I believe is most common in financial analysis, you can use function gitrd.convert.to.wide. See an example next:

df.income.wide <- gitrd.convert.to.wide(df.income.long)knitr::kable(df.income.wide )
acc.numberacc.desccompany.name2005-03-312005-06-302005-09-30
3.01Receita Bruta de Vendas e/ou ServiçosPETROBRAS313551833542558437870949
3.02DeduçÔes da Receita BrutaPETROBRAS-8788723-9321322-9778549
3.03Receita Líquida de Vendas e/ou ServiçosPETROBRAS225664602610426228092400
3.04Custo de Bens e/ou Serviços VendidosPETROBRAS-12052044-14530594-15030559
3.05Resultado BrutoPETROBRAS105144161157366813061841
3.06Despesas/Receitas OperacionaisPETROBRAS-2869703-5249799-4270217
3.06.01Com VendasPETROBRAS-858170-820899-1221668
3.06.02Gerais e AdministrativasPETROBRAS-768830-880185-895230
3.06.02.01Honor.Diretoria e Cons. AdministraçãoPETROBRAS-984-886-899
3.06.02.02De AdministraçãoPETROBRAS-767846-879299-894331
3.06.03FinanceirasPETROBRAS-53787-480281-282706
3.06.03.01Receitas FinanceirasPETROBRAS525452106753272290
3.06.03.02Despesas FinanceirasPETROBRAS-579239-587034-554996
3.06.04Outras Receitas OperacionaisPETROBRAS000
3.06.05Outras Despesas OperacionaisPETROBRAS-2104923-3155693-1956858
3.06.05.01Custos Explot.p/Extração Petróleo/GåsPETROBRAS-107010-101527-334116
3.06.05.02Custo c/ Pesq. Desenv. TecnolĂłgicoPETROBRAS-192741-221813-247456
3.06.05.03TributĂĄriasPETROBRAS-185581-290086-114519
3.06.05.04VariaçÔes Monetårias e Cambiais LíquidasPETROBRAS-117821-921626-401757
3.06.05.05Outras Despesas/Receitas Oper. LiquidasPETROBRAS-1501770-1620641-859010
3.06.06Resultado da EquivalĂȘncia PatrimonialPETROBRAS9160078725986245
3.07Resultado OperacionalPETROBRAS764471363238698791624
3.08Resultado NĂŁo OperacionalPETROBRAS-151498-646701064
3.08.01ReceitasPETROBRAS12568805450552
3.08.02DespesasPETROBRAS-152754-73475-449488
3.09Resultado Antes Tributação/ParticipaçÔesPETROBRAS749321562591998792688
3.10Provisão para IR e Contribuição SocialPETROBRAS-1847762-1151342-3002751
3.11IR DiferidoPETROBRAS-538132-408725-111709
3.12ParticipaçÔes/ContribuiçÔes EstatutåriasPETROBRAS000
3.12.01ParticipaçÔesPETROBRAS000
3.12.01.01Partic. de Empregados e administradoresPETROBRAS0NANA
3.12.02ContribuiçÔesPETROBRAS000
3.13ReversĂŁo dos Juros sobre Capital PrĂłprioPETROBRAS000
3.15Lucro/PrejuĂ­zo do PerĂ­odoPETROBRAS510732146991325678228

Downloading financial information for SEVERAL companies

If you are doing serious research, it is likely that you need financial statements for more than one company. Package GetITRData is specially designed for handling large scale download of data. Let’s build a case with 5 randomly selected companies:

set.seed(5)my.companies <- sample(unique(df.info$name.company), 5)first.date <- '2005-01-01'last.date  <- '2006-01-01'type.statements <- 'individual'df.reports <- gitrd.GetITRData(name.companies = my.companies,                                   first.date = first.date,                                  last.date = last.date,                                  type.info = type.statements)## ## Reading info file from github## Found 24012 lines for 603 companies  [Actives =  457  Inactives =  146 ]## Last file update:  2017-09-19## ## Downloading data for 5 companies## Type of financial statements: individual individual  individual  individual  individual## First Date: 2005-01-01## Laste Date: 2006-01-01## Inflation index: none## ## Downloading none data using BETS Done## ## ## WARNING: Cant find available dates for BV LEASING## WARNING: For quarters before 2009, the cash flow statements are not available## ## Starting processing stage:## BANESTES S/A##  Available quarters: 2005-09-30  2005-06-30  2005-03-31## CIA. IGUAÇU DE CAFÉ SOLÚVEL##  Available quarters: 2005-09-30  2005-06-30  2005-03-31## MUNDIAL##  Available quarters: 2005-09-30  2005-06-30  2005-03-31## TELEMAR PARTICIPAÇÔES S.A##  Available quarters: 2005-09-30  2005-06-30  2005-03-31## ## ## Processing BANESTES S/A, Quarter = 2005-09-30    Downloading | Reading file## Processing BANESTES S/A, Quarter = 2005-06-30    Downloading | Reading file## Processing BANESTES S/A, Quarter = 2005-03-31    Downloading | Reading file## Warning in max.default(structure(numeric(0), class = "Date"), na.rm =## FALSE): no non-missing arguments to max; returning -Inf## ## Processing CIA. IGUAÇU DE CAFÉ SOLÚVEL, Quarter = 2005-09-30 Downloading | Reading file## Processing CIA. IGUAÇU DE CAFÉ SOLÚVEL, Quarter = 2005-06-30 Downloading | Reading file## Processing CIA. IGUAÇU DE CAFÉ SOLÚVEL, Quarter = 2005-03-31 Downloading | Reading file## Warning in max.default(structure(numeric(0), class = "Date"), na.rm =## FALSE): no non-missing arguments to max; returning -Inf## ## Processing MUNDIAL, Quarter = 2005-09-30 Downloading | Reading file## Processing MUNDIAL, Quarter = 2005-06-30 Downloading | Reading file## Processing MUNDIAL, Quarter = 2005-03-31 Downloading | Reading file## Warning in max.default(structure(numeric(0), class = "Date"), na.rm =## FALSE): no non-missing arguments to max; returning -Inf## ## Processing TELEMAR PARTICIPAÇÔES S.A, Quarter = 2005-09-30   Downloading | Reading file## Processing TELEMAR PARTICIPAÇÔES S.A, Quarter = 2005-06-30   Downloading | Reading file## Processing TELEMAR PARTICIPAÇÔES S.A, Quarter = 2005-03-31   Downloading | Reading file## Warning in max.default(structure(numeric(0), class = "Date"), na.rm =## FALSE): no non-missing arguments to max; returning -Inf

And now we can check the resulting tibble:

head(df.reports )## # A tibble: 4 x 10##                  company.name company.code  type.info   min.date##                                            ## 1                BANESTES S/A         1155 individual 2005-03-31## 2 CIA. IGUAÇU DE CAFÉ SOLÚVEL         3336 individual 2005-03-31## 3                     MUNDIAL         5312 individual 2005-03-31## 4   TELEMAR PARTICIPAÇÔES S.A        18678 individual 2005-03-31## # ... with 6 more variables: max.date , n.quarters ,## #   assets , liabilities , income , df.cashflow 

Every row of df.reports will provide information for one company. Metadata about the corresponding dataframes such as min/max dates is available in the first columns. Keeping a tabular structure facilitates the organization and future processing of all financial data. We can use tibble df.reports for creating other dataframes in the long format containing data for all companies. See next, where we create dataframes with the assets and liabilities of all companies:

df.assets <- do.call(what = rbind, args = df.reports$assets)df.liabilities <- do.call(what = rbind, args = df.reports$liabilities)df.assets.liabilities <- rbind(df.assets, df.liabilities)

As an example, let’s use the resulting dataframe for calculating and analyzing a simple liquidity index of a company, the total of current (liquid) assets (Ativo circulante) divided by the total of current short term liabilities (Passivo Circulante), over time.

library(dplyr)## ## Attaching package: 'dplyr'## The following objects are masked from 'package:stats':## ##     filter, lag## The following objects are masked from 'package:base':## ##     intersect, setdiff, setequal, unionmy.tab <- df.assets.liabilities %>%  group_by(company.name, ref.date) %>%  summarise(Liq.Index = acc.value[acc.number == '1.01']/ acc.value[acc.number == '2.01'])my.tab## # A tibble: 12 x 3## # Groups:   company.name [?]##                   company.name   ref.date Liq.Index##                                    ##  1                BANESTES S/A 2005-03-31 0.7985816##  2                BANESTES S/A 2005-06-30 0.8393188##  3                BANESTES S/A 2005-09-30 0.9151590##  4 CIA. IGUAÇU DE CAFÉ SOLÚVEL 2005-03-31 2.3459918##  5 CIA. IGUAÇU DE CAFÉ SOLÚVEL 2005-06-30 2.7291873##  6 CIA. IGUAÇU DE CAFÉ SOLÚVEL 2005-09-30 2.1644541##  7                     MUNDIAL 2005-03-31 0.7903105##  8                     MUNDIAL 2005-06-30 0.8555824##  9                     MUNDIAL 2005-09-30 0.9052814## 10   TELEMAR PARTICIPAÇÔES S.A 2005-03-31 1.5650393## 11   TELEMAR PARTICIPAÇÔES S.A 2005-06-30 0.9419386## 12   TELEMAR PARTICIPAÇÔES S.A 2005-09-30 1.3275712

Now we can visualize the information using ggplot2:

library(ggplot2)p <- ggplot(my.tab, aes(x = ref.date, y = Liq.Index, fill = company.name)) +  geom_col(position = 'dodge' )print(p)

As we can see, CIA IGUACU is the company with highest liquidity, being able to pay its short term debt with the current assets in all quarters. We can certainly do a lot more interesting studies based on this dataset.

Exporting financial data

The package includes function gitrd.export.ITR.data for exporting the financial data to an Excel file. Users can choose between the long and wide format. See next:

my.basename <- 'MyExcelData'my.format <- 'xlsx' # only supported so fargitrd.export.ITR.data(data.in = df.reports,                       base.file.name = my.basename,                      type.export = my.format,                      format.data = 'long')

The resulting Excel file contains all data available in df.reports.

var vglnk = { key: '949efb41171ac6ec1bf7f206d57e90b8' }; (function(d, t) {var s = d.createElement(t); s.type = 'text/javascript'; s.async = true;s.src = '//cdn.viglink.com/api/vglnk.js';var r = d.getElementsByTagName(t)[0]; r.parentNode.insertBefore(s, r); }(document, 'script'));

To leave a comment for the author, please follow the link and comment on their blog: R and Finance.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

↧

Viewing all articles
Browse latest Browse all 12080

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>