-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathREADME.Rmd
232 lines (187 loc) · 7.38 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
---
output: github_document
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
# load README.RData
load("README.RData")
```
# rb3 <img src="man/figures/logo.png" align="right" width="120" alt="rb3" />
<!-- badges: start -->
[](https://www.repostatus.org/#active)
[](https://app.codecov.io/gh/wilsonfreitas/rb3?branch=main)
[](https://github.com/ropensci/rb3/actions)
[](https://CRAN.R-project.org/package=rb3)
[](https://cran.r-project.org/package=rb3)
[](https://github.com/ropensci/software-review/issues/534)
<!-- badges: end -->
## Overview
[B3](https://www.b3.com.br) is the main financial exchange in Brazil, offering access to trading systems for stocks, futures, options, and other financial instruments. The `rb3` package provides tools for downloading, processing, and analyzing market data from B3, including:
- **Stocks & Equities**: Historical price data through COTAHIST files
- **Futures Contracts**: Settlement prices for futures contracts
- **Yield Curves**: Historical yield curves calculated from futures contracts
- **ETFs & BDRs**: Data for Exchange Traded Funds and Brazilian Depositary Receipts
- **REITs (FIIs)**: Data for Brazilian Real Estate Investment Trusts
- **Options**: Equity and index options contracts
- **Market Indices**: B3 indices composition and historical data
The package uses webscraping tools to obtain data directly from [B3's website](https://www.b3.com.br), making it accessible in R as structured datasets. These datasets are valuable for financial analysis, academic research, and investment decision-making.
## Installation
```r
# From CRAN (stable version)
install.packages("rb3")
# Development version from GitHub
if (!require(devtools)) install.packages("devtools")
devtools::install_github("ropensci/rb3")
```
## Basic Usage
### Downloading Data
Execute the following code to download all data you need to start working with `rb3`:
```{r, eval=FALSE}
# Set the rb3.cachedir folder - it must be executed before loading rb3 package
options(rb3.cachedir = "/path/to/your/custom/folder")
library(rb3)
library(bizdays)
# download COTAHIST data from 2000 to 2025
fetch_marketdata("b3-cotahist-yearly", year = 2000:2025)
# download futures settlement prices from 2000 to 2025
fetch_marketdata("b3-futures-settlement-prices", refdate = bizseq("2000-01-01", Sys.Date(), "Brazil/B3"))
# download yield curves from 2018 to 2025
fetch_marketdata("b3-reference-rates",
refdate = bizseq("2018-01-01", Sys.Date(), "Brazil/B3"),
curve_name = c("DIC", "DOC", "PRE")
)
# download indexes composition data - it is necessary to execute `indexes_get()`
fetch_marketdata("b3-indexes-composition")
# download current portfolio for all indexes
fetch_marketdata("b3-indexes-current-portfolio", index = indexes_get(), throttle = TRUE)
# download theoretical portfolio for all indexes
fetch_marketdata("b3-indexes-theoretical-portfolio", index = indexes_get(), throttle = TRUE)
# download historical data for all indexes
fetch_marketdata("b3-indexes-historical-data", index = indexes_get(), year = 2000:2025, throttle = TRUE)
```
### Market Data Templates
The `rb3` package uses a template system to standardize the downloading and processing of different data types. To see available templates:
```{r, eval=TRUE, message=FALSE, warning=FALSE}
library(tidyverse)
library(bizdays)
library(rb3)
# List available templates
list_templates()
```
### Downloading Market Data
The main function for fetching data is `fetch_marketdata()`, which downloads data based on a template and parameters:
```{r, eval=FALSE}
# Download yield curve data for specific dates
fetch_marketdata("b3-reference-rates",
refdate = as.Date("2024-01-31"),
curve_name = "PRE"
)
# Download futures settlement prices
fetch_marketdata("b3-futures-settlement-prices",
refdate = as.Date("2024-01-31")
)
# Download yearly COTAHIST files
fetch_marketdata("b3-cotahist-yearly", year = 2023)
```
### Working with Historical Equity Data
```{r, eval=FALSE}
# Access the data
ch <- cotahist_get("yearly")
# Filter for stocks
eq <- ch |>
filter(year(refdate) == 2023) |>
cotahist_filter_equity() |>
collect()
```
```{r cotahist, eval=TRUE}
# Get top 10 most traded stocks
symbols <- eq |>
group_by(symbol) |>
summarise(volume = sum(volume)) |>
arrange(desc(volume)) |>
head(10) |>
pull(symbol)
# show top 10 most traded stocks
symbols
```
```{r plot-cotahist, eval=TRUE}
# Plot the most traded stocks grouped by month
eq |>
filter(symbol %in% symbols) |>
mutate(refdate = floor_date(refdate, "month")) |>
group_by(refdate, symbol) |>
summarise(volume = sum(volume)) |>
# Plot
ggplot(aes(x = refdate, y = volume, color = symbol)) +
geom_line() +
labs(
title = "Top 10 Most Traded Stocks in 2023",
x = "Date",
y = "Volume"
) +
scale_y_continuous(labels = scales::comma)
```
### Yield Curve Analysis
```{r, eval=FALSE}
# Get Brazilian nominal yield curve (PRE)
yc_data <- yc_brl_get() |>
filter(refdate == "2024-01-31") |>
collect()
```
```{r plot-yc, eval=TRUE}
# Plot the yield curve
ggplot(yc_data, aes(x = forward_date, y = r_252)) +
geom_line() +
labs(
title = "Brazilian Yield Curve (PRE)",
x = "Forward Date",
y = "Annual Interest Rate"
) +
scale_y_continuous(labels = scales::percent)
```
### Futures Contracts
```{r, eval=FALSE}
# Get futures settlement prices
futures_data <- futures_get() |>
filter(commodity == "DI1") |>
collect()
```
```{r plot-futures, eval=TRUE}
# Calculate implied rates
di1_futures <- futures_data |>
mutate(
maturity_date = maturitycode2date(maturity_code),
business_days = bizdays(refdate, maturity_date, "Brazil/ANBIMA"),
implied_rate = (100000 / price)^(252 / business_days) - 1
)
# Plot the implied rates
ggplot(di1_futures, aes(x = maturity_date, y = implied_rate)) +
geom_line() +
geom_point() +
labs(
title = "Implied Rates for DI1 Futures",
x = "Maturity Date",
y = "Implied Rate"
) +
scale_y_continuous(labels = scales::percent)
```
## Documentation
For comprehensive documentation and examples, visit:
- [Package Website](https://ropensci.github.io/rb3/)
- Vignettes (in-depth tutorials):
- [Getting Started](https://ropensci.github.io/rb3/articles/Getting-started.html)
- [Fetching Historical Equity Data](https://ropensci.github.io/rb3/articles/Fetching-historical-equity-data.html)
- [Analyzing B3 Index Data](https://ropensci.github.io/rb3/articles/Fetching-historical-index-data.html)
- [How to Compute Historical Rates from B3 Future Prices](https://ropensci.github.io/rb3/articles/Fetching-historical-future-rates.html)
- [Fetching B3 Yield Curves](https://ropensci.github.io/rb3/articles/Fetching-historical-yield-curve.html)
## Citation
If you use `rb3` in your research, please cite it:
```{r, echo=FALSE, comment=""}
citation("rb3")
```