PYield 0.43.4__tar.gz → 0.43.6__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 (69) hide show
  1. {pyield-0.43.4 → pyield-0.43.6}/PKG-INFO +1 -1
  2. pyield-0.43.6/pyield/__about__.py +1 -0
  3. {pyield-0.43.4 → pyield-0.43.6}/pyield/__init__.py +2 -1
  4. {pyield-0.43.4 → pyield-0.43.6}/pyield/anbima/difusao.py +36 -40
  5. pyield-0.43.6/pyield/b3/common.py +161 -0
  6. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/futures/core.py +11 -1
  7. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/futures/historical/historical_b3.py +1 -1
  8. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/price_report.py +16 -5
  9. {pyield-0.43.4 → pyield-0.43.6}/pyield/bc/__init__.py +2 -0
  10. pyield-0.43.6/pyield/bc/copom.py +203 -0
  11. pyield-0.43.6/pyield/selic/__init__.py +14 -0
  12. pyield-0.43.6/pyield/selic/cpm.py +263 -0
  13. pyield-0.43.4/pyield/__about__.py +0 -1
  14. pyield-0.43.4/pyield/b3/common.py +0 -104
  15. {pyield-0.43.4 → pyield-0.43.6}/.gitignore +0 -0
  16. {pyield-0.43.4 → pyield-0.43.6}/LICENSE +0 -0
  17. {pyield-0.43.4 → pyield-0.43.6}/README.md +0 -0
  18. {pyield-0.43.4 → pyield-0.43.6}/pyield/_internal/__init__.py +0 -0
  19. {pyield-0.43.4 → pyield-0.43.6}/pyield/_internal/converters.py +0 -0
  20. {pyield-0.43.4 → pyield-0.43.6}/pyield/_internal/data_cache.py +0 -0
  21. {pyield-0.43.4 → pyield-0.43.6}/pyield/_internal/retry.py +0 -0
  22. {pyield-0.43.4 → pyield-0.43.6}/pyield/_internal/types.py +0 -0
  23. {pyield-0.43.4 → pyield-0.43.6}/pyield/anbima/__init__.py +0 -0
  24. {pyield-0.43.4 → pyield-0.43.6}/pyield/anbima/ettj_intraday.py +0 -0
  25. {pyield-0.43.4 → pyield-0.43.6}/pyield/anbima/ettj_last.py +0 -0
  26. {pyield-0.43.4 → pyield-0.43.6}/pyield/anbima/ima.py +0 -0
  27. {pyield-0.43.4 → pyield-0.43.6}/pyield/anbima/imaq.py +0 -0
  28. {pyield-0.43.4 → pyield-0.43.6}/pyield/anbima/tpf.py +0 -0
  29. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/__init__.py +0 -0
  30. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/di1.py +0 -0
  31. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/di_over.py +0 -0
  32. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/futures/__init__.py +0 -0
  33. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/futures/historical/__init__.py +0 -0
  34. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/futures/historical/core.py +0 -0
  35. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/futures/historical/historical_bmf.py +0 -0
  36. {pyield-0.43.4 → pyield-0.43.6}/pyield/b3/futures/intraday.py +0 -0
  37. {pyield-0.43.4 → pyield-0.43.6}/pyield/bc/auction.py +0 -0
  38. {pyield-0.43.4 → pyield-0.43.6}/pyield/bc/ptax_api.py +0 -0
  39. {pyield-0.43.4 → pyield-0.43.6}/pyield/bc/rates.py +0 -0
  40. {pyield-0.43.4 → pyield-0.43.6}/pyield/bc/repo.py +0 -0
  41. {pyield-0.43.4 → pyield-0.43.6}/pyield/bc/trades_intraday.py +0 -0
  42. {pyield-0.43.4 → pyield-0.43.6}/pyield/bc/trades_monthly.py +0 -0
  43. {pyield-0.43.4 → pyield-0.43.6}/pyield/bc/vna.py +0 -0
  44. {pyield-0.43.4 → pyield-0.43.6}/pyield/bday/__init__.py +0 -0
  45. {pyield-0.43.4 → pyield-0.43.6}/pyield/bday/core.py +0 -0
  46. {pyield-0.43.4 → pyield-0.43.6}/pyield/bday/holidays/br_holidays_new.txt +0 -0
  47. {pyield-0.43.4 → pyield-0.43.6}/pyield/bday/holidays/br_holidays_old.txt +0 -0
  48. {pyield-0.43.4 → pyield-0.43.6}/pyield/bday/holidays/brholidays.py +0 -0
  49. {pyield-0.43.4 → pyield-0.43.6}/pyield/clock.py +0 -0
  50. {pyield-0.43.4 → pyield-0.43.6}/pyield/fwd.py +0 -0
  51. {pyield-0.43.4 → pyield-0.43.6}/pyield/interpolator.py +0 -0
  52. {pyield-0.43.4 → pyield-0.43.6}/pyield/ipca/__init__.py +0 -0
  53. {pyield-0.43.4 → pyield-0.43.6}/pyield/ipca/historical.py +0 -0
  54. {pyield-0.43.4 → pyield-0.43.6}/pyield/ipca/projected.py +0 -0
  55. {pyield-0.43.4 → pyield-0.43.6}/pyield/py.typed +0 -0
  56. {pyield-0.43.4 → pyield-0.43.6}/pyield/rmd.py +0 -0
  57. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/__init__.py +0 -0
  58. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/auctions.py +0 -0
  59. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/benchmark.py +0 -0
  60. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/lft.py +0 -0
  61. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/ltn.py +0 -0
  62. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/ntnb.py +0 -0
  63. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/ntnb1.py +0 -0
  64. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/ntnbprinc.py +0 -0
  65. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/ntnc.py +0 -0
  66. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/ntnf.py +0 -0
  67. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/pre.py +0 -0
  68. {pyield-0.43.4 → pyield-0.43.6}/pyield/tn/tools.py +0 -0
  69. {pyield-0.43.4 → pyield-0.43.6}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyield
3
- Version: 0.43.4
3
+ Version: 0.43.6
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.43.6"
@@ -1,6 +1,6 @@
1
1
  import logging
2
2
 
3
- from pyield import anbima, b3, bc, bday, ipca, tn
3
+ from pyield import anbima, b3, bc, bday, ipca, selic, tn
4
4
  from pyield.__about__ import __version__
5
5
  from pyield.b3 import di1, futures
6
6
  from pyield.clock import now, today
@@ -34,6 +34,7 @@ __all__ = [
34
34
  "pre",
35
35
  "rmd",
36
36
  "bday",
37
+ "selic",
37
38
  ]
38
39
 
39
40
  # Configura o logger do pacote principal com um NullHandler
@@ -1,5 +1,4 @@
1
1
  import datetime as dt
2
- import io
3
2
  import logging
4
3
 
5
4
  import polars as pl
@@ -92,54 +91,56 @@ def _buscar_dados_url(data_referencia: str) -> str:
92
91
  URL_CONSULTA_DADOS, headers=cabecalhos, data=carga, timeout=60
93
92
  )
94
93
  response_consulta.raise_for_status()
95
- except requests.exceptions.RequestException as e:
96
- logger.error(f"Erro ao registrar a data '{data_referencia}' na sessão: {e}")
97
- return ""
98
-
99
- try:
100
94
  response_download = s.post(
101
95
  URL_DOWNLOAD, headers=cabecalhos, data=carga, timeout=60
102
96
  )
103
97
  response_download.raise_for_status()
104
98
  if "text/html" in response_download.headers.get("Content-Type", ""):
105
- logger.error(
106
- "AVISO: O servidor respondeu com HTML em vez de CSV para '%s'.",
107
- data_referencia,
99
+ raise ValueError(
100
+ "Servidor respondeu com HTML em vez de CSV para a data "
101
+ f"{data_referencia}."
108
102
  )
109
- return ""
110
103
  response_download.encoding = "iso-8859-1"
111
104
  return response_download.text
112
105
  except requests.exceptions.RequestException as e:
113
- logger.error(
114
- f"Erro durante o download para a data '{data_referencia}': {e}"
115
- )
116
- return ""
106
+ logger.error(f"Erro ao buscar dados para a data '{data_referencia}': {e}")
107
+ raise
117
108
 
118
109
 
119
- def _processar_csv(csv_data: str) -> pl.DataFrame:
120
- """Converte o CSV bruto em um DataFrame Polars limpo e estruturado."""
110
+ def _extrair_data_referencia_e_csv_limpo(csv_data: str) -> tuple[dt.date, bytes]:
111
+ """Extrai a data de referência do CSV e devolve o conteúdo pronto para leitura."""
121
112
  linhas_csv = csv_data.strip().splitlines()
113
+ if not linhas_csv:
114
+ raise ValueError("CSV vazio ou inválido.")
115
+
116
+ if ":" not in linhas_csv[0]:
117
+ raise ValueError("Cabeçalho do CSV inválido: data de referência ausente.")
122
118
 
123
- # Extrai a data de referência da primeira linha do arquivo
124
119
  data_ref_str = linhas_csv[0].split(":")[1].strip()
125
120
  data_ref = dt.datetime.strptime(data_ref_str, "%d/%m/%Y").date()
126
121
 
127
- # Prepara o conteúdo do CSV para leitura
128
- # O arquivo CSV da Anbima contém um ';' extra no final do cabeçalho.
129
- # Esta linha remove o ';' da última coluna para garantir a leitura correta.
130
- csv_limpo = "\n".join(linhas_csv[1:]).replace(
131
- "Volume Negociado (R$);", "Volume Negociado (R$)"
122
+ # O CSV da Anbima contém ';' extra no fim do cabeçalho.
123
+ # Remove apenas esse caractere para garantir a leitura correta.
124
+ csv_limpo = (
125
+ "\n".join(linhas_csv[1:])
126
+ .replace("Volume Negociado (R$);", "Volume Negociado (R$)")
127
+ .encode()
132
128
  )
133
129
 
130
+ return data_ref, csv_limpo
131
+
132
+
133
+ def _processar_csv(data_ref: dt.date, csv_limpo: bytes) -> pl.DataFrame:
134
+ """Converte o CSV limpo em um DataFrame Polars estruturado."""
134
135
  df = (
135
136
  pl.read_csv(
136
- io.StringIO(csv_limpo),
137
+ csv_limpo,
137
138
  separator=";",
138
139
  decimal_comma=True,
139
140
  schema=ESQUEMA_API,
140
141
  )
141
142
  .rename(ALIAS_COLUNAS)
142
- .with_columns(pl.col(pl.String).str.strip_chars()) # Remove espaços em branco
143
+ .with_columns(cs.string().str.strip_chars()) # Remove espaços em branco
143
144
  .with_columns(
144
145
  pl.col("data_vencimento").str.to_date(format="%d/%m/%Y"),
145
146
  data_referencia=data_ref, # Adiciona a coluna de data de referência
@@ -149,10 +150,7 @@ def _processar_csv(csv_data: str) -> pl.DataFrame:
149
150
  .otherwise(pl.col("horario").str.to_time(format="%H:%M:%S")),
150
151
  taxa_media=pl.mean_horizontal("taxa_compra", "taxa_venda"),
151
152
  )
152
- )
153
-
154
- df = (
155
- df.with_columns(
153
+ .with_columns(
156
154
  bday.count_expr("data_referencia", "data_vencimento").alias("dias_uteis"),
157
155
  # Converte as colunas de taxa de percentual para decimal
158
156
  # São 6 casas decimais no máximo.
@@ -160,6 +158,7 @@ def _processar_csv(csv_data: str) -> pl.DataFrame:
160
158
  cs.starts_with("taxa_").truediv(100).round(8),
161
159
  pl.col("data_referencia")
162
160
  .dt.combine(pl.col("horario"))
161
+ .dt.replace_time_zone("America/Sao_Paulo")
163
162
  .alias("data_hora_referencia"),
164
163
  )
165
164
  .select(ORDEM_COLUNAS_FINAL)
@@ -177,11 +176,15 @@ def tpf_difusao(data_referencia: DateLike) -> pl.DataFrame:
177
176
  data_referencia (DateLike): Data de referência.
178
177
 
179
178
  Returns:
180
- pl.DataFrame: DataFrame com os dados. Retorna um DataFrame vazio se
181
- não houver dados ou em caso de erro.
179
+ pl.DataFrame: DataFrame com os dados.
180
+
181
+ Raises:
182
+ requests.RequestException: Em falhas operacionais de rede ou HTTP.
183
+ ValueError: Em resposta inválida da API ou erro de parsing do CSV.
182
184
 
183
185
  Output Columns:
184
- - data_hora_referencia (datetime): Data e hora de referência da taxa.
186
+ - data_hora_referencia (datetime[America/Sao_Paulo]): Data e hora de
187
+ referência da taxa no fuso horário de São Paulo.
185
188
  - provedor (string): Provedor dos dados.
186
189
  - titulo (string): Nome do título (ex: LFT, LTN).
187
190
  - data_vencimento (date): Data de vencimento do título.
@@ -200,12 +203,5 @@ def tpf_difusao(data_referencia: DateLike) -> pl.DataFrame:
200
203
  data_str = data.strftime("%d/%m/%Y")
201
204
  csv_data = _buscar_dados_url(data_str)
202
205
 
203
- if not csv_data:
204
- logger.warning("Nenhum dado foi retornado para a data '%s'.", data_str)
205
- return pl.DataFrame()
206
-
207
- try:
208
- return _processar_csv(csv_data)
209
- except Exception as e:
210
- logger.error("Falha ao processar o CSV para a data '%s': %s", data_str, e)
211
- return pl.DataFrame()
206
+ data_ref, csv_limpo = _extrair_data_referencia_e_csv_limpo(csv_data)
207
+ return _processar_csv(data_ref, csv_limpo)
@@ -0,0 +1,161 @@
1
+ import datetime as dt
2
+ import logging
3
+
4
+ import polars as pl
5
+
6
+ from pyield import bday, clock
7
+
8
+ registro = logging.getLogger(__name__)
9
+
10
+
11
+ def expr_dv01(
12
+ coluna_dias_uteis: str,
13
+ coluna_taxa: str,
14
+ coluna_preco: str,
15
+ ) -> pl.Expr:
16
+ """Retorna a expressão Polars para cálculo de DV01.
17
+
18
+ Fórmula:
19
+ DV01 = (Duration / (1 + taxa)) * preço * 0,0001
20
+
21
+ Onde:
22
+ - Duration = dias_uteis / 252
23
+ - taxa deve estar em formato decimal (ex.: 0.145)
24
+ - preço é o PU do contrato.
25
+ """
26
+ duracao = pl.col(coluna_dias_uteis) / 252
27
+ duracao_modificada = duracao / (1 + pl.col(coluna_taxa))
28
+ return 0.0001 * duracao_modificada * pl.col(coluna_preco)
29
+
30
+
31
+ _MAPA_MESES: dict[str, int] = {
32
+ "F": 1,
33
+ "G": 2,
34
+ "H": 3,
35
+ "J": 4,
36
+ "K": 5,
37
+ "M": 6,
38
+ "N": 7,
39
+ "Q": 8,
40
+ "U": 9,
41
+ "V": 10,
42
+ "X": 11,
43
+ "Z": 12,
44
+ }
45
+ _MAPA_MESES_STR: dict[str, str] = {k: str(v) for k, v in _MAPA_MESES.items()}
46
+
47
+
48
+ def _corrigir_vencimento_cpm(df: pl.DataFrame, coluna_ticker: str) -> pl.DataFrame:
49
+ """
50
+ Replace ExpirationDate for CPM contracts using the COPOM calendar.
51
+
52
+ CPM options expire on the first business day AFTER the COPOM meeting end date,
53
+ not on the first business day of the meeting month (which is what the generic
54
+ adicionar_vencimento computes). The correct date is fetched from the COPOM
55
+ calendar (pyield.bc.copom.calendar()) using meeting month+year as the join key.
56
+
57
+ If the calendar has no entry for a given meeting (e.g. a very distant future
58
+ meeting not yet in the hardcoded list), the original ExpirationDate is kept.
59
+ """
60
+ from pyield.bc import copom # noqa: PLC0415 (deferred to avoid circular import)
61
+
62
+ cal = copom.calendar().select(
63
+ _meeting_month=pl.col("EndDate").dt.month().cast(pl.Int32),
64
+ _meeting_year=pl.col("EndDate").dt.year().cast(pl.Int32),
65
+ _calendar_expiry=pl.col("ExpiryDate"),
66
+ )
67
+
68
+ df = df.with_columns(
69
+ _meeting_month=(
70
+ pl.col(coluna_ticker)
71
+ .str.slice(3, 1)
72
+ .replace(_MAPA_MESES_STR)
73
+ .cast(pl.Int32, strict=False)
74
+ ),
75
+ _meeting_year=(
76
+ pl.col(coluna_ticker)
77
+ .str.slice(4, 2)
78
+ .cast(pl.Int32, strict=False)
79
+ .add(2000)
80
+ ),
81
+ )
82
+
83
+ df = df.join(cal, on=["_meeting_month", "_meeting_year"], how="left")
84
+
85
+ df = df.with_columns(
86
+ ExpirationDate=pl.when(pl.col("_calendar_expiry").is_not_null())
87
+ .then(pl.col("_calendar_expiry"))
88
+ .otherwise(pl.col("ExpirationDate"))
89
+ )
90
+
91
+ return df.drop("_meeting_month", "_meeting_year", "_calendar_expiry")
92
+
93
+
94
+ def adicionar_vencimento(
95
+ df: pl.DataFrame, codigo_contrato: str, coluna_ticker: str
96
+ ) -> pl.DataFrame:
97
+ """
98
+ Recebe um DataFrame Polars e ADICIONA a coluna 'ExpirationDate'.
99
+
100
+ - Pega a coluna 'coluna_ticker'.
101
+ - Extrai o código de vencimento.
102
+ - Converte para a data "bruta", sem ajuste de feriado.
103
+ - Garante que a data de vencimento é um dia útil.
104
+ - Retorna o DataFrame com a nova coluna ExpirationDate.
105
+
106
+ For CPM contracts specifically, the ExpirationDate is corrected by joining
107
+ against the COPOM calendar (first bday after meeting end), since the generic
108
+ formula (first bday of month) is wrong for CPM.
109
+ """
110
+ dia_vencimento = 15 if "DAP" in codigo_contrato else 1
111
+ df = df.with_columns(
112
+ pl.date(
113
+ # Ano: posição 4-5 (2 dígitos) -> Int -> Soma 2000
114
+ # Funciona para tickers de 6 chars (DI1F25) e 13 chars (CPMF25C100750)
115
+ year=pl.col(coluna_ticker).str.slice(4, 2).cast(pl.Int32, strict=False)
116
+ + 2000,
117
+ # Mês: posição 3 (1 char = código do mês) -> mapeia para Int
118
+ month=pl.col(coluna_ticker)
119
+ .str.slice(3, 1)
120
+ .replace_strict(_MAPA_MESES, default=None, return_dtype=pl.Int8),
121
+ day=dia_vencimento,
122
+ ).alias("ExpirationDate")
123
+ )
124
+ # Garante que a data de vencimento é um dia útil
125
+ df = df.with_columns(ExpirationDate=bday.offset_expr("ExpirationDate", 0))
126
+
127
+ if codigo_contrato == "CPM":
128
+ df = _corrigir_vencimento_cpm(df, coluna_ticker)
129
+
130
+ return df
131
+
132
+
133
+ def data_negociacao_valida(data_negociacao: dt.date) -> bool:
134
+ """Valida se a data de referência é utilizável para consulta.
135
+
136
+ Critérios:
137
+ - Deve ser um dia útil brasileiro.
138
+ - Não pode estar no futuro (maior que a data corrente no Brasil).
139
+
140
+ Retorna True se válida, False caso contrário (e loga um aviso).
141
+ """
142
+ if data_negociacao > clock.today():
143
+ registro.warning(f"A data informada {data_negociacao} está no futuro.")
144
+ return False
145
+ if not bday.is_business_day(data_negociacao):
146
+ registro.warning(f"A data informada {data_negociacao} não é dia útil.")
147
+ return False
148
+
149
+ # Não tem pregão na véspera de Natal e Ano Novo
150
+ datas_fechadas_especiais = { # Datas especiais
151
+ dt.date(data_negociacao.year, 12, 24), # Véspera de Natal
152
+ dt.date(data_negociacao.year, 12, 31), # Véspera de Ano Novo
153
+ }
154
+ if data_negociacao in datas_fechadas_especiais:
155
+ registro.warning(
156
+ "Não há pregão na véspera de Natal e de Ano Novo: "
157
+ f"{data_negociacao}"
158
+ )
159
+ return False
160
+
161
+ return True
@@ -11,7 +11,17 @@ from pyield import clock
11
11
  from pyield._internal.types import DateLike, any_is_empty
12
12
  from pyield.b3.futures.intraday import fetch_intraday_df
13
13
 
14
- OpcoesContrato = Literal["DI1", "DDI", "FRC", "DAP", "DOL", "WDO", "IND", "WIN"]
14
+ OpcoesContrato = Literal[
15
+ "DI1",
16
+ "DDI",
17
+ "FRC",
18
+ "DAP",
19
+ "DOL",
20
+ "WDO",
21
+ "IND",
22
+ "WIN",
23
+ "CPM",
24
+ ]
15
25
  logger = logging.getLogger(__name__)
16
26
 
17
27
 
@@ -88,7 +88,7 @@ def _preprocessar_df(df: pl.DataFrame, codigo_contrato: str) -> pl.DataFrame:
88
88
  """Renomeia e filtra o DataFrame para o contrato desejado."""
89
89
  df = df.rename(MAPA_RENOMEACAO, strict=False).filter(
90
90
  pl.col("TickerSymbol").str.starts_with(codigo_contrato),
91
- pl.col("TickerSymbol").str.len_chars() == 6, # noqa
91
+ pl.col("TickerSymbol").str.len_chars().is_in([6, 13]),
92
92
  )
93
93
 
94
94
  return df
@@ -30,8 +30,11 @@ NAMESPACE_B3 = "urn:bvmf.217.01.xsd"
30
30
  NAMESPACES = {"ns": NAMESPACE_B3}
31
31
  # ZIP válido do price report ~2KB; 1KB detecta arquivos "sem dados"
32
32
  MIN_TAMANHO_ZIP_BYTES = 1024
33
- # Formato de ticker B3: AAAnYY (ex.: DI1F26 = DI1, jan/2026)
34
- TAMANHO_TICKER = 6
33
+ # Comprimentos de ticker B3:
34
+ # - 6 chars: futuros padrão AAAnYY (ex.: DI1F26)
35
+ # - 13 chars: opções sobre futuros AAAnYYTssssss (ex.: CPMF25C100750)
36
+ TAMANHO_TICKER_FUTURO = 6
37
+ TAMANHO_TICKER_OPCAO = 13
35
38
  TICKER_XPATH_TEMPLATE = '//ns:TckrSymb[starts-with(text(), "{asset_code}")]'
36
39
  TRADE_DATE_XPATH = ".//ns:TradDt/ns:Dt"
37
40
  FIN_INSTRM_ATTRBTS_XPATH = ".//ns:FinInstrmAttrbts"
@@ -198,8 +201,16 @@ def _extrair_xml_zip_aninhado(conteudo_zip: bytes) -> bytes:
198
201
  return conteudo_xml
199
202
 
200
203
 
201
- def _extrair_dados_contrato(ticker: _Element) -> dict | None:
202
- if ticker.text is None or len(ticker.text) != TAMANHO_TICKER:
204
+ def _ticker_valido_para_contrato(ticker: str, contract_code: str) -> bool:
205
+ if contract_code == "CPM":
206
+ return len(ticker) == TAMANHO_TICKER_OPCAO
207
+ return len(ticker) == TAMANHO_TICKER_FUTURO
208
+
209
+
210
+ def _extrair_dados_contrato(ticker: _Element, contract_code: str) -> dict | None:
211
+ if ticker.text is None or not _ticker_valido_para_contrato(
212
+ ticker.text, contract_code
213
+ ):
203
214
  return None
204
215
  parent = ticker.getparent()
205
216
  if parent is None:
@@ -245,7 +256,7 @@ def _parsear_xml_registros(xml_bytes: bytes, asset_code: str) -> list[dict]:
245
256
  for ticker in tickers:
246
257
  if not isinstance(ticker, etree._Element):
247
258
  continue
248
- dados_contrato = _extrair_dados_contrato(ticker)
259
+ dados_contrato = _extrair_dados_contrato(ticker, asset_code)
249
260
  if dados_contrato is not None:
250
261
  registros.append(dados_contrato)
251
262
  return registros
@@ -1,3 +1,4 @@
1
+ from pyield.bc import copom
1
2
  from pyield.bc.auction import auctions
2
3
  from pyield.bc.ptax_api import ptax, ptax_series
3
4
  from pyield.bc.rates import (
@@ -15,6 +16,7 @@ from pyield.bc.vna import vna_lft
15
16
 
16
17
  __all__ = [
17
18
  "auctions",
19
+ "copom",
18
20
  "di_over",
19
21
  "di_over_series",
20
22
  "ptax_series",
@@ -0,0 +1,203 @@
1
+ """
2
+ copom — COPOM meeting calendar.
3
+
4
+ Past meetings sourced from the BCB public API (atas endpoint).
5
+ Future meetings for the current cycle are hardcoded from the
6
+ official BCB public note and must be updated each January.
7
+
8
+ BCB API field mapping
9
+ ---------------------
10
+ nroReuniao → MeetingNumber (sequential BCB number)
11
+ dataReferencia → EndDate (last day of the 2-day meeting)
12
+ StartDate derived as EndDate − 1 calendar day (always 2-day meetings)
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import datetime
18
+ import logging
19
+
20
+ import polars as pl
21
+ import requests
22
+
23
+ from pyield import bday, clock
24
+ from pyield._internal.converters import converter_datas
25
+ from pyield._internal.retry import retry_padrao
26
+ from pyield._internal.types import DateLike
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ URL_ATAS = "https://www.bcb.gov.br/api/servico/sitebcb/copom/atas"
31
+
32
+ _SCHEMA_CALENDARIO = {
33
+ "MeetingNumber": pl.Int32,
34
+ "StartDate": pl.Date,
35
+ "EndDate": pl.Date,
36
+ }
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Future meetings — update every January from the official BCB public note
40
+ # Source: https://www.bcb.gov.br/controleinflacao/calendarioreunioescopom
41
+ # ---------------------------------------------------------------------------
42
+ _FUTURE_MEETINGS_2026: list[tuple[datetime.date, datetime.date]] = [
43
+ # (StartDate, EndDate)
44
+ (datetime.date(2026, 1, 27), datetime.date(2026, 1, 28)),
45
+ (datetime.date(2026, 3, 17), datetime.date(2026, 3, 18)),
46
+ (datetime.date(2026, 4, 28), datetime.date(2026, 4, 29)),
47
+ (datetime.date(2026, 6, 16), datetime.date(2026, 6, 17)),
48
+ (datetime.date(2026, 8, 4), datetime.date(2026, 8, 5)),
49
+ (datetime.date(2026, 9, 15), datetime.date(2026, 9, 16)),
50
+ (datetime.date(2026, 11, 3), datetime.date(2026, 11, 4)),
51
+ (datetime.date(2026, 12, 8), datetime.date(2026, 12, 9)),
52
+ ]
53
+
54
+ # Combine all future meetings here. When a new year's calendar is
55
+ # published, add _FUTURE_MEETINGS_{YEAR} and append it to this list.
56
+ _ALL_FUTURE_MEETINGS: list[tuple[datetime.date, datetime.date]] = _FUTURE_MEETINGS_2026
57
+
58
+
59
+ @retry_padrao
60
+ def _chamar_api_atas(quantidade: int = 500) -> list[dict]:
61
+ """Fetch raw COPOM meeting list from the BCB atas API."""
62
+ resposta = requests.get(URL_ATAS, params={"quantidade": quantidade}, timeout=10)
63
+ resposta.raise_for_status()
64
+ return resposta.json().get("conteudo", [])
65
+
66
+
67
+ def _fetch_past_meetings() -> pl.DataFrame:
68
+ """
69
+ Fetch historical COPOM meetings from the BCB atas API.
70
+
71
+ Returns a DataFrame with columns: MeetingNumber, StartDate, EndDate.
72
+ StartDate is derived as EndDate − 1 calendar day (COPOM always meets
73
+ over 2 consecutive days; the exact start is embedded in the title
74
+ field but the simple subtraction is consistent across all records).
75
+ """
76
+ try:
77
+ dados = _chamar_api_atas()
78
+ except Exception:
79
+ logger.exception("Falha ao buscar reuniões do Copom na API do BCB.")
80
+ return pl.DataFrame(schema=_SCHEMA_CALENDARIO)
81
+
82
+ if not dados:
83
+ logger.warning("API do BCB retornou lista vazia para atas do Copom.")
84
+ return pl.DataFrame(schema=_SCHEMA_CALENDARIO)
85
+
86
+ return (
87
+ pl.from_dicts(dados)
88
+ .select(
89
+ MeetingNumber=pl.col("nroReuniao").cast(pl.Int32),
90
+ EndDate=pl.col("dataReferencia").str.to_date("%Y-%m-%d"),
91
+ )
92
+ .with_columns(StartDate=(pl.col("EndDate") - pl.duration(days=1)))
93
+ .select("MeetingNumber", "StartDate", "EndDate")
94
+ )
95
+
96
+
97
+ def _build_future_meetings() -> pl.DataFrame:
98
+ """
99
+ Build a DataFrame of future meetings from _ALL_FUTURE_MEETINGS.
100
+
101
+ MeetingNumber is null (BCB assigns the number after the meeting).
102
+ Only meetings whose EndDate is strictly after today are included,
103
+ so already-past entries in the hardcoded list are silently skipped.
104
+ """
105
+ hoje = clock.today()
106
+ rows = [{"StartDate": s, "EndDate": e} for s, e in _ALL_FUTURE_MEETINGS if e > hoje]
107
+
108
+ if not rows:
109
+ return pl.DataFrame(schema=_SCHEMA_CALENDARIO)
110
+
111
+ return (
112
+ pl.from_dicts(rows)
113
+ .with_columns(MeetingNumber=pl.lit(None, dtype=pl.Int32))
114
+ .select("MeetingNumber", "StartDate", "EndDate")
115
+ )
116
+
117
+
118
+ def calendar(
119
+ start: DateLike | None = None,
120
+ end: DateLike | None = None,
121
+ ) -> pl.DataFrame:
122
+ """
123
+ Return the full COPOM meeting calendar (past + future).
124
+
125
+ Past meetings are fetched live from the BCB API.
126
+ Future meetings come from the hardcoded annual constant.
127
+ Duplicates between the two sources are removed by deduplication
128
+ on EndDate, so there is no need to manually keep the lists in sync.
129
+
130
+ Parameters
131
+ ----------
132
+ start, end : DateLike | None
133
+ Optional inclusive date range filter applied to EndDate.
134
+ None means no bound.
135
+
136
+ Returns
137
+ -------
138
+ pl.DataFrame
139
+ Columns:
140
+ MeetingNumber : Int32 BCB sequential number (null for future)
141
+ StartDate : Date first day of the 2-day meeting
142
+ EndDate : Date last day of the 2-day meeting
143
+ ExpiryDate : Date next Brazilian business day after EndDate
144
+ (= B3 CPM contract settlement/expiry date)
145
+ Rows are sorted by EndDate ascending.
146
+
147
+ Notes
148
+ -----
149
+ ExpiryDate is computed with ``bday.offset_expr("EndDate", 1)``, using
150
+ the Brazilian holiday calendar already embedded in ``pyield.bday``.
151
+
152
+ Examples
153
+ --------
154
+ >>> import pyield as yd
155
+ >>> cal = yd.bc.copom.calendar()
156
+ >>> "ExpiryDate" in cal.columns
157
+ True
158
+ >>> cal["EndDate"].is_sorted()
159
+ True
160
+ """
161
+ past = _fetch_past_meetings()
162
+ future = _build_future_meetings()
163
+
164
+ df = (
165
+ pl.concat([past, future], how="diagonal")
166
+ .unique(subset=["EndDate"])
167
+ .sort("EndDate")
168
+ )
169
+
170
+ # ExpiryDate: next business day after the meeting ends.
171
+ # Vectorized via offset_expr — consistent with the rest of the codebase.
172
+ df = df.with_columns(ExpiryDate=bday.offset_expr("EndDate", 1))
173
+
174
+ # Optional date-range filter on EndDate
175
+ if start is not None:
176
+ start_date = converter_datas(start)
177
+ if start_date is not None:
178
+ df = df.filter(pl.col("EndDate") >= start_date)
179
+ if end is not None:
180
+ end_date = converter_datas(end)
181
+ if end_date is not None:
182
+ df = df.filter(pl.col("EndDate") <= end_date)
183
+
184
+ return df
185
+
186
+
187
+ def next_meeting(reference: DateLike | None = None) -> pl.DataFrame:
188
+ """
189
+ Return the single next COPOM meeting on or after ``reference``.
190
+
191
+ If ``reference`` is None, today's date (Brazil timezone) is used.
192
+ Returns a one-row DataFrame with the same schema as :func:`calendar`.
193
+
194
+ Examples
195
+ --------
196
+ >>> import pyield as yd
197
+ >>> row = yd.bc.copom.next_meeting()
198
+ >>> len(row)
199
+ 1
200
+ """
201
+ ref = clock.today() if reference is None else converter_datas(reference)
202
+ cal = calendar()
203
+ return cal.filter(pl.col("EndDate") >= ref).head(1)
@@ -0,0 +1,14 @@
1
+ """
2
+ selic — Selic-related market data and analytics.
3
+
4
+ Submodules
5
+ ----------
6
+ cpm
7
+ Raw B3 COPOM Digital Option (CPM) contract data.
8
+ probabilities (future)
9
+ Implied COPOM meeting probabilities from CPM prices.
10
+ """
11
+
12
+ from pyield.selic import cpm
13
+
14
+ __all__ = ["cpm"]
@@ -0,0 +1,263 @@
1
+ """
2
+ CPM — B3 COPOM Digital Option contract data.
3
+
4
+ Ticker format: CPM{month_code}{year2}{C|P}{strike_6digits}
5
+ Example: CPMZ25C099500
6
+ ^^^ → prefix "CPM"
7
+ ^ → month code "Z" = December
8
+ ^^ → year "25" = 2025
9
+ ^ → option type "C" = call
10
+ ^^^^^^ → strike "099500" → 99.500
11
+
12
+ Strike interpretation (Selic Meta context):
13
+ strike_float = int(strike_6digits) / 1000 # e.g. 99.500
14
+ change_bps = round((strike_float - 100) * 100) # e.g. -50 bps
15
+
16
+ Month codes (B3 standard futures convention):
17
+ F=1, G=2, H=3, J=4, K=5, M=6,
18
+ N=7, Q=8, U=9, V=10, X=11, Z=12
19
+
20
+ Implementation note
21
+ -------------------
22
+ CPM options expire on the first business day AFTER the COPOM meeting
23
+ ends (ExpiryDate), not on the first business day of the meeting month.
24
+ This module bypasses the generic B3 pipeline (which applies a 6-char
25
+ ticker filter and a DaysToExp > 0 filter, both incorrect for CPM) and
26
+ calls the lower-level price-report helpers directly.
27
+
28
+ ExpiryDate and MeetingEndDate are resolved by joining against the COPOM
29
+ calendar (bc.copom.calendar()) on meeting month + year extracted from
30
+ the ticker. The join is a left join so CPM rows are never dropped even
31
+ if the calendar has gaps for very recently announced future meetings.
32
+ """
33
+
34
+ import logging
35
+
36
+ import polars as pl
37
+
38
+ import pyield._internal.converters as cv
39
+ import pyield.b3.common as cm
40
+ from pyield._internal.retry import DadoIndisponivelError
41
+ from pyield._internal.types import DateLike
42
+ from pyield.b3.price_report import (
43
+ _baixar_zip_url,
44
+ _converter_para_df,
45
+ _extrair_xml_zip_aninhado,
46
+ _mapa_renomeacao_colunas,
47
+ _parsear_xml_registros,
48
+ )
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+ # B3 futures month code → calendar month integer (same mapping as common.py)
53
+ _MONTH_CODES: dict[str, int] = {
54
+ "F": 1,
55
+ "G": 2,
56
+ "H": 3,
57
+ "J": 4,
58
+ "K": 5,
59
+ "M": 6,
60
+ "N": 7,
61
+ "Q": 8,
62
+ "U": 9,
63
+ "V": 10,
64
+ "X": 11,
65
+ "Z": 12,
66
+ }
67
+
68
+ # Polars-compatible replacement map (str → str, cast later)
69
+ _MONTH_CODE_STR: dict[str, str] = {k: str(v) for k, v in _MONTH_CODES.items()}
70
+ _CPM_TICKER_LENGTH = 13
71
+
72
+
73
+ def _empty_schema() -> pl.DataFrame:
74
+ """Return an empty DataFrame with the canonical CPM output schema."""
75
+ return pl.DataFrame(
76
+ schema={
77
+ "TradeDate": pl.Date,
78
+ "TickerSymbol": pl.String,
79
+ "MeetingEndDate": pl.Date,
80
+ "ExpiryDate": pl.Date,
81
+ "OptionType": pl.String,
82
+ "StrikeChangeBps": pl.Int32,
83
+ "SettlementPrice": pl.Float64,
84
+ }
85
+ )
86
+
87
+
88
+ def _parse_ticker(ticker: str) -> tuple[int, int, str, float, int]:
89
+ """
90
+ Parse a CPM ticker string into its components.
91
+
92
+ Returns (month, year, option_type, strike_float, change_bps).
93
+ Raises ValueError for malformed tickers.
94
+
95
+ Examples
96
+ --------
97
+ >>> _parse_ticker("CPMZ25C099500")
98
+ (12, 2025, 'call', 99.5, -50)
99
+
100
+ >>> _parse_ticker("CPMF25C100750")
101
+ (1, 2025, 'call', 100.75, 75)
102
+
103
+ >>> _parse_ticker("CPMH25P100000")
104
+ (3, 2025, 'put', 100.0, 0)
105
+ """
106
+ if len(ticker) != _CPM_TICKER_LENGTH or not ticker.startswith("CPM"):
107
+ raise ValueError(f"Invalid CPM ticker: {ticker!r}")
108
+
109
+ month_code = ticker[3]
110
+ year_str = ticker[4:6]
111
+ opt_char = ticker[6]
112
+ strike_str = ticker[7:13]
113
+
114
+ month = _MONTH_CODES.get(month_code)
115
+ if month is None:
116
+ raise ValueError(f"Unknown month code {month_code!r} in ticker {ticker!r}")
117
+
118
+ year = int(year_str) + 2000
119
+
120
+ if opt_char == "C":
121
+ option_type = "call"
122
+ elif opt_char == "P":
123
+ option_type = "put"
124
+ else:
125
+ raise ValueError(f"Unknown option type {opt_char!r} in ticker {ticker!r}")
126
+
127
+ strike = int(strike_str) / 1000
128
+ change_bps = round((strike - 100) * 100)
129
+
130
+ return month, year, option_type, strike, change_bps
131
+
132
+
133
+ def data(date: DateLike) -> pl.DataFrame:
134
+ """
135
+ Fetch B3 end-of-day CPM contract data for a given trade date.
136
+
137
+ Parameters
138
+ ----------
139
+ date : DateLike
140
+ Trade date. Accepts DD-MM-YYYY, YYYY-MM-DD, datetime.date, etc.
141
+
142
+ Returns
143
+ -------
144
+ pl.DataFrame
145
+ Columns:
146
+ TradeDate : date
147
+ TickerSymbol : str
148
+ MeetingEndDate : date actual COPOM meeting end date (from BCB calendar)
149
+ ExpiryDate : date next business day after MeetingEndDate
150
+ (= B3 CPM contract settlement date)
151
+ OptionType : str "call" or "put"
152
+ StrikeChangeBps: int change in bps vs 100.000 strike
153
+ SettlementPrice: float last traded price in points (0–100)
154
+
155
+ Returns empty DataFrame with correct schema if no CPM data
156
+ exists for the requested date (weekend, holiday, etc.).
157
+
158
+ Examples
159
+ --------
160
+ >>> import pyield as yd
161
+ >>> df = yd.selic.cpm.data("29-01-2025")
162
+ >>> df.is_empty() or set(df.schema.keys()) >= {
163
+ ... "TradeDate",
164
+ ... "TickerSymbol",
165
+ ... "MeetingEndDate",
166
+ ... "ExpiryDate",
167
+ ... "OptionType",
168
+ ... "StrikeChangeBps",
169
+ ... "SettlementPrice",
170
+ ... }
171
+ True
172
+ """
173
+ trade_date = cv.converter_datas(date) if date is not None else None
174
+ if trade_date is None:
175
+ return _empty_schema()
176
+
177
+ if not cm.data_negociacao_valida(trade_date):
178
+ logger.warning(
179
+ "Data %s inválida para CPM. Retornando DataFrame vazio.", trade_date
180
+ )
181
+ return _empty_schema()
182
+
183
+ try:
184
+ zip_data = _baixar_zip_url(trade_date, "SPR")
185
+ xml_bytes = _extrair_xml_zip_aninhado(zip_data)
186
+ records = _parsear_xml_registros(xml_bytes, "CPM")
187
+ except DadoIndisponivelError:
188
+ logger.warning("CPM: dados SPR indisponíveis para %s.", trade_date)
189
+ return _empty_schema()
190
+ except Exception:
191
+ logger.exception("CPM: falha ao baixar SPR para %s.", trade_date)
192
+ return _empty_schema()
193
+
194
+ if not records:
195
+ return _empty_schema()
196
+
197
+ df = _converter_para_df(records)
198
+
199
+ # CPM is not in CONTRATOS_TAXA; suffix → Price (ClosePrice, OpenPrice, …)
200
+ mapa = _mapa_renomeacao_colunas("CPM")
201
+ df = df.rename(mapa, strict=False)
202
+ df = df.with_columns(TradeDate=trade_date)
203
+
204
+ # ClosePrice (← LastPric) is the settlement proxy for CPM options;
205
+ # AdjstdQt is absent in the SPR XML for option contracts.
206
+ price_col = "ClosePrice" if "ClosePrice" in df.columns else "SettlementPrice"
207
+
208
+ # Parse option type (ticker[6]) and strike change (ticker[7:13])
209
+ # entirely with Polars string expressions — no Python loops over rows.
210
+ df = df.with_columns(
211
+ OptionType=pl.col("TickerSymbol")
212
+ .str.slice(6, 1)
213
+ .replace({"C": "call", "P": "put"}),
214
+ # strike_int / 10 − 10_000 ≡ round((strike_int/1000 − 100) * 100)
215
+ # because CPM strikes are multiples of 250 (25 bp increments).
216
+ StrikeChangeBps=(
217
+ pl.col("TickerSymbol")
218
+ .str.slice(7, 6)
219
+ .cast(pl.Int64, strict=False)
220
+ .floordiv(10)
221
+ .sub(10_000)
222
+ .cast(pl.Int32)
223
+ ),
224
+ # Meeting month and year extracted from ticker positions 3 and 4-5.
225
+ # Used as join keys against the COPOM calendar.
226
+ _meeting_month=(
227
+ pl.col("TickerSymbol")
228
+ .str.slice(3, 1)
229
+ .replace(_MONTH_CODE_STR)
230
+ .cast(pl.Int32, strict=False)
231
+ ),
232
+ _meeting_year=(
233
+ pl.col("TickerSymbol")
234
+ .str.slice(4, 2)
235
+ .cast(pl.Int32, strict=False)
236
+ .add(2000)
237
+ ),
238
+ )
239
+
240
+ # Join with COPOM calendar to get MeetingEndDate and the correct ExpiryDate.
241
+ # Import is deferred to avoid a module-level circular dependency risk.
242
+ from pyield.bc import copom # noqa: PLC0415
243
+
244
+ cal = copom.calendar().select(
245
+ _meeting_month=pl.col("EndDate").dt.month().cast(pl.Int32),
246
+ _meeting_year=pl.col("EndDate").dt.year().cast(pl.Int32),
247
+ MeetingEndDate=pl.col("EndDate"),
248
+ ExpiryDate=pl.col("ExpiryDate"),
249
+ )
250
+
251
+ df = df.join(cal, on=["_meeting_month", "_meeting_year"], how="left").drop(
252
+ "_meeting_month", "_meeting_year"
253
+ )
254
+
255
+ return df.select(
256
+ pl.col("TradeDate"),
257
+ pl.col("TickerSymbol"),
258
+ pl.col("MeetingEndDate"),
259
+ pl.col("ExpiryDate"),
260
+ pl.col("OptionType"),
261
+ pl.col("StrikeChangeBps"),
262
+ pl.col(price_col).alias("SettlementPrice"),
263
+ ).sort("ExpiryDate", "StrikeChangeBps")
@@ -1 +0,0 @@
1
- __version__ = "0.43.4"
@@ -1,104 +0,0 @@
1
- import datetime as dt
2
- import logging
3
-
4
- import polars as pl
5
-
6
- from pyield import bday, clock
7
-
8
- registro = logging.getLogger(__name__)
9
-
10
-
11
- def expr_dv01(
12
- coluna_dias_uteis: str,
13
- coluna_taxa: str,
14
- coluna_preco: str,
15
- ) -> pl.Expr:
16
- """Retorna a expressão Polars para cálculo de DV01.
17
-
18
- Fórmula:
19
- DV01 = (Duration / (1 + taxa)) * preço * 0,0001
20
-
21
- Onde:
22
- - Duration = dias_uteis / 252
23
- - taxa deve estar em formato decimal (ex.: 0.145)
24
- - preço é o PU do contrato.
25
- """
26
- duracao = pl.col(coluna_dias_uteis) / 252
27
- duracao_modificada = duracao / (1 + pl.col(coluna_taxa))
28
- return 0.0001 * duracao_modificada * pl.col(coluna_preco)
29
-
30
-
31
- def adicionar_vencimento(
32
- df: pl.DataFrame, codigo_contrato: str, coluna_ticker: str
33
- ) -> pl.DataFrame:
34
- """
35
- Recebe um DataFrame Polars e ADICIONA a coluna 'ExpirationDate'.
36
-
37
- - Pega a coluna 'coluna_ticker'.
38
- - Extrai o código de vencimento.
39
- - Converte para a data "bruta", sem ajuste de feriado.
40
- - Garante que a data de vencimento é um dia útil.
41
- - Retorna o DataFrame com a nova coluna ExpirationDate.
42
- """
43
-
44
- mapa_meses = {
45
- "F": 1,
46
- "G": 2,
47
- "H": 3,
48
- "J": 4,
49
- "K": 5,
50
- "M": 6,
51
- "N": 7,
52
- "Q": 8,
53
- "U": 9,
54
- "V": 10,
55
- "X": 11,
56
- "Z": 12,
57
- }
58
- dia_vencimento = 15 if "DAP" in codigo_contrato else 1
59
- df = df.with_columns(
60
- pl.date(
61
- # Ano: Pega os 2 últimos dígitos -> Int -> Soma 2000
62
- year=pl.col(coluna_ticker).str.slice(-2).cast(pl.Int32, strict=False)
63
- + 2000,
64
- # Mês: Pega 1ª letra -> Mapeia -> Int
65
- month=pl.col(coluna_ticker)
66
- .str.slice(-3, 1)
67
- .replace_strict(mapa_meses, default=None, return_dtype=pl.Int8),
68
- day=dia_vencimento,
69
- ).alias("ExpirationDate")
70
- )
71
- # Garante que a data de vencimento é um dia útil
72
- df = df.with_columns(ExpirationDate=bday.offset_expr("ExpirationDate", 0))
73
- return df
74
-
75
-
76
- def data_negociacao_valida(data_negociacao: dt.date) -> bool:
77
- """Valida se a data de referência é utilizável para consulta.
78
-
79
- Critérios:
80
- - Deve ser um dia útil brasileiro.
81
- - Não pode estar no futuro (maior que a data corrente no Brasil).
82
-
83
- Retorna True se válida, False caso contrário (e loga um aviso).
84
- """
85
- if data_negociacao > clock.today():
86
- registro.warning(f"A data informada {data_negociacao} está no futuro.")
87
- return False
88
- if not bday.is_business_day(data_negociacao):
89
- registro.warning(f"A data informada {data_negociacao} não é dia útil.")
90
- return False
91
-
92
- # Não tem pregão na véspera de Natal e Ano Novo
93
- datas_fechadas_especiais = { # Datas especiais
94
- dt.date(data_negociacao.year, 12, 24), # Véspera de Natal
95
- dt.date(data_negociacao.year, 12, 31), # Véspera de Ano Novo
96
- }
97
- if data_negociacao in datas_fechadas_especiais:
98
- registro.warning(
99
- "Não há pregão na véspera de Natal e de Ano Novo: "
100
- f"{data_negociacao}"
101
- )
102
- return False
103
-
104
- return True
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