PYield 0.37.4__tar.gz → 0.37.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.
- {pyield-0.37.4 → pyield-0.37.6}/PKG-INFO +1 -1
- pyield-0.37.6/pyield/__about__.py +1 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/anbima/ettj.py +109 -47
- {pyield-0.37.4 → pyield-0.37.6}/pyield/anbima/tpf.py +56 -38
- {pyield-0.37.4 → pyield-0.37.6}/pyield/b3/di1.py +8 -5
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/benchmark.py +78 -59
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/lft.py +6 -15
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/ltn.py +6 -14
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/ntnb.py +6 -15
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/ntnc.py +4 -3
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/ntnf.py +6 -7
- pyield-0.37.4/pyield/__about__.py +0 -1
- {pyield-0.37.4 → pyield-0.37.6}/.gitignore +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/LICENSE +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/README.md +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/__init__.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/anbima/__init__.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/anbima/ima.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/anbima/imaq.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/anbima/ipca.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/b3/__init__.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/b3/di_over.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/b3/futures/__init__.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/b3/futures/common.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/b3/futures/historical.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/b3/futures/intraday.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/b3/futures/xml.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bc/__init__.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bc/auction.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bc/ptax_api.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bc/rates.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bc/repo.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bc/trades_intraday.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bc/trades_monthly.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bc/vna.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/bday.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/conftest.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/data_cache.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/date_converter.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/fwd.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/holidays/__init__.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/holidays/br_holidays_new.txt +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/holidays/br_holidays_old.txt +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/holidays/brholidays.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/ibge/__init__.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/ibge/ipca.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/interpolator.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/py.typed +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/retry.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/__init__.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/pre.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyield/tn/tools.py +0 -0
- {pyield-0.37.4 → pyield-0.37.6}/pyproject.toml +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.37.6"
|
|
@@ -18,7 +18,7 @@ ROUND_DIGITS = 6
|
|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
@default_retry
|
|
21
|
-
def
|
|
21
|
+
def _get_last_content_text() -> str:
|
|
22
22
|
"""Fetches the raw yield curve data from ANBIMA."""
|
|
23
23
|
request_payload = {
|
|
24
24
|
"Idioma": "PT",
|
|
@@ -30,34 +30,47 @@ def _get_last_content() -> str:
|
|
|
30
30
|
return r.text
|
|
31
31
|
|
|
32
32
|
|
|
33
|
-
def
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
33
|
+
def _get_reference_date(text: str) -> pd.Timestamp:
|
|
34
|
+
file_date_str = text[0:10] # formato = 09/09/2024
|
|
35
|
+
file_date = pd.to_datetime(file_date_str, format="%d/%m/%Y")
|
|
36
|
+
return file_date
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _filter_ettf_text(texto_completo: str) -> str:
|
|
40
|
+
# Definir os marcadores de início e fim
|
|
41
|
+
marcador_inicio = "Vertices;ETTJ IPCA;ETTJ PREF;Inflação Implícita"
|
|
42
|
+
marcador_fim = "PREFIXADOS (CIRCULAR 3.361)"
|
|
43
|
+
|
|
44
|
+
# 2. Dividir o texto em uma lista de linhas
|
|
45
|
+
linhas = texto_completo.strip().splitlines()
|
|
46
|
+
|
|
47
|
+
# 3. Encontrar os índices das linhas de início e fim
|
|
48
|
+
indice_inicio = linhas.index(marcador_inicio)
|
|
49
|
+
indice_fim = linhas.index(marcador_fim)
|
|
50
|
+
|
|
51
|
+
# 4. Fatiar a lista para extrair o trecho desejado
|
|
52
|
+
trecho_filtrado = linhas[indice_inicio:indice_fim]
|
|
53
|
+
|
|
54
|
+
# Remover linhas vazias que possam ter sido incluídas no final
|
|
55
|
+
while trecho_filtrado and not trecho_filtrado[-1].strip():
|
|
56
|
+
trecho_filtrado.pop()
|
|
42
57
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
csv_buffer = StringIO()
|
|
58
|
+
# 5. Juntar as linhas filtradas em um único texto e retornar
|
|
59
|
+
return "\n".join(trecho_filtrado)
|
|
46
60
|
|
|
47
|
-
# Save the DataFrame as CSV in memory buffer to be read again
|
|
48
|
-
# It's easier than handling values with commas and dots directly in the DataFrame
|
|
49
|
-
raw_df.to_csv(csv_buffer, index=False)
|
|
50
|
-
csv_buffer.seek(0) # Move the buffer cursor to the beginning
|
|
51
61
|
|
|
62
|
+
def _convert_text_to_df(text: str, reference_date: pd.Timestamp) -> pd.DataFrame:
|
|
63
|
+
"""Converts the raw yield curve text to a DataFrame."""
|
|
52
64
|
df = pd.read_csv(
|
|
53
|
-
|
|
65
|
+
StringIO(text),
|
|
66
|
+
sep=";",
|
|
54
67
|
decimal=",",
|
|
55
68
|
thousands=".",
|
|
56
|
-
|
|
69
|
+
encoding="latin1",
|
|
70
|
+
dtype_backend="pyarrow",
|
|
57
71
|
)
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
df["date"] = file_date
|
|
72
|
+
df["date"] = reference_date
|
|
73
|
+
df["date"] = df["date"].astype("date32[pyarrow]")
|
|
61
74
|
|
|
62
75
|
return df
|
|
63
76
|
|
|
@@ -85,9 +98,7 @@ def _process_df(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
85
98
|
"real_rate",
|
|
86
99
|
"implied_inflation",
|
|
87
100
|
]
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return df
|
|
101
|
+
return df[column_order].copy()
|
|
91
102
|
|
|
92
103
|
|
|
93
104
|
def last_ettj() -> pd.DataFrame:
|
|
@@ -111,11 +122,68 @@ def last_ettj() -> pd.DataFrame:
|
|
|
111
122
|
Note:
|
|
112
123
|
All rates are expressed in decimal format (e.g., 0.12 for 12%).
|
|
113
124
|
"""
|
|
114
|
-
text =
|
|
115
|
-
|
|
125
|
+
text = _get_last_content_text()
|
|
126
|
+
reference_date = _get_reference_date(text)
|
|
127
|
+
text = _filter_ettf_text(text)
|
|
128
|
+
df = _convert_text_to_df(text, reference_date)
|
|
116
129
|
return _process_df(df)
|
|
117
130
|
|
|
118
131
|
|
|
132
|
+
def _extrair_data_e_tabelas(
|
|
133
|
+
texto: str, titulo_tabela: str
|
|
134
|
+
) -> tuple[pd.Timestamp, str, str]:
|
|
135
|
+
# Títulos que servem como nossos marcadores
|
|
136
|
+
titulo_pre = "ETTJ PREFIXADOS (%a.a./252)"
|
|
137
|
+
titulo_ipca = "ETTJ IPCA (%a.a./252)"
|
|
138
|
+
|
|
139
|
+
# Dividir o texto em linhas
|
|
140
|
+
linhas = [linha for linha in texto.strip().splitlines() if linha.strip()]
|
|
141
|
+
|
|
142
|
+
# Encontrar os índices dos títulos
|
|
143
|
+
inicio_tabela_pre = linhas.index(titulo_pre)
|
|
144
|
+
inicio_tabela_ipca = linhas.index(titulo_ipca)
|
|
145
|
+
|
|
146
|
+
# --- Extrair Tabela 1 ---
|
|
147
|
+
data_ref_pre = linhas[inicio_tabela_pre + 1]
|
|
148
|
+
# A tabela 1 vai do seu cabeçalho até a linha antes do título da tabela 2
|
|
149
|
+
tabela_pre_linhas = linhas[inicio_tabela_pre + 2 : inicio_tabela_ipca]
|
|
150
|
+
tabela_pre = "\n".join(tabela_pre_linhas)
|
|
151
|
+
|
|
152
|
+
# --- Extrair Tabela 2 ---
|
|
153
|
+
data_ref_ipca = linhas[inicio_tabela_ipca + 1]
|
|
154
|
+
# A tabela 2 vai do seu cabeçalho até o final da lista
|
|
155
|
+
tabela_ipca_linhas = linhas[inicio_tabela_ipca + 2 :]
|
|
156
|
+
tabela_ipca = "\n".join(tabela_ipca_linhas)
|
|
157
|
+
|
|
158
|
+
if data_ref_pre != data_ref_ipca:
|
|
159
|
+
raise ValueError("Datas de referência diferentes")
|
|
160
|
+
|
|
161
|
+
data_ref = pd.to_datetime(data_ref_pre, format="%d/%m/%Y")
|
|
162
|
+
|
|
163
|
+
return data_ref, tabela_pre, tabela_ipca
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _ler_tabela_intradia(texto: str) -> pd.DataFrame:
|
|
167
|
+
"""
|
|
168
|
+
Reads a table from the given text and returns it as a DataFrame.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
texto (str): The text containing the table data.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
pd.DataFrame: A DataFrame containing the table data.
|
|
175
|
+
"""
|
|
176
|
+
df = pd.read_csv(
|
|
177
|
+
StringIO(texto),
|
|
178
|
+
sep=";",
|
|
179
|
+
decimal=",",
|
|
180
|
+
thousands=".",
|
|
181
|
+
dtype_backend="pyarrow",
|
|
182
|
+
)
|
|
183
|
+
df = df.drop(columns=["Fechamento D -1"])
|
|
184
|
+
return df
|
|
185
|
+
|
|
186
|
+
|
|
119
187
|
def intraday_ettj() -> pd.DataFrame:
|
|
120
188
|
"""
|
|
121
189
|
Retrieves and processes the intraday Brazilian yield curve data from ANBIMA.
|
|
@@ -140,25 +208,18 @@ def intraday_ettj() -> pd.DataFrame:
|
|
|
140
208
|
|
|
141
209
|
request_payload = {"Dt_Ref": "", "saida": "csv"}
|
|
142
210
|
response = requests.post(INTRADAY_ETTJ_URL, data=request_payload)
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
lines = real_text.splitlines()
|
|
156
|
-
df_text = "\n".join(lines[2:])
|
|
157
|
-
df_real = pd.read_csv(StringIO(df_text), sep=";", decimal=",", thousands=".")
|
|
158
|
-
df_real = df_real.drop(columns=["Fechamento D -1"])
|
|
159
|
-
df_real = df_real.rename(columns={"D0": "real_rate"})
|
|
160
|
-
|
|
161
|
-
df = pd.merge(df_nominal, df_real, on="Vertices", how="right")
|
|
211
|
+
texto = response.text
|
|
212
|
+
|
|
213
|
+
# --- Extração da Tabela 1: PREFIXADOS ---
|
|
214
|
+
data_ref, tabela_pre, tabela_ipca = _extrair_data_e_tabelas(texto, texto)
|
|
215
|
+
|
|
216
|
+
df_pre = _ler_tabela_intradia(tabela_pre)
|
|
217
|
+
df_pre = df_pre.rename(columns={"D0": "nominal_rate"})
|
|
218
|
+
|
|
219
|
+
df_ipca = _ler_tabela_intradia(tabela_ipca)
|
|
220
|
+
df_ipca = df_ipca.rename(columns={"D0": "real_rate"})
|
|
221
|
+
|
|
222
|
+
df = pd.merge(df_pre, df_ipca, on="Vertices", how="right")
|
|
162
223
|
df = df.rename(columns={"Vertices": "vertex"})
|
|
163
224
|
|
|
164
225
|
# Divide float columns by 100 and round to 6 decimal places
|
|
@@ -167,6 +228,7 @@ def intraday_ettj() -> pd.DataFrame:
|
|
|
167
228
|
df["implied_inflation"] = (df["nominal_rate"] + 1) / (df["real_rate"] + 1) - 1
|
|
168
229
|
df["implied_inflation"] = df["implied_inflation"].round(ROUND_DIGITS)
|
|
169
230
|
|
|
170
|
-
df["date"] =
|
|
231
|
+
df["date"] = data_ref
|
|
232
|
+
df["date"] = df["date"].astype("date32[pyarrow]")
|
|
171
233
|
column_order = ["date", "vertex", "nominal_rate", "real_rate", "implied_inflation"]
|
|
172
234
|
return df[column_order].copy()
|
|
@@ -209,18 +209,19 @@ def _reorder_columns(df: pd.DataFrame) -> pd.DataFrame:
|
|
|
209
209
|
|
|
210
210
|
|
|
211
211
|
def _fetch_tpf_data(date: pd.Timestamp) -> pd.DataFrame:
|
|
212
|
-
"""
|
|
212
|
+
"""Busca e processa dados do mercado secundário de TPF diretamente da fonte ANBIMA.
|
|
213
213
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
214
|
+
Esta é uma função de baixo nível para uso interno. Ela lida com a lógica
|
|
215
|
+
de construir a URL correta (pública ou RTM), baixar os dados com novas
|
|
216
|
+
tentativas e processá-los em um DataFrame estruturado.
|
|
217
217
|
|
|
218
218
|
Args:
|
|
219
|
-
date (pd.Timestamp):
|
|
219
|
+
date (pd.Timestamp): A data de referência para os dados.
|
|
220
220
|
|
|
221
221
|
Returns:
|
|
222
|
-
pd.DataFrame:
|
|
223
|
-
|
|
222
|
+
pd.DataFrame: Um DataFrame contendo os dados de mercado de títulos
|
|
223
|
+
processados, ou um DataFrame vazio se os dados não estiverem
|
|
224
|
+
disponíveis ou ocorrer um erro de conexão.
|
|
224
225
|
"""
|
|
225
226
|
file_url = _build_file_url(date)
|
|
226
227
|
date_str = date.strftime("%d/%m/%Y")
|
|
@@ -283,38 +284,37 @@ def tpf_data(
|
|
|
283
284
|
bond_type: str | None = None,
|
|
284
285
|
fetch_from_source: bool = False,
|
|
285
286
|
) -> pd.DataFrame:
|
|
286
|
-
"""
|
|
287
|
+
"""Recupera os dados do mercado secundário de TPF da ANBIMA.
|
|
287
288
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
directly from the ANBIMA website.
|
|
289
|
+
Esta função busca taxas indicativas e outros dados de títulos públicos
|
|
290
|
+
brasileiros. A obtenção dos dados segue uma hierarquia de fontes para
|
|
291
|
+
otimizar o desempenho e o acesso.
|
|
292
292
|
|
|
293
293
|
Args:
|
|
294
|
-
date (DateScalar):
|
|
295
|
-
bond_type (str, optional):
|
|
296
|
-
(
|
|
297
|
-
fetch_from_source (bool, optional):
|
|
298
|
-
|
|
299
|
-
|
|
294
|
+
date (DateScalar): A data de referência para os dados (ex: '2024-06-14').
|
|
295
|
+
bond_type (str, optional): Filtra os resultados por um tipo de título
|
|
296
|
+
específico (ex: 'LTN', 'NTN-B'). Por padrão, retorna todos os tipos.
|
|
297
|
+
fetch_from_source (bool, optional): Se True, força a função a ignorar o
|
|
298
|
+
cache e buscar os dados diretamente da fonte (ANBIMA).
|
|
299
|
+
Padrão é False.
|
|
300
300
|
|
|
301
301
|
Returns:
|
|
302
|
-
pd.DataFrame:
|
|
303
|
-
DataFrame
|
|
304
|
-
|
|
302
|
+
pd.DataFrame: Um DataFrame contendo os dados solicitados. Retorna um
|
|
303
|
+
DataFrame vazio se não houver dados para a data especificada (ex:
|
|
304
|
+
finais de semana, feriados ou datas futuras).
|
|
305
305
|
|
|
306
306
|
Examples:
|
|
307
307
|
>>> from pyield import anbima
|
|
308
308
|
>>> anbima.tpf_data(date="22-08-2025")
|
|
309
|
-
ReferenceDate BondType
|
|
310
|
-
0 2025-08-22 LFT
|
|
311
|
-
1 2025-08-22 LFT
|
|
312
|
-
2 2025-08-22 LFT
|
|
313
|
-
3 2025-08-22 LFT
|
|
314
|
-
4 2025-08-22 LFT 2027-09-01 0.000411 17186.767105
|
|
309
|
+
ReferenceDate BondType SelicCode ... AskRate IndicativeRate DIRate
|
|
310
|
+
0 2025-08-22 LFT 210100 ... 0.0001 0.000165 0.14906
|
|
311
|
+
1 2025-08-22 LFT 210100 ... -0.000156 -0.000116 0.14843
|
|
312
|
+
2 2025-08-22 LFT 210100 ... -0.000143 -0.000107 0.1436
|
|
313
|
+
3 2025-08-22 LFT 210100 ... 0.000292 0.000302 0.138189
|
|
315
314
|
...
|
|
316
315
|
|
|
317
|
-
|
|
316
|
+
|
|
317
|
+
Data columns:
|
|
318
318
|
- BondType: Tipo do título público (e.g., 'LTN', 'NTN-B').
|
|
319
319
|
- ReferenceDate: Data de referência dos dados.
|
|
320
320
|
- SelicCode: Código do título no SELIC.
|
|
@@ -329,7 +329,7 @@ def tpf_data(
|
|
|
329
329
|
- BidRate: Taxa de compra em formato decimal (e.g., 0.10 para 10%).
|
|
330
330
|
- AskRate: Taxa de venda em formato decimal.
|
|
331
331
|
- IndicativeRate: Taxa indicativa em formato decimal.
|
|
332
|
-
- DIRate: Taxa DI interpolada
|
|
332
|
+
- DIRate: Taxa DI interpolada (flatforward) no vencimento do título.
|
|
333
333
|
- StdDev: Desvio padrão da taxa indicativa.
|
|
334
334
|
- LowerBoundRateD0: Limite inferior do intervalo indicativo para D+0.
|
|
335
335
|
- UpperBoundRateD0: Limite superior do intervalo indicativo para D+0.
|
|
@@ -338,11 +338,16 @@ def tpf_data(
|
|
|
338
338
|
- Criteria: Critério utilizado pela ANBIMA para o cálculo.
|
|
339
339
|
|
|
340
340
|
Notes:
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
341
|
+
A fonte dos dados segue a seguinte hierarquia:
|
|
342
|
+
|
|
343
|
+
1. **Cache Local (Padrão):** Fornece acesso rápido a dados históricos
|
|
344
|
+
desde 01/01/2020. É utilizado por padrão (`fetch_from_source=False`).
|
|
345
|
+
2. **Site Público da ANBIMA:** Acessado quando `fetch_from_source=True`,
|
|
346
|
+
disponibiliza os dados dos últimos 5 dias úteis.
|
|
347
|
+
3. **Rede RTM da ANBIMA:** Acessada quando `fetch_from_source=True` para
|
|
348
|
+
datas com mais de 5 dias úteis. O acesso ao histórico completo
|
|
349
|
+
requer uma conexão à rede RTM. Sem ela, a consulta para datas
|
|
350
|
+
antigas retornará um DataFrame vazio.
|
|
346
351
|
"""
|
|
347
352
|
date = convert_input_dates(date)
|
|
348
353
|
|
|
@@ -377,11 +382,10 @@ def tpf_data(
|
|
|
377
382
|
|
|
378
383
|
|
|
379
384
|
def tpf_fixed_rate_maturities(date: DateScalar) -> pd.Series:
|
|
380
|
-
"""Retrieve
|
|
385
|
+
"""Retrieve existing maturity dates for fixed-rate public bonds (LTN and NTN-F).
|
|
381
386
|
|
|
382
|
-
This function fetches
|
|
383
|
-
'NTN-F'
|
|
384
|
-
for a given reference date.
|
|
387
|
+
This function fetches existing maturity dates for 'LTN' and
|
|
388
|
+
'NTN-F' bond types for a given date.
|
|
385
389
|
|
|
386
390
|
Args:
|
|
387
391
|
date (DateScalar): The reference date for maturity dates.
|
|
@@ -389,6 +393,20 @@ def tpf_fixed_rate_maturities(date: DateScalar) -> pd.Series:
|
|
|
389
393
|
Returns:
|
|
390
394
|
pd.Series: A Series containing unique maturity dates for 'LTN' and
|
|
391
395
|
'NTN-F' bonds, sorted in ascending order.
|
|
396
|
+
|
|
397
|
+
Examples:
|
|
398
|
+
>>> from pyield import anbima
|
|
399
|
+
>>> anbima.tpf_fixed_rate_maturities(date="22-08-2025")
|
|
400
|
+
0 2025-10-01
|
|
401
|
+
1 2026-01-01
|
|
402
|
+
2 2026-04-01
|
|
403
|
+
3 2026-07-01
|
|
404
|
+
...
|
|
405
|
+
14 2031-01-01
|
|
406
|
+
15 2032-01-01
|
|
407
|
+
16 2033-01-01
|
|
408
|
+
17 2035-01-01
|
|
409
|
+
Name: MaturityDate, dtype: date32[day][pyarrow]
|
|
392
410
|
"""
|
|
393
411
|
maturity_dates = (
|
|
394
412
|
tpf_data(date)
|
|
@@ -37,11 +37,14 @@ def _get_data(dates: pd.Series) -> pd.DataFrame:
|
|
|
37
37
|
):
|
|
38
38
|
try:
|
|
39
39
|
df_intraday = b3.futures(contract_code="DI1", date=today)
|
|
40
|
-
if not df_intraday.empty:
|
|
41
|
-
logger.
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
40
|
+
if "SettlementPrice" not in df_intraday.columns or df_intraday.empty:
|
|
41
|
+
logger.warning(
|
|
42
|
+
f"Ainda sem dados de ajustes intraday para {today}."
|
|
43
|
+
" Retornando apenas dados do cache."
|
|
44
|
+
)
|
|
45
|
+
return df_cached
|
|
46
|
+
logger.info("Dados intraday de DI inseridos com sucesso.")
|
|
47
|
+
return pd.concat([df_cached, df_intraday]).reset_index(drop=True)
|
|
45
48
|
except Exception as e:
|
|
46
49
|
logger.error(f"Falha ao buscar dados intraday para {today}: {e}")
|
|
47
50
|
|
|
@@ -7,8 +7,6 @@ import requests
|
|
|
7
7
|
|
|
8
8
|
logger = logging.getLogger(__name__)
|
|
9
9
|
|
|
10
|
-
TIMEZONE_BZ = ZoneInfo("America/Sao_Paulo")
|
|
11
|
-
|
|
12
10
|
COLUMN_MAPPING = {
|
|
13
11
|
"INÍCIO": "StartDate",
|
|
14
12
|
"TERMINO": "EndDate",
|
|
@@ -17,14 +15,71 @@ COLUMN_MAPPING = {
|
|
|
17
15
|
"BENCHMARK": "Benchmark",
|
|
18
16
|
}
|
|
19
17
|
|
|
20
|
-
|
|
21
18
|
API_BASE_URL = (
|
|
22
19
|
"https://apiapex.tesouro.gov.br/aria/v1/api-leiloes-pub/custom/benchmarks"
|
|
23
20
|
)
|
|
24
21
|
API_HISTORY_PARAM = "incluir_historico"
|
|
25
22
|
|
|
23
|
+
TIMEZONE_BZ = ZoneInfo("America/Sao_Paulo")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _fetch_raw_benchmarks(include_history: bool) -> list[dict]:
|
|
27
|
+
"""
|
|
28
|
+
Fetches the raw benchmark data from the Tesouro Nacional API.
|
|
29
|
+
Handles network requests, retries, and basic response validation.
|
|
30
|
+
"""
|
|
31
|
+
session = requests.Session()
|
|
32
|
+
include_history_param_value = "S" if include_history else "N"
|
|
33
|
+
api_endpoint = f"{API_BASE_URL}?{API_HISTORY_PARAM}={include_history_param_value}"
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
response = session.get(api_endpoint)
|
|
37
|
+
response.raise_for_status()
|
|
38
|
+
except requests.exceptions.SSLError as e:
|
|
39
|
+
logger.warning(
|
|
40
|
+
f"SSL error encountered: {e}. Retrying without certificate verification."
|
|
41
|
+
)
|
|
42
|
+
response = session.get(api_endpoint, verify=False)
|
|
43
|
+
response.raise_for_status()
|
|
44
|
+
except requests.exceptions.RequestException as e:
|
|
45
|
+
logger.error(f"Error fetching benchmarks from API: {e}")
|
|
46
|
+
return [] # Retorna lista vazia em caso de erro
|
|
47
|
+
|
|
48
|
+
response_dict = response.json()
|
|
49
|
+
|
|
50
|
+
if not response_dict or "registros" not in response_dict:
|
|
51
|
+
logger.warning("API response did not contain 'registros' key or was empty.")
|
|
52
|
+
return []
|
|
53
|
+
|
|
54
|
+
return response_dict["registros"]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _process_benchmark_data(raw_data: list[dict]) -> pd.DataFrame:
|
|
58
|
+
"""
|
|
59
|
+
Converts raw benchmark data into a cleaned and typed pandas DataFrame.
|
|
60
|
+
"""
|
|
61
|
+
if not raw_data:
|
|
62
|
+
return pd.DataFrame()
|
|
63
|
+
|
|
64
|
+
df = pd.DataFrame(raw_data).dropna().convert_dtypes(dtype_backend="pyarrow")
|
|
26
65
|
|
|
27
|
-
|
|
66
|
+
if df.empty:
|
|
67
|
+
logger.warning("DataFrame is empty after dropping NaN values.")
|
|
68
|
+
return pd.DataFrame()
|
|
69
|
+
|
|
70
|
+
# Limpeza e tipagem
|
|
71
|
+
date_cols = ["VENCIMENTO", "TERMINO", "INÍCIO"]
|
|
72
|
+
for col in date_cols:
|
|
73
|
+
df[col] = pd.to_datetime(df[col]).astype("date32[pyarrow]")
|
|
74
|
+
|
|
75
|
+
str_cols = ["BENCHMARK", "TÍTULO"]
|
|
76
|
+
for col in str_cols:
|
|
77
|
+
df[col] = df[col].str.strip()
|
|
78
|
+
|
|
79
|
+
return df
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def benchmarks(bond_type: str = None, include_history: bool = False) -> pd.DataFrame:
|
|
28
83
|
"""Fetches benchmark data for Brazilian Treasury Bonds from the TN API.
|
|
29
84
|
|
|
30
85
|
This function retrieves current or historical benchmark data for various Brazilian
|
|
@@ -56,9 +111,8 @@ def benchmarks(include_history: bool = False) -> pd.DataFrame:
|
|
|
56
111
|
Examples:
|
|
57
112
|
>>> from pyield import tn
|
|
58
113
|
>>> df_current = tn.benchmarks()
|
|
59
|
-
|
|
60
114
|
>>> # Get historical benchmarks
|
|
61
|
-
>>> df_history = tn.benchmarks(include_history=True)
|
|
115
|
+
>>> df_history = tn.benchmarks(bond_type="LFT", include_history=True)
|
|
62
116
|
>>> df_history.head()
|
|
63
117
|
StartDate EndDate BondType MaturityDate Benchmark
|
|
64
118
|
0 2014-01-01 2014-06-30 LFT 2020-03-01 LFT 6 anos
|
|
@@ -67,67 +121,32 @@ def benchmarks(include_history: bool = False) -> pd.DataFrame:
|
|
|
67
121
|
3 2015-05-01 2015-12-31 LFT 2021-09-01 LFT 6 anos
|
|
68
122
|
4 2016-01-01 2016-06-30 LFT 2022-03-01 LFT 6 anos
|
|
69
123
|
"""
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
try:
|
|
75
|
-
stn_benchmarks = session.get(api_endpoint)
|
|
76
|
-
stn_benchmarks.raise_for_status()
|
|
77
|
-
except requests.exceptions.SSLError as e:
|
|
78
|
-
logger.error(
|
|
79
|
-
f"SSL error encountered: {e}. Retrying without certificate verification."
|
|
80
|
-
)
|
|
81
|
-
stn_benchmarks = session.get(api_endpoint, verify=False)
|
|
82
|
-
stn_benchmarks.raise_for_status()
|
|
83
|
-
except requests.exceptions.RequestException as e:
|
|
84
|
-
logger.error(f"Error fetching benchmarks from API: {e}")
|
|
85
|
-
return pd.DataFrame()
|
|
124
|
+
# Passo 1: Buscar os dados brutos
|
|
125
|
+
raw_data = _fetch_raw_benchmarks(include_history=include_history)
|
|
126
|
+
if not raw_data:
|
|
127
|
+
return pd.DataFrame() # Retorna DF vazio se a busca falhou
|
|
86
128
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
# 1a verificação: Verifica se a resposta da API contém dados válidos de registros
|
|
90
|
-
if not response_dict or not response_dict.get("registros"):
|
|
91
|
-
logger.warning("API response did not contain 'registros' key or it was empty.")
|
|
92
|
-
return pd.DataFrame()
|
|
93
|
-
|
|
94
|
-
# Tenta criar o DataFrame.
|
|
95
|
-
df = (
|
|
96
|
-
pd.DataFrame(response_dict["registros"])
|
|
97
|
-
.dropna()
|
|
98
|
-
.convert_dtypes(dtype_backend="pyarrow")
|
|
99
|
-
)
|
|
100
|
-
|
|
101
|
-
# 2a verificação: Verifica se o DataFrame resultante (pós-dropna) está vazio
|
|
102
|
-
# Esta verificação é importante porque .dropna() pode remover todas as linhas.
|
|
129
|
+
# Passo 2: Processar os dados em um DataFrame limpo
|
|
130
|
+
df = _process_benchmark_data(raw_data)
|
|
103
131
|
if df.empty:
|
|
104
|
-
|
|
105
|
-
"No valid benchmark data found after initial processing"
|
|
106
|
-
"(e.g., all rows had NaNs and were dropped).",
|
|
107
|
-
)
|
|
108
|
-
return pd.DataFrame()
|
|
109
|
-
|
|
110
|
-
# Se chegamos até aqui, o DataFrame tem dados e pode ser processado.
|
|
111
|
-
for col in ["VENCIMENTO", "TERMINO", "INÍCIO"]:
|
|
112
|
-
df[col] = pd.to_datetime(df[col]).astype("date32[pyarrow]")
|
|
113
|
-
|
|
114
|
-
df["BENCHMARK"] = df["BENCHMARK"].str.strip()
|
|
115
|
-
df["TÍTULO"] = df["TÍTULO"].str.strip()
|
|
132
|
+
return pd.DataFrame() # Retorna DF vazio se o processamento resultou em nada
|
|
116
133
|
|
|
134
|
+
# Passo 3: Aplicar filtros específicos da chamada
|
|
117
135
|
if not include_history:
|
|
118
|
-
# Em tese, a API já retorna apenas benchmarks ativos,
|
|
119
|
-
# mas vamos garantir que o DataFrame só contenha benchmarks ativos
|
|
120
|
-
# considerando o período atual.
|
|
121
136
|
today = dt.now(TIMEZONE_BZ).date() # noqa
|
|
122
137
|
df = df.query("INÍCIO <= @today <= TERMINO").reset_index(drop=True)
|
|
138
|
+
if df.empty:
|
|
139
|
+
logger.warning(
|
|
140
|
+
"No current benchmark data found after filtering by active period."
|
|
141
|
+
)
|
|
123
142
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
)
|
|
143
|
+
if bond_type:
|
|
144
|
+
df = df.query("TÍTULO == @bond_type").reset_index(drop=True)
|
|
145
|
+
|
|
146
|
+
if df.empty:
|
|
147
|
+
return pd.DataFrame() # Retorna DF vazio se os filtros removeram tudo
|
|
130
148
|
|
|
149
|
+
# Passo 4: Formatar a saída final
|
|
131
150
|
column_order = [c for c in COLUMN_MAPPING if c in df.columns]
|
|
132
151
|
return (
|
|
133
152
|
df[column_order]
|
|
@@ -24,21 +24,12 @@ def data(date: DateScalar) -> pd.DataFrame:
|
|
|
24
24
|
Examples:
|
|
25
25
|
>>> from pyield import lft
|
|
26
26
|
>>> lft.data("23-08-2024")
|
|
27
|
-
ReferenceDate BondType
|
|
28
|
-
0 2024-08-23 LFT
|
|
29
|
-
1 2024-08-23 LFT
|
|
30
|
-
2 2024-08-23 LFT
|
|
31
|
-
3 2024-08-23 LFT
|
|
32
|
-
|
|
33
|
-
5 2024-08-23 LFT 2027-03-01 0.000669 15226.824838
|
|
34
|
-
6 2024-08-23 LFT 2027-09-01 0.000948 15208.842417
|
|
35
|
-
7 2024-08-23 LFT 2028-03-01 0.001172 15189.853347
|
|
36
|
-
8 2024-08-23 LFT 2028-09-01 0.001328 15171.352348
|
|
37
|
-
9 2024-08-23 LFT 2029-03-01 0.001491 15150.700781
|
|
38
|
-
10 2024-08-23 LFT 2029-09-01 0.001587 15131.894737
|
|
39
|
-
11 2024-08-23 LFT 2030-03-01 0.001591 15119.952213
|
|
40
|
-
12 2024-08-23 LFT 2030-06-01 0.001641 15109.717943
|
|
41
|
-
13 2024-08-23 LFT 2030-09-01 0.001687 15099.285393
|
|
27
|
+
ReferenceDate BondType SelicCode ... AskRate IndicativeRate DIRate
|
|
28
|
+
0 2024-08-23 LFT 210100 ... 0.000226 0.000272 0.10408
|
|
29
|
+
1 2024-08-23 LFT 210100 ... -0.000481 -0.000418 0.11082
|
|
30
|
+
2 2024-08-23 LFT 210100 ... -0.000258 -0.00023 0.114315
|
|
31
|
+
3 2024-08-23 LFT 210100 ... 0.00006 0.000075 0.114982
|
|
32
|
+
...
|
|
42
33
|
"""
|
|
43
34
|
return anbima.tpf_data(date, "LFT")
|
|
44
35
|
|
|
@@ -22,20 +22,12 @@ def data(date: DateScalar) -> pd.DataFrame:
|
|
|
22
22
|
Examples:
|
|
23
23
|
>>> from pyield import ltn
|
|
24
24
|
>>> ltn.data("23-08-2024")
|
|
25
|
-
|
|
26
|
-
0
|
|
27
|
-
1
|
|
28
|
-
2
|
|
29
|
-
3
|
|
30
|
-
|
|
31
|
-
5 2024-08-23 LTN 2026-01-01 0.114654 863.026594
|
|
32
|
-
6 2024-08-23 LTN 2026-04-01 0.114997 840.232741
|
|
33
|
-
7 2024-08-23 LTN 2026-07-01 0.115265 818.020491
|
|
34
|
-
8 2024-08-23 LTN 2026-10-01 0.115357 795.185488
|
|
35
|
-
9 2024-08-23 LTN 2027-07-01 0.115335 733.981131
|
|
36
|
-
10 2024-08-23 LTN 2028-01-01 0.115694 693.647778
|
|
37
|
-
11 2024-08-23 LTN 2028-07-01 0.116417 655.6398
|
|
38
|
-
12 2024-08-23 LTN 2030-01-01 0.117436 554.331151
|
|
25
|
+
ReferenceDate BondType SelicCode ... AskRate IndicativeRate DIRate
|
|
26
|
+
0 2024-08-23 LTN 100000 ... 0.104252 0.104416 0.10472
|
|
27
|
+
1 2024-08-23 LTN 100000 ... 0.107016 0.107171 0.10823
|
|
28
|
+
2 2024-08-23 LTN 100000 ... 0.110746 0.110866 0.11179
|
|
29
|
+
3 2024-08-23 LTN 100000 ... 0.112947 0.113032 0.11365
|
|
30
|
+
...
|
|
39
31
|
|
|
40
32
|
"""
|
|
41
33
|
return anbima.tpf_data(date, "LTN")
|
|
@@ -36,21 +36,12 @@ def data(date: DateScalar) -> pd.DataFrame:
|
|
|
36
36
|
Examples:
|
|
37
37
|
>>> from pyield import ntnb
|
|
38
38
|
>>> ntnb.data("23-08-2024")
|
|
39
|
-
ReferenceDate BondType
|
|
40
|
-
0 2024-08-23 NTN-B
|
|
41
|
-
1 2024-08-23 NTN-B
|
|
42
|
-
2 2024-08-23 NTN-B
|
|
43
|
-
3 2024-08-23 NTN-B
|
|
44
|
-
|
|
45
|
-
5 2024-08-23 NTN-B 2030-08-15 0.060298 4324.468801
|
|
46
|
-
6 2024-08-23 NTN-B 2032-08-15 0.0604 4320.153067
|
|
47
|
-
7 2024-08-23 NTN-B 2033-05-15 0.060403 4384.189924
|
|
48
|
-
8 2024-08-23 NTN-B 2035-05-15 0.060375 4386.002533
|
|
49
|
-
9 2024-08-23 NTN-B 2040-08-15 0.059797 4345.119587
|
|
50
|
-
10 2024-08-23 NTN-B 2045-05-15 0.060923 4358.235102
|
|
51
|
-
11 2024-08-23 NTN-B 2050-08-15 0.06114 4279.434119
|
|
52
|
-
12 2024-08-23 NTN-B 2055-05-15 0.060892 4355.145036
|
|
53
|
-
13 2024-08-23 NTN-B 2060-08-15 0.061005 4282.308398
|
|
39
|
+
ReferenceDate BondType SelicCode ... AskRate IndicativeRate DIRate
|
|
40
|
+
0 2024-08-23 NTN-B 760199 ... 0.063667 0.063804 0.112749
|
|
41
|
+
1 2024-08-23 NTN-B 760199 ... 0.065635 0.065795 0.114963
|
|
42
|
+
2 2024-08-23 NTN-B 760199 ... 0.063601 0.063794 0.114888
|
|
43
|
+
3 2024-08-23 NTN-B 760199 ... 0.062905 0.063094 0.115595
|
|
44
|
+
...
|
|
54
45
|
"""
|
|
55
46
|
return anbima.tpf_data(date, "NTN-B")
|
|
56
47
|
|
|
@@ -52,9 +52,10 @@ def data(date: DateScalar) -> pd.DataFrame:
|
|
|
52
52
|
|
|
53
53
|
Examples:
|
|
54
54
|
>>> from pyield import ntnc
|
|
55
|
-
>>> ntnc.data("
|
|
56
|
-
ReferenceDate BondType
|
|
57
|
-
0
|
|
55
|
+
>>> ntnc.data("23-08-2024")
|
|
56
|
+
ReferenceDate BondType SelicCode ... AskRate IndicativeRate DIRate
|
|
57
|
+
0 2024-08-23 NTN-C 770100 ... 0.057587 0.059617 0.11575
|
|
58
|
+
...
|
|
58
59
|
"""
|
|
59
60
|
return anbima.tpf_data(date, "NTN-C")
|
|
60
61
|
|
|
@@ -36,13 +36,12 @@ def data(date: DateScalar) -> pd.DataFrame:
|
|
|
36
36
|
Examples:
|
|
37
37
|
>>> from pyield import ntnf
|
|
38
38
|
>>> ntnf.data("23-08-2024")
|
|
39
|
-
ReferenceDate BondType
|
|
40
|
-
0 2024-08-23 NTN-F
|
|
41
|
-
1 2024-08-23 NTN-F
|
|
42
|
-
2 2024-08-23 NTN-F
|
|
43
|
-
3 2024-08-23 NTN-F
|
|
44
|
-
|
|
45
|
-
5 2024-08-23 NTN-F 2035-01-01 0.116586 923.239406
|
|
39
|
+
ReferenceDate BondType SelicCode ... AskRate IndicativeRate DIRate
|
|
40
|
+
0 2024-08-23 NTN-F 950199 ... 0.107524 0.107692 0.10823
|
|
41
|
+
1 2024-08-23 NTN-F 950199 ... 0.114948 0.115109 0.11467
|
|
42
|
+
2 2024-08-23 NTN-F 950199 ... 0.11621 0.116337 0.1156
|
|
43
|
+
3 2024-08-23 NTN-F 950199 ... 0.116958 0.117008 0.11575
|
|
44
|
+
...
|
|
46
45
|
"""
|
|
47
46
|
return anbima.tpf_data(date, "NTN-F")
|
|
48
47
|
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.37.4"
|
|
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
|
|
File without changes
|