-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathscraper-indexes.R
319 lines (304 loc) · 9.39 KB
/
scraper-indexes.R
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#' Get composition of B3 indexes
#'
#' Gets the composition of listed B3 indexes.
#'
#' @param index_name a string with the index name
#' @param cache_folder Location of cache folder (default = cachedir())
#' @param do_cache Whether to use cache or not (default = TRUE)
#'
#' @return a character vector with symbols that belong to the given index name
#'
#' @examples
#' \dontrun{
#' index_comp_get("IBOV")
#' }
#' @export
index_comp_get <- function(index_name,
cache_folder = cachedir(),
do_cache = TRUE) {
f <- download_marketdata("GetTheoricalPortfolio", cache_folder, do_cache,
index_name = index_name
)
df <- read_marketdata(
f, "GetTheoricalPortfolio", TRUE,
do_cache
)
df$Results$code
}
#' Get the assets weights of B3 indexes
#'
#' Gets the assets weights of B3 indexes.
#'
#' @param index_name a string with the index name
#' @param cache_folder Location of cache folder (default = cachedir())
#' @param do_cache Whether to use cache or not (default = TRUE)
#'
#' @return
#' data.frame with symbols that belong to the given index name with its weights
#' and theoretical positions.
#'
#' @examples
#' \dontrun{
#' index_weights_get("IBOV")
#' }
#' @export
index_weights_get <- function(index_name,
cache_folder = cachedir(),
do_cache = TRUE) {
f <- download_marketdata("GetTheoricalPortfolio", cache_folder, do_cache,
index_name = index_name
)
df <- read_marketdata(
f, "GetTheoricalPortfolio", TRUE,
do_cache
)
ds <- df$Results[, c("code", "part", "theoricalQty")]
colnames(ds) <- c("symbol", "weight", "position")
ds$weight <- ds$weight / 100
ds
}
#' Get the date of indexes composition last update
#'
#' Gets the date where the indexes have been updated lastly.
#'
#' @param cache_folder Location of cache folder (default = cachedir())
#' @param do_cache Whether to use cache or not (default = TRUE)
#'
#' @return the Date when the indexes have been updated
#'
#' @examples
#' \dontrun{
#' indexes_last_update()
#' }
#' @export
indexes_last_update <- function(cache_folder = cachedir(),
do_cache = TRUE) {
f <- download_marketdata("GetStockIndex",
cache_folder = cache_folder, do_cache = do_cache
)
df <- read_marketdata(f, "GetStockIndex", do_cache = do_cache)
df$Header$update
}
#' Get B3 indexes available
#'
#' Gets B3 indexes available.
#'
#' @param cache_folder Location of cache folder (default = cachedir())
#' @param do_cache Whether to use cache or not (default = TRUE)
#'
#' @return a character vector with symbols of indexes available
#'
#' @examples
#' \dontrun{
#' indexes_get()
#' }
#' @export
indexes_get <- function(cache_folder = cachedir(),
do_cache = TRUE) {
f <- download_marketdata("GetStockIndex",
cache_folder = cache_folder, do_cache = do_cache
)
df <- read_marketdata(f, "GetStockIndex", do_cache = do_cache)
str_split(df$Results$indexes, ",") |>
unlist() |>
unique() |>
sort()
}
#' Get B3 indexes available
#'
#' Gets B3 indexes available.
#'
#' @param index_name a string with the index name
#' @param cache_folder Location of cache folder (default = cachedir())
#' @param do_cache Whether to use cache or not (default = TRUE)
#'
#' @return
#' A dataframe with the index stocks, their weights, segments and positions.
#'
#' @examples
#' \dontrun{
#' index_by_segment_get("IBOV")
#' }
#' @export
index_by_segment_get <- function(index_name,
cache_folder = cachedir(),
do_cache = TRUE) {
f <- download_marketdata("GetPortfolioDay",
cache_folder = cache_folder,
do_cache = do_cache,
index_name = index_name
)
pp <- read_marketdata(f, "GetPortfolioDay", do_cache = do_cache)
df <- pp$Results[, c("code", "segment", "part", "part_acum", "theoricalQty")]
colnames(df) <- c("symbol", "segment", "weight", "segment_weight", "position")
df$weight <- df$weight / 100
df$segment_weight <- df$segment_weight / 100
df$refdate <- pp$Header$date
df
}
#' Fetches indexes data from B3
#'
#' Downloads index data from B3 website
#' <https://www.b3.com.br/pt_br/market-data-e-indices/servicos-de-dados/market-data/historico/boletins-diarios/pesquisa-por-pregao/pesquisa-por-pregao/>.
#'
#' @param refdate Specific date ("YYYY-MM-DD") to `yc_get` single curve
#' @param first_date First date ("YYYY-MM-DD") to `yc_mget` multiple curves
#' @param last_date Last date ("YYYY-MM-DD") to `yc_mget` multiple curves
#' @param by Number of days in between fetched dates (default = 1) in `yc_mget`
#' @param cache_folder Location of cache folder (default = cachedir())
#' @param do_cache Whether to use cache or not (default = TRUE)
#'
#' @details
#' `indexreport_get` returns index data for the given date and
#' `indexreport_mget` returns index data for a given range of dates.
#'
#' @return
#' A dataframe with index data (OHLC, average and daily oscillation)
#'
#' @name indexreport_get
#'
#' @examples
#' \dontrun{
#' df_ir <- indexreport_mget(Sys.Date() - 5, Sys.Date())
#' head(df_ir)
#' }
#' @export
indexreport_mget <- function(first_date = Sys.Date() - 5,
last_date = Sys.Date(),
by = 1,
cache_folder = cachedir(),
do_cache = TRUE) {
first_date <- as.Date(first_date)
last_date <- as.Date(last_date)
tpl <- template_retrieve("IndexReport")
date_vec <- bizseq(first_date, last_date, tpl$calendar)
date_vec <- date_vec[seq(1, length(date_vec), by = by)]
bind_rows(
log_map_process_along(date_vec, get_single_indexreport,
"Fetching data points",
date_vec = date_vec,
cache_folder = cache_folder,
do_cache = do_cache
)
)
}
#' @rdname indexreport_get
#' @examples
#' \dontrun{
#' df_ir <- indexreport_get(Sys.Date())
#' head(df_ir)
#' }
#' @export
indexreport_get <- function(refdate = Sys.Date(),
cache_folder = cachedir(),
do_cache = TRUE) {
get_single_indexreport(1, as.Date(refdate), cache_folder, do_cache)
}
get_single_indexreport <- function(idx_date,
date_vec,
cache_folder,
do_cache) {
df <- get_single_marketdata(
"IndexReport", idx_date, date_vec, cache_folder, do_cache
)
if (!is.null(df)) {
cols <- c(
"refdate", "symbol", "open", "high", "low", "close", "average",
"oscillation"
)
df[, cols]
} else {
NULL
}
}
ibovespa_index_get <- function(first_date, last_date = as.Date("1997-12-31")) {
f <- system.file("extdata/IBOV.rds", package = "rb3")
read_rds(f) |> filter(.data$refdate >= first_date, .data$refdate <= last_date)
}
single_index_get <- function(index_name, year, cache_folder, do_cache) {
template <- "GetPortfolioDay_IndexStatistics"
f <- download_marketdata(template,
index_name = index_name, year = year,
cache_folder = cache_folder, do_cache = do_cache
)
index_data <- read_marketdata(f, template, do_cache = do_cache)
if (is.null(index_data)) {
return(NULL)
}
day <- index_data$Results$day
months <- index_data$Results |>
select("month01":"month12") |>
as.list()
months_dfs <- names(months) |>
lapply(function(m) {
month <- as.integer(str_match(m, "\\d\\d")[1])
data.frame(year, month, day, value = months[[m]])
})
index_data <- do.call(rbind, months_dfs) |>
mutate(
refdate = ISOdate(.data$year, .data$month, .data$day) |> as.Date(),
index_name = index_name
) |>
filter(!is.na(.data$value)) |>
arrange("refdate")
index_data |> select("refdate", "index_name", "value")
}
#' Get index historical data
#'
#' Gets historical data from B3 indexes
#'
#' @param index_name a string with the index name
#' @param first_date First date
#' @param last_date Last date
#' @param cache_folder Location of cache folder (default = cachedir())
#' @param do_cache Whether to use cache or not (default = TRUE)
#'
#' @return A data.frame/tibble with index data
#'
#' @examples
#' \dontrun{
#' index_get("IBOV", as.Date("1977-01-01"), as.Date("1999-12-31"))
#' }
#'
#' @export
index_get <- function(index_name, first_date,
last_date = Sys.Date(),
cache_folder = cachedir(),
do_cache = TRUE) {
start_year <- format(first_date, "%Y") |> as.integer()
end_year <- format(last_date, "%Y") |> as.integer()
if (index_name == "IBOV") {
if (start_year > 1997) {
year <- seq(start_year, end_year)
map_dfr(year, \(year) single_index_get(
index_name, year, cache_folder,
do_cache
))
} else {
if (end_year <= 1997) {
df <- ibovespa_index_get(first_date, last_date)
} else {
df1 <- ibovespa_index_get(first_date, as.Date("1997-12-31"))
year <- seq(1998, end_year)
df2 <- map_dfr(year, \(year) single_index_get(
index_name, year,
cache_folder, do_cache
)) |>
filter(.data$refdate <= last_date)
df <- bind_rows(df1, df2) |> arrange("refdate")
}
}
} else {
year <- seq(start_year, end_year)
df <- map_dfr(year, \(year) single_index_get(
index_name, year,
cache_folder, do_cache
))
if (any(dim(df) == 0)) {
return(NULL)
} else {
df |>
filter(.data$refdate <= last_date, .data$refdate >= first_date)
}
}
}