PYield 0.46.6__tar.gz → 0.46.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. {pyield-0.46.6 → pyield-0.46.8}/PKG-INFO +1 -1
  2. pyield-0.46.8/pyield/__about__.py +1 -0
  3. {pyield-0.46.6 → pyield-0.46.8}/pyield/anbima/__init__.py +0 -2
  4. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/futures/__init__.py +29 -35
  5. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/futures/historical.py +7 -11
  6. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/futures/intraday.py +1 -0
  7. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/intraday_derivatives.py +31 -2
  8. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/price_report.py +29 -42
  9. pyield-0.46.6/pyield/__about__.py +0 -1
  10. pyield-0.46.6/pyield/anbima/difusao.py +0 -163
  11. {pyield-0.46.6 → pyield-0.46.8}/.gitignore +0 -0
  12. {pyield-0.46.6 → pyield-0.46.8}/LICENSE +0 -0
  13. {pyield-0.46.6 → pyield-0.46.8}/README.md +0 -0
  14. {pyield-0.46.6 → pyield-0.46.8}/pyield/__init__.py +0 -0
  15. {pyield-0.46.6 → pyield-0.46.8}/pyield/_internal/__init__.py +0 -0
  16. {pyield-0.46.6 → pyield-0.46.8}/pyield/_internal/br_numbers.py +0 -0
  17. {pyield-0.46.6 → pyield-0.46.8}/pyield/_internal/cache.py +0 -0
  18. {pyield-0.46.6 → pyield-0.46.8}/pyield/_internal/converters.py +0 -0
  19. {pyield-0.46.6 → pyield-0.46.8}/pyield/_internal/data_cache.py +0 -0
  20. {pyield-0.46.6 → pyield-0.46.8}/pyield/_internal/retry.py +0 -0
  21. {pyield-0.46.6 → pyield-0.46.8}/pyield/_internal/types.py +0 -0
  22. {pyield-0.46.6 → pyield-0.46.8}/pyield/anbima/ettj_intraday.py +0 -0
  23. {pyield-0.46.6 → pyield-0.46.8}/pyield/anbima/ettj_last.py +0 -0
  24. {pyield-0.46.6 → pyield-0.46.8}/pyield/anbima/ima.py +0 -0
  25. {pyield-0.46.6 → pyield-0.46.8}/pyield/anbima/imaq.py +0 -0
  26. {pyield-0.46.6 → pyield-0.46.8}/pyield/anbima/tpf.py +0 -0
  27. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/__init__.py +0 -0
  28. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/_contracts.py +0 -0
  29. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/_validar_pregao.py +0 -0
  30. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/di1.py +0 -0
  31. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/di_over.py +0 -0
  32. {pyield-0.46.6 → pyield-0.46.8}/pyield/b3/futures/common.py +0 -0
  33. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/__init__.py +0 -0
  34. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/auction.py +0 -0
  35. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/copom.py +0 -0
  36. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/ptax_api.py +0 -0
  37. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/rates.py +0 -0
  38. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/repo.py +0 -0
  39. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/trades_intraday.py +0 -0
  40. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/trades_monthly.py +0 -0
  41. {pyield-0.46.6 → pyield-0.46.8}/pyield/bc/vna.py +0 -0
  42. {pyield-0.46.6 → pyield-0.46.8}/pyield/bday/__init__.py +0 -0
  43. {pyield-0.46.6 → pyield-0.46.8}/pyield/bday/core.py +0 -0
  44. {pyield-0.46.6 → pyield-0.46.8}/pyield/bday/holidays/br_holidays_new.txt +0 -0
  45. {pyield-0.46.6 → pyield-0.46.8}/pyield/bday/holidays/br_holidays_old.txt +0 -0
  46. {pyield-0.46.6 → pyield-0.46.8}/pyield/bday/holidays/brholidays.py +0 -0
  47. {pyield-0.46.6 → pyield-0.46.8}/pyield/clock.py +0 -0
  48. {pyield-0.46.6 → pyield-0.46.8}/pyield/fwd.py +0 -0
  49. {pyield-0.46.6 → pyield-0.46.8}/pyield/interpolator.py +0 -0
  50. {pyield-0.46.6 → pyield-0.46.8}/pyield/ipca/__init__.py +0 -0
  51. {pyield-0.46.6 → pyield-0.46.8}/pyield/ipca/historical.py +0 -0
  52. {pyield-0.46.6 → pyield-0.46.8}/pyield/ipca/projected.py +0 -0
  53. {pyield-0.46.6 → pyield-0.46.8}/pyield/py.typed +0 -0
  54. {pyield-0.46.6 → pyield-0.46.8}/pyield/rmd.py +0 -0
  55. {pyield-0.46.6 → pyield-0.46.8}/pyield/selic/__init__.py +0 -0
  56. {pyield-0.46.6 → pyield-0.46.8}/pyield/selic/cpm.py +0 -0
  57. {pyield-0.46.6 → pyield-0.46.8}/pyield/selic/probabilities.py +0 -0
  58. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/__init__.py +0 -0
  59. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/auctions.py +0 -0
  60. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/benchmark.py +0 -0
  61. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/lft.py +0 -0
  62. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/ltn.py +0 -0
  63. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/ntnb.py +0 -0
  64. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/ntnb1.py +0 -0
  65. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/ntnbprinc.py +0 -0
  66. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/ntnc.py +0 -0
  67. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/ntnf.py +0 -0
  68. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/pre.py +0 -0
  69. {pyield-0.46.6 → pyield-0.46.8}/pyield/tn/utils.py +0 -0
  70. {pyield-0.46.6 → pyield-0.46.8}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyield
3
- Version: 0.46.6
3
+ Version: 0.46.8
4
4
  Summary: A Python library for analysis of fixed income instruments in Brazil
5
5
  Project-URL: Homepage, https://github.com/crdcj/PYield
6
6
  Project-URL: Documentation, https://crdcj.github.io/PYield
@@ -0,0 +1 @@
1
+ __version__ = "0.46.8"
@@ -1,4 +1,3 @@
1
- from pyield.anbima.difusao import tpf_difusao
2
1
  from pyield.anbima.ettj_intraday import intraday_ettj
3
2
  from pyield.anbima.ettj_last import last_ettj
4
3
  from pyield.anbima.ima import last_ima
@@ -13,5 +12,4 @@ __all__ = [
13
12
  "fetch_tpf",
14
13
  "last_ettj",
15
14
  "intraday_ettj",
16
- "tpf_difusao",
17
15
  ]
@@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)
19
19
  def futures(
20
20
  date: DateLike | ArrayLike,
21
21
  contract_code: str | list[str],
22
- full_report: bool | None = None,
22
+ full_report: bool = False,
23
23
  ) -> pl.DataFrame:
24
24
  """Busca dados de um contrato futuro da B3 para a data de referência.
25
25
 
@@ -28,29 +28,25 @@ def futures(
28
28
  Quando uma coleção é fornecida, os dados são buscados para cada
29
29
  data individualmente e concatenados. Datas inválidas (feriados,
30
30
  fins de semana, futuras) são silenciosamente ignoradas.
31
- contract_code: Código do contrato futuro na B3 ou coleção de códigos.
32
- Exemplos de códigos válidos:
33
- - Juros: DI1, DDI, OC1, DAP, IAP
34
- - Moedas: DOL, WDO, EUR, GBR, JAP, CNY
35
- - Índices: IND, WIN, ISP, WSP
36
- - Commodities: BGI, CCM, ICF, CNL, SJC, SOY, ETH, GLD
37
- full_report: Controla a fonte de dados quando o dado não está no cache.
38
- Se None (padrão) e a data é hoje: entre 09:16 e 19:00 prioriza
39
- dados intraday; a partir das 19:00 prioriza os dados consolidados
40
- (SPR → PR) com intraday como fallback.
41
- Se False, usa o simplified price report (SPR, ~2 KB).
42
- Se True, usa apenas o price report completo (PR, ~2 MB) —
31
+ contract_code: Código do contrato futuro na B3 ou coleção de
32
+ códigos. Aceita qualquer código de contrato futuro listado
33
+ na B3. Contratos com histórico pré-cacheado (desde 2018)
34
+ são retornados instantaneamente:
35
+ - Juros: DI1, DDI, FRC, FRO, DAP
36
+ - Moedas: DOL, WDO
37
+ - Índices: IND, WIN
38
+ Para os demais contratos (OC1, IAP, EUR, GBR, JAP, CNY,
39
+ ISP, WSP, BGI, CCM, ICF, SJC, SOY, ETH, GLD, etc.),
40
+ os dados são baixados diretamente da B3 a cada chamada.
41
+ full_report: Controla a fonte de dados quando o dado não está
42
+ no cache. Se False (padrão), tenta o simplified price
43
+ report (SPR, ~2 KB) primeiro e faz fallback para o price
44
+ report completo (PR, ~2 MB). Se True, usa apenas o PR —
43
45
  indicado para processos batch noturnos.
44
46
 
45
47
  Returns:
46
48
  DataFrame Polars com os dados do contrato informado.
47
49
 
48
- Notes:
49
- Os contratos DI1, DDI, FRC, FRO, DAP, DOL, WDO, IND e WIN possuem
50
- histórico pré-cacheado (desde 2018) e são retornados instantaneamente.
51
- Para os demais contratos, os dados são baixados diretamente da B3 a
52
- cada chamada, o que pode ser mais lento.
53
-
54
50
  Examples:
55
51
  >>> df = futures("31-05-2024", "DI1")
56
52
  >>> df = futures("31-05-2024", "DAP")
@@ -101,7 +97,7 @@ def futures(
101
97
  def _buscar_varias_datas(
102
98
  datas: ArrayLike,
103
99
  codigos: list[str],
104
- full_report: bool | None,
100
+ full_report: bool,
105
101
  ) -> pl.DataFrame:
106
102
  """Busca dados para múltiplas datas e concatena os resultados.
107
103
 
@@ -142,27 +138,25 @@ def _buscar_varias_datas(
142
138
  def _buscar_por_fonte(
143
139
  data: dt.date,
144
140
  codigos: list[str],
145
- full_report: bool | None,
141
+ full_report: bool,
146
142
  ) -> pl.DataFrame:
147
- """Seleciona a fonte de dados com base no horário e parâmetros."""
148
- if full_report is not None or data != clock.today():
143
+ """Seleciona a fonte de dados com base na data e horário.
144
+
145
+ Para datas passadas, usa dados consolidados (historical).
146
+ Para a data de hoje, depende do horário:
147
+ - Antes das 09:16: sem dados disponíveis (DataFrame vazio).
148
+ - Entre 09:16 e 19:00: dados intraday.
149
+ - A partir das 19:00: dados consolidados (historical).
150
+ """
151
+ if data != clock.today():
149
152
  return historical.historical(data, codigos, full_report)
150
153
 
151
154
  horario = clock.now().time()
152
155
  if horario >= HORA_INICIO_CONSOLIDADO:
153
- # Consolidado (SPR → PR) primeiro; intraday como fallback
154
- df = historical.historical(data, codigos, full_report)
155
- if not df.is_empty():
156
- return df
157
- return intraday.intraday(codigos)
158
-
156
+ return historical.historical(data, codigos, full_report)
159
157
  if horario >= HORA_INICIO_INTRADAY:
160
- # Intraday primeiro; historical como fallback
161
- df = intraday.intraday(codigos)
162
- if not df.is_empty():
163
- return df
164
-
165
- return historical.historical(data, codigos, full_report)
158
+ return intraday.intraday(codigos)
159
+ return pl.DataFrame()
166
160
 
167
161
 
168
162
  def available_dates(contract_code: str) -> pl.Series:
@@ -63,16 +63,15 @@ def _obter_pr_normalizado() -> pl.DataFrame:
63
63
  def historical(
64
64
  data: dt.date,
65
65
  codigo_contrato: str | list[str],
66
- full_report: bool | None = None,
66
+ full_report: bool = False,
67
67
  ) -> pl.DataFrame:
68
68
  """Busca histórico de futuros priorizando o dataset PR cacheado.
69
69
 
70
70
  Args:
71
71
  data: Data de negociação.
72
72
  codigo_contrato: Código(s) do contrato futuro na B3.
73
- full_report: Se None (padrão), tenta SPR primeiro e PR como fallback.
74
- Se False, usa o simplified price report (SPR, ~2 KB).
75
- Se True, usa o price report completo (PR, ~2 MB).
73
+ full_report: Se False (padrão), tenta SPR primeiro e PR como
74
+ fallback. Se True, usa apenas o PR completo (~2 MB).
76
75
 
77
76
  Returns:
78
77
  DataFrame Polars com dados históricos de futuros.
@@ -202,16 +201,13 @@ def listar_datas_disponiveis(codigo_contrato: str) -> pl.Series:
202
201
  )
203
202
 
204
203
 
205
- def _buscar_price_report(
206
- data: dt.date, codigo: str, full_report: bool | None
207
- ) -> pl.DataFrame:
204
+ def _buscar_price_report(data: dt.date, codigo: str, full_report: bool) -> pl.DataFrame:
208
205
  """Busca o price report da B3, com fallback SPR→PR.
209
206
 
210
- Quando full_report é True, usa apenas o PR (completo).
211
- Nos demais casos (None ou False), tenta o SPR (leve) primeiro
212
- e faz fallback para o PR se o SPR estiver vazio.
207
+ Se full_report é True, usa apenas o PR (completo).
208
+ Se False, tenta o SPR (leve) primeiro e faz fallback para o PR.
213
209
  """
214
- if full_report is True:
210
+ if full_report:
215
211
  return _normalizar_colunas_pr(
216
212
  fetch_price_report(date=data, contract_code=codigo, full_report=True)
217
213
  )
@@ -87,6 +87,7 @@ def _intraday_contrato(codigo_contrato: str) -> pl.DataFrame:
87
87
  def _preprocessar_df_intraday(df: pl.DataFrame) -> pl.DataFrame:
88
88
  return (
89
89
  df.filter(pl.col("codigo_mercado") == "FUT")
90
+ .drop_nulls(subset=["data_vencimento"])
90
91
  .rename(
91
92
  {
92
93
  "preco_limite_minimo": "taxa_limite_minimo",
@@ -1,3 +1,31 @@
1
+ """Cotações intraday de derivativos da B3 (endpoint DerivativeQuotation).
2
+
3
+ Exemplo de chamada à API:
4
+ https://cotacao.b3.com.br/mds/api/v1/DerivativeQuotation/DI1
5
+
6
+ Exemplo de resposta JSON (resumido):
7
+ {"Scty": [
8
+ {"symb": "DI1J30",
9
+ "desc": "DI DE 1 DIA",
10
+ "asset": {"code": "DI1",
11
+ "AsstSummry": {"mtrtyCode": "2030-04-01",
12
+ "opnCtrcts": 64037,
13
+ "grssAmt": 5272867.79,
14
+ "tradQty": 36,
15
+ "traddCtrctsQty": 89}},
16
+ "mkt": {"cd": "FUT"},
17
+ "SctyQtn": {"curPrc": 14.105, "opngPric": 14.22,
18
+ "minPric": 14.02, "maxPric": 14.22,
19
+ "avrgPric": 14.1013,
20
+ "prvsDayAdjstmntPric": 14.127,
21
+ "bottomLmtPric": 13.16,
22
+ "topLmtPric": 15.385},
23
+ "buyOffer": {"price": 14.105},
24
+ "sellOffer": {"price": 14.13}},
25
+ ...
26
+ ]}
27
+ """
28
+
1
29
  import datetime as dt
2
30
  import logging
3
31
 
@@ -122,6 +150,8 @@ def fetch_intraday_derivatives(contract_code: str) -> pl.DataFrame:
122
150
  * preco_oferta_compra (Float64): melhor oferta de compra (opcional).
123
151
  * preco_oferta_venda (Float64): melhor oferta de venda (opcional).
124
152
  * tipo_lado (String): tipo de lado (opcional).
153
+ * atualizado_as (Datetime): horário aproximado a que o dado se
154
+ refere (horário da consulta menos 15 min de atraso da fonte).
125
155
  """
126
156
  if not intraday_disponivel():
127
157
  return pl.DataFrame()
@@ -133,9 +163,8 @@ def fetch_intraday_derivatives(contract_code: str) -> pl.DataFrame:
133
163
  return (
134
164
  _converter_json_intraday(dados_json)
135
165
  .pipe(_processar_colunas_intraday)
136
- .drop_nulls(subset=["data_vencimento"])
137
166
  .with_columns(
138
167
  atualizado_as=clock.now() - dt.timedelta(minutes=15),
139
168
  )
140
- .sort("codigo_mercado", "codigo_negociacao")
169
+ .sort("codigo_negociacao")
141
170
  )
@@ -43,7 +43,7 @@ COLUNAS_PRICE_REPORT: list[tuple[str, str, type[pl.DataType]]] = [
43
43
  ("3.01.01", "Id", pl.String),
44
44
  ("3.01.02.01", "Prtry", pl.String),
45
45
  ("3.02.01", "MktIdrCd", pl.String),
46
- ("4.01", "DaysToSttlm", pl.String),
46
+ ("4.01", "DaysToSttlm", pl.Int64),
47
47
  ("4.02", "TradQty", pl.Int64),
48
48
  ("5.01", "MktDataStrmId", pl.String),
49
49
  ("5.02", "NtlFinVol", pl.Float64),
@@ -102,27 +102,18 @@ def _baixar_zip_url(data: dt.date, relatorio_completo: bool) -> bytes:
102
102
 
103
103
 
104
104
  def _extrair_xml_de_zip(conteudo_zip: bytes) -> bytes:
105
- """Extrai o XML de um ZIP, suportando ZIP aninhado (ZIP→ZIP→XML) ou simples (ZIP→XML)."""
105
+ """Extrai o XML do ZIP aninhado da B3 (ZIP externo → ZIP interno → XML)."""
106
106
  with zipfile.ZipFile(io.BytesIO(conteudo_zip), "r") as zip_externo:
107
- nomes_externos = zip_externo.namelist()
108
- if not nomes_externos:
107
+ nomes = zip_externo.namelist()
108
+ if not nomes:
109
109
  raise ValueError("ZIP externo está vazio")
110
110
 
111
- # Caso 1: ZIP contém XML diretamente
112
- xml_nomes = [n for n in nomes_externos if n.endswith(".xml")]
113
- if xml_nomes:
114
- xml_nomes.sort()
115
- return zip_externo.read(xml_nomes[-1])
116
-
117
- # Caso 2: ZIP aninhado — o primeiro arquivo interno é outro ZIP
118
- conteudo_interno = zip_externo.read(nomes_externos[0])
119
-
120
- with zipfile.ZipFile(io.BytesIO(conteudo_interno), "r") as zip_interno:
121
- xml_nomes = [n for n in zip_interno.namelist() if n.endswith(".xml")]
122
- if not xml_nomes:
123
- raise ValueError("Nenhum XML encontrado no ZIP")
124
- xml_nomes.sort()
125
- return zip_interno.read(xml_nomes[-1])
111
+ conteudo_interno = zip_externo.read(nomes[0])
112
+ with zipfile.ZipFile(io.BytesIO(conteudo_interno), "r") as zip_interno:
113
+ nomes_xml = sorted(n for n in zip_interno.namelist() if n.endswith(".xml"))
114
+ if not nomes_xml:
115
+ raise ValueError("Nenhum XML encontrado no ZIP interno")
116
+ return zip_interno.read(nomes_xml[-1])
126
117
 
127
118
 
128
119
  def _ticker_valido_para_contrato(ticker: str, codigo_contrato: str) -> bool:
@@ -219,7 +210,14 @@ def _obter_xml_price_report(data: dt.date, relatorio_completo: bool) -> bytes:
219
210
  dados_zip = _baixar_zip_url(data, relatorio_completo)
220
211
  if not dados_zip:
221
212
  return bytes()
222
- return _extrair_xml_de_zip(dados_zip)
213
+ try:
214
+ return _extrair_xml_de_zip(dados_zip)
215
+ except zipfile.BadZipFile:
216
+ registro.warning("ZIP corrompido na transmissão, re-baixando...")
217
+ dados_zip = _baixar_zip_url(data, relatorio_completo)
218
+ if not dados_zip:
219
+ return bytes()
220
+ return _extrair_xml_de_zip(dados_zip)
223
221
 
224
222
 
225
223
  def fetch_price_report(
@@ -264,7 +262,7 @@ def fetch_price_report(
264
262
  * Id (String): identificador do instrumento.
265
263
  * Prtry (String): tipo do identificador proprietário.
266
264
  * MktIdrCd (String): código do mercado.
267
- * DaysToSttlm (String): dias para liquidação.
265
+ * DaysToSttlm (Int64): dias para liquidação.
268
266
  * TradQty (Int64): número de negócios.
269
267
  * MktDataStrmId (String): identificador do fluxo de dados.
270
268
  * NtlFinVol (Float64): volume financeiro nacional bruto.
@@ -303,9 +301,8 @@ def fetch_price_report(
303
301
 
304
302
  Raises:
305
303
  requests.HTTPError: Se a requisição HTTP ao endpoint falhar.
306
- zipfile.BadZipFile: Se o arquivo ZIP recebido estiver corrompido.
304
+ zipfile.BadZipFile: Se o ZIP estiver corrompido após re-download.
307
305
  etree.XMLSyntaxError: Se o XML recebido estiver malformado.
308
- Exception: Erros críticos inesperados são propagados após log.
309
306
 
310
307
  Examples:
311
308
  >>> import pyield as yd
@@ -328,25 +325,15 @@ def fetch_price_report(
328
325
  if not data_negociacao_valida(date):
329
326
  return pl.DataFrame()
330
327
 
331
- try:
332
- xml_bytes = _obter_xml_price_report(date, full_report)
333
- dataframes = []
334
- for contrato in contratos:
335
- df = _processar_xml_extraido(xml_bytes, contrato)
336
- if not df.is_empty():
337
- dataframes.append(df)
338
- if not dataframes:
339
- return pl.DataFrame()
340
- return pl.concat(dataframes, how="diagonal").sort("TckrSymb")
341
- except (zipfile.BadZipFile, etree.XMLSyntaxError):
342
- registro.exception(f"Falha ao parsear o price report de {contratos} em {date}.")
343
- raise
344
- except Exception:
345
- tipo = "PR" if full_report else "SPR"
346
- registro.exception(
347
- f"ERRO CRÍTICO: Falha ao processar {contratos} {tipo} em {date}"
348
- )
349
- raise
328
+ xml_bytes = _obter_xml_price_report(date, full_report)
329
+ dataframes = []
330
+ for contrato in contratos:
331
+ df = _processar_xml_extraido(xml_bytes, contrato)
332
+ if not df.is_empty():
333
+ dataframes.append(df)
334
+ if not dataframes:
335
+ return pl.DataFrame()
336
+ return pl.concat(dataframes, how="diagonal").sort("TckrSymb")
350
337
 
351
338
 
352
339
  def read_price_report(
@@ -1 +0,0 @@
1
- __version__ = "0.46.6"
@@ -1,163 +0,0 @@
1
- import datetime as dt
2
- import logging
3
-
4
- import polars as pl
5
- import requests
6
-
7
- import pyield._internal.converters as cv
8
- from pyield import bday
9
- from pyield._internal.br_numbers import taxa_br
10
- from pyield._internal.cache import ttl_cache
11
- from pyield._internal.types import DateLike, any_is_empty
12
-
13
- VERSAO_API = "1.0018"
14
- URL_BASE = (
15
- f"https://www.anbima.com.br/sistemas/taxasonline/consulta/versao/{VERSAO_API}"
16
- )
17
-
18
- URL_PAGINA_INICIAL = f"{URL_BASE}/taxasOnline.asp"
19
- URL_CONSULTA_DADOS = f"{URL_BASE}/exibedados.asp"
20
- URL_DOWNLOAD = f"{URL_BASE}/download_dados.asp?extensao=csv"
21
-
22
- logger = logging.getLogger(__name__)
23
-
24
-
25
- @ttl_cache()
26
- def _buscar_dados_url(data_referencia: str) -> bytes:
27
- cabecalhos = {
28
- "Referer": URL_PAGINA_INICIAL,
29
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", # noqa
30
- "Origin": "https://www.anbima.com.br",
31
- "Content-Type": "application/x-www-form-urlencoded",
32
- }
33
- carga = {
34
- "dataref": data_referencia,
35
- "dtRefIdioma": data_referencia,
36
- "layoutimprimir": "0",
37
- "idioma": "",
38
- "idresumo": "",
39
- "nome": "",
40
- "provedor": "",
41
- "codigo": "",
42
- "vencimento": "",
43
- "referencia": "",
44
- "dbNome": "",
45
- "fldColunas": ["C2", "C17", "C18", "C19"],
46
- }
47
-
48
- # Timeouts (conexão, leitura) ajustados ao perfil de cada request:
49
- # - GET inicial: página leve, apenas para estabelecer cookies de sessão.
50
- # - POST consulta: dispara a query no servidor (~30s observado em uso normal).
51
- # - POST download: dados já preparados pelo POST anterior, resposta rápida.
52
- timeout_pagina = (10, 20)
53
- timeout_consulta = (10, 120)
54
- timeout_download = (10, 30)
55
-
56
- with requests.Session() as s:
57
- s.get(URL_PAGINA_INICIAL, headers=cabecalhos, timeout=timeout_pagina)
58
- try:
59
- response_consulta = s.post(
60
- URL_CONSULTA_DADOS,
61
- headers=cabecalhos,
62
- data=carga,
63
- timeout=timeout_consulta,
64
- )
65
- response_consulta.raise_for_status()
66
- response_download = s.post(
67
- URL_DOWNLOAD,
68
- headers=cabecalhos,
69
- data=carga,
70
- timeout=timeout_download,
71
- )
72
- response_download.raise_for_status()
73
- if "text/html" in response_download.headers.get("Content-Type", ""):
74
- raise ValueError(
75
- "Servidor respondeu com HTML em vez de CSV para a data "
76
- f"{data_referencia}."
77
- )
78
- response_download.encoding = "iso-8859-1"
79
- return response_download.text.encode("utf-8")
80
- except requests.exceptions.RequestException as e:
81
- logger.error(f"Erro ao buscar dados para a data '{data_referencia}': {e}")
82
- raise
83
-
84
-
85
- def _ler_csv_bruto(csv_bruto: bytes) -> pl.DataFrame:
86
- """Lê o CSV bruto da Anbima e devolve DataFrame com todas as colunas string."""
87
- return pl.read_csv(
88
- csv_bruto,
89
- separator=";",
90
- infer_schema=False,
91
- skip_rows=1,
92
- ).with_columns(pl.all().str.strip_chars())
93
-
94
-
95
- def _processar_csv(data_ref: dt.date, df: pl.DataFrame) -> pl.DataFrame:
96
- """Converte o DataFrame bruto em DataFrame Polars estruturado."""
97
-
98
- return (
99
- df.with_columns(
100
- data_vencimento=pl.col("Vencimento").str.to_date(format="%d/%m/%Y"),
101
- horario=pl.when(pl.col("Provedor") == "ANBIMA 12H")
102
- .then(dt.time(12, 0))
103
- .otherwise(pl.col("Horário").str.to_time(format="%H:%M:%S")),
104
- taxa_venda=taxa_br("Oferta Venda"),
105
- taxa_compra=taxa_br("Oferta Compra"),
106
- )
107
- .select(
108
- data_hora_referencia=pl.lit(data_ref).dt.combine(pl.col("horario")),
109
- provedor=pl.col("Provedor"),
110
- titulo=pl.col("Título"),
111
- data_vencimento=pl.col("data_vencimento"),
112
- isin=pl.col("Código ISIN"),
113
- dias_uteis=bday.count_expr(data_ref, "data_vencimento"),
114
- taxa_indicativa_anterior=taxa_br("Fech D-1"),
115
- taxa_indicativa_superior=taxa_br("Indicativo Superior"),
116
- taxa_indicativa_inferior=taxa_br("Indicativo Inferior"),
117
- taxa_venda=pl.col("taxa_venda"),
118
- taxa_compra=pl.col("taxa_compra"),
119
- taxa_media=pl.mean_horizontal("taxa_compra", "taxa_venda"),
120
- taxa_ultima=taxa_br("Última"),
121
- )
122
- .sort("titulo", "data_vencimento", "data_hora_referencia")
123
- )
124
-
125
-
126
- def tpf_difusao(data_referencia: DateLike) -> pl.DataFrame:
127
- """
128
- Obtém a TPF Difusão da Anbima para uma data de referência específica.
129
-
130
- Args:
131
- data_referencia (DateLike): Data de referência.
132
-
133
- Returns:
134
- pl.DataFrame: DataFrame com os dados.
135
-
136
- Raises:
137
- requests.RequestException: Em falhas operacionais de rede ou HTTP.
138
- ValueError: Em resposta inválida da API ou erro de parsing do CSV.
139
-
140
- Output Columns:
141
- - data_hora_referencia (Datetime): Data e hora de referência da taxa.
142
- - provedor (string): Provedor dos dados.
143
- - titulo (string): Nome do título (ex: LFT, LTN).
144
- - data_vencimento (date): Data de vencimento do título.
145
- - isin (string): código ISIN do título.
146
- - dias_uteis (int): Dias úteis entre a data de referência e o vencimento.
147
- - taxa_indicativa_anterior (float): Taxa indicativa de fechamento D-1 (decimal).
148
- - taxa_indicativa_superior (float): Limite superior da banda indicativa (decimal).
149
- - taxa_indicativa_inferior (float): Limite inferior da banda indicativa (decimal).
150
- - taxa_venda (float): Taxa de oferta de venda (Ask rate) (decimal).
151
- - taxa_compra (float): Taxa de oferta de compra (Bid rate) (decimal).
152
- - taxa_media (float): Média entre a taxa de compra e venda (decimal).
153
- - taxa_ultima (float): Última taxa negociada (decimal).
154
- """
155
- if any_is_empty(data_referencia):
156
- return pl.DataFrame()
157
- data = cv.converter_datas(data_referencia)
158
- if not bday.is_business_day(data):
159
- return pl.DataFrame()
160
- data_str = data.strftime("%d/%m/%Y")
161
- csv_bruto = _buscar_dados_url(data_str)
162
- df = _ler_csv_bruto(csv_bruto)
163
- return _processar_csv(data, df)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes