PYield 0.36.4__tar.gz → 0.36.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 (54) hide show
  1. {pyield-0.36.4 → pyield-0.36.6}/PKG-INFO +1 -1
  2. pyield-0.36.6/pyield/__about__.py +1 -0
  3. {pyield-0.36.4 → pyield-0.36.6}/pyield/anbima/tpf.py +27 -4
  4. {pyield-0.36.4 → pyield-0.36.6}/pyield/bc/trades_monthly.py +41 -8
  5. pyield-0.36.6/pyield/retry.py +96 -0
  6. pyield-0.36.4/pyield/__about__.py +0 -1
  7. pyield-0.36.4/pyield/retry.py +0 -174
  8. {pyield-0.36.4 → pyield-0.36.6}/.gitignore +0 -0
  9. {pyield-0.36.4 → pyield-0.36.6}/LICENSE +0 -0
  10. {pyield-0.36.4 → pyield-0.36.6}/README.md +0 -0
  11. {pyield-0.36.4 → pyield-0.36.6}/pyield/__init__.py +0 -0
  12. {pyield-0.36.4 → pyield-0.36.6}/pyield/anbima/__init__.py +0 -0
  13. {pyield-0.36.4 → pyield-0.36.6}/pyield/anbima/ettj.py +0 -0
  14. {pyield-0.36.4 → pyield-0.36.6}/pyield/anbima/ima.py +0 -0
  15. {pyield-0.36.4 → pyield-0.36.6}/pyield/anbima/imaq.py +0 -0
  16. {pyield-0.36.4 → pyield-0.36.6}/pyield/anbima/ipca.py +0 -0
  17. {pyield-0.36.4 → pyield-0.36.6}/pyield/b3/__init__.py +0 -0
  18. {pyield-0.36.4 → pyield-0.36.6}/pyield/b3/di1.py +0 -0
  19. {pyield-0.36.4 → pyield-0.36.6}/pyield/b3/di_over.py +0 -0
  20. {pyield-0.36.4 → pyield-0.36.6}/pyield/b3/futures/__init__.py +0 -0
  21. {pyield-0.36.4 → pyield-0.36.6}/pyield/b3/futures/common.py +0 -0
  22. {pyield-0.36.4 → pyield-0.36.6}/pyield/b3/futures/historical.py +0 -0
  23. {pyield-0.36.4 → pyield-0.36.6}/pyield/b3/futures/intraday.py +0 -0
  24. {pyield-0.36.4 → pyield-0.36.6}/pyield/b3/futures/xml.py +0 -0
  25. {pyield-0.36.4 → pyield-0.36.6}/pyield/bc/__init__.py +0 -0
  26. {pyield-0.36.4 → pyield-0.36.6}/pyield/bc/auction.py +0 -0
  27. {pyield-0.36.4 → pyield-0.36.6}/pyield/bc/bcdata.py +0 -0
  28. {pyield-0.36.4 → pyield-0.36.6}/pyield/bc/ptax.py +0 -0
  29. {pyield-0.36.4 → pyield-0.36.6}/pyield/bc/repo.py +0 -0
  30. {pyield-0.36.4 → pyield-0.36.6}/pyield/bc/trades_intraday.py +0 -0
  31. {pyield-0.36.4 → pyield-0.36.6}/pyield/bc/vna.py +0 -0
  32. {pyield-0.36.4 → pyield-0.36.6}/pyield/bday.py +0 -0
  33. {pyield-0.36.4 → pyield-0.36.6}/pyield/conftest.py +0 -0
  34. {pyield-0.36.4 → pyield-0.36.6}/pyield/data_cache.py +0 -0
  35. {pyield-0.36.4 → pyield-0.36.6}/pyield/date_converter.py +0 -0
  36. {pyield-0.36.4 → pyield-0.36.6}/pyield/fwd.py +0 -0
  37. {pyield-0.36.4 → pyield-0.36.6}/pyield/holidays/__init__.py +0 -0
  38. {pyield-0.36.4 → pyield-0.36.6}/pyield/holidays/br_holidays_new.txt +0 -0
  39. {pyield-0.36.4 → pyield-0.36.6}/pyield/holidays/br_holidays_old.txt +0 -0
  40. {pyield-0.36.4 → pyield-0.36.6}/pyield/holidays/brholidays.py +0 -0
  41. {pyield-0.36.4 → pyield-0.36.6}/pyield/ibge/__init__.py +0 -0
  42. {pyield-0.36.4 → pyield-0.36.6}/pyield/ibge/ipca.py +0 -0
  43. {pyield-0.36.4 → pyield-0.36.6}/pyield/interpolator.py +0 -0
  44. {pyield-0.36.4 → pyield-0.36.6}/pyield/py.typed +0 -0
  45. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/__init__.py +0 -0
  46. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/benchmark.py +0 -0
  47. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/lft.py +0 -0
  48. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/ltn.py +0 -0
  49. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/ntnb.py +0 -0
  50. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/ntnc.py +0 -0
  51. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/ntnf.py +0 -0
  52. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/pre.py +0 -0
  53. {pyield-0.36.4 → pyield-0.36.6}/pyield/tn/tools.py +0 -0
  54. {pyield-0.36.4 → pyield-0.36.6}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PYield
3
- Version: 0.36.4
3
+ Version: 0.36.6
4
4
  Summary: A Python library for analysis of fixed income instruments in Brazil
5
5
  Project-URL: Source, https://github.com/crdcj/PYield
6
6
  Author-email: Carlos Carvalho <cr.cj@outlook.com>
@@ -0,0 +1 @@
1
+ __version__ = "0.36.6"
@@ -1,6 +1,8 @@
1
+ import datetime as dt
1
2
  import logging
2
3
  from typing import Literal
3
4
  from urllib.error import HTTPError
5
+ from zoneinfo import ZoneInfo
4
6
 
5
7
  import pandas as pd
6
8
 
@@ -9,10 +11,17 @@ from pyield.data_cache import get_cached_dataset
9
11
  from pyield.date_converter import DateScalar, convert_input_dates
10
12
  from pyield.retry import default_retry
11
13
 
14
+ BZ_TIMEZONE = ZoneInfo("America/Sao_Paulo")
15
+
12
16
  BOND_TYPES = Literal["LTN", "NTN-B", "NTN-C", "NTN-F", "LFT"]
17
+
13
18
  ANBIMA_URL = "https://www.anbima.com.br/informacoes/merc-sec/arqs"
19
+ ANBIMA_RTM_URL = "http://www.anbima.associados.rtm/merc_sec/arqs"
14
20
  # URL example: https://www.anbima.com.br/informacoes/merc-sec/arqs/ms240614.txt
15
21
 
22
+ # Before 13/05/2014 the file was zipped and the endpoint ended with ".exe"
23
+ FORMAT_CHANGE_DATE = pd.to_datetime("13-05-2014", dayfirst=True)
24
+
16
25
  logger = logging.getLogger(__name__)
17
26
 
18
27
 
@@ -22,10 +31,24 @@ def _bond_type_mapping(bond_type: str) -> str:
22
31
  return bond_type_mapping.get(bond_type, bond_type)
23
32
 
24
33
 
25
- def _build_file_url(date: pd.Timestamp) -> str:
34
+ def _build_file_name(date: pd.Timestamp) -> str:
26
35
  url_date = date.strftime("%y%m%d")
27
- filename = f"ms{url_date}.txt"
28
- file_url = f"{ANBIMA_URL}/{filename}"
36
+ if date < FORMAT_CHANGE_DATE:
37
+ file_name = f"ms{url_date}.exe"
38
+ else:
39
+ file_name = f"ms{url_date}.txt"
40
+ return file_name
41
+
42
+
43
+ def _build_file_url(date: pd.Timestamp) -> str:
44
+ today = dt.datetime.now(BZ_TIMEZONE).date()
45
+ business_days_count = bday.count(date, today)
46
+ if business_days_count > 5: # noqa
47
+ # For dates older than 5 business days, only the RTM data is available
48
+ logger.info(f"Trying to fetch RTM data for {date.strftime('%d/%m/%Y')}")
49
+ file_url = f"{ANBIMA_RTM_URL}/{_build_file_name(date)}"
50
+ else:
51
+ file_url = f"{ANBIMA_URL}/{_build_file_name(date)}"
29
52
  return file_url
30
53
 
31
54
 
@@ -106,7 +129,7 @@ def tpf_web_data(
106
129
  df = _read_raw_df(file_url)
107
130
  if df.empty:
108
131
  logger.info(
109
- f"No Anbima TPF secondary market data ANBIMA for {date_log}."
132
+ f"Anbima TPF secondary market data for {date_log} not available."
110
133
  "Returning empty DataFrame."
111
134
  )
112
135
  return df
@@ -1,4 +1,5 @@
1
1
  import logging
2
+ from urllib.error import HTTPError
2
3
 
3
4
  import pandas as pd
4
5
 
@@ -57,9 +58,20 @@ def _fetch_data_from_url(file_url: str) -> pd.DataFrame:
57
58
  decimal=",",
58
59
  dtype_backend="numpy_nullable",
59
60
  )
61
+ return df
62
+
63
+
64
+ def _process_df(df: pd.DataFrame) -> pd.DataFrame:
60
65
  for col in ["DATA MOV", "EMISSAO", "VENCIMENTO"]:
61
66
  df[col] = pd.to_datetime(df[col], format="%d/%m/%Y", errors="coerce")
62
67
 
68
+ df = df.rename(columns=COLUMN_MAPPING)
69
+
70
+ # Volume are empty in the original BCB file, so we calculate it
71
+ df["Volume"] = (df["Quantity"] * df["AvgPrice"]).round(2)
72
+
73
+ sort_cols = ["SettlementDate", "BondType", "MaturityDate"]
74
+ df = df.sort_values(by=sort_cols).reset_index(drop=True)
63
75
  return df
64
76
 
65
77
 
@@ -110,13 +122,34 @@ def fpd_monthly_trades(
110
122
  >>> from pyield import bc
111
123
  >>> df = bc.fpd_monthly_trades("07-01-2025") # Returns all trades for Jan/2025
112
124
  """
113
- filename = _build_filename(target_date, extragroup)
114
125
  logger.info(f"Fetching FPD trades for {target_date} from BCB")
126
+ filename = _build_filename(target_date, extragroup)
115
127
  url = f"{BASE_URL}/{filename}"
116
- df = _fetch_data_from_url(url)
117
- df = df.rename(columns=COLUMN_MAPPING)
118
- # Volume are empty in the original BCB file, so we calculate it
119
- df["Volume"] = (df["Quantity"] * df["AvgPrice"]).round(2)
120
- sort_cols = ["SettlementDate", "BondType", "MaturityDate"]
121
- df = df.sort_values(by=sort_cols).reset_index(drop=True)
122
- return df
128
+
129
+ try:
130
+ df = _fetch_data_from_url(url)
131
+ except HTTPError as e:
132
+ if e.code == 404: # noqa
133
+ # LOG ÚNICO E CONTEXTUAL PARA 404
134
+ logger.warning(
135
+ f"Recurso não encontrado (404) em {url}. Retornando DataFrame vazio."
136
+ )
137
+ return pd.DataFrame()
138
+ else:
139
+ # LOG ÚNICO E COMPLETO PARA OUTROS ERROS HTTP
140
+ logger.exception(f"Erro HTTP inesperado ({e.code}) ao acessar a URL.")
141
+ raise e
142
+
143
+ except Exception:
144
+ # LOG ÚNICO E COMPLETO PARA QUALQUER OUTRO ERRO
145
+ logger.exception(
146
+ "Ocorreu um erro não previsto durante o processamento dos dados."
147
+ )
148
+ raise
149
+
150
+ # LOG DE SUCESSO
151
+ logger.info(
152
+ f"Dados de {url} processados com sucesso. {len(df)} registros encontrados."
153
+ )
154
+
155
+ return _process_df(df)
@@ -0,0 +1,96 @@
1
+ """
2
+ Módulo de retry configurável para chamadas de API e processamento de dados.
3
+
4
+ Este módulo fornece um decorador `tenacity.retry` pré-configurado (`default_retry`)
5
+ para lidar com erros transitórios comuns ao interagir com APIs web e ao
6
+ processar os dados resultantes (ex: parsing de CSV/JSON).
7
+ """
8
+
9
+ import logging
10
+ from urllib.error import HTTPError, URLError
11
+
12
+ # Dependências de terceiros
13
+ import pandas as pd
14
+ import tenacity
15
+
16
+ # Importar tipos específicos necessários
17
+ from tenacity import RetryCallState
18
+
19
+ # --- Configuração do Logger ---
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ # --- Funções Auxiliares para Tenacity ---
24
+ def _log_before_sleep(retry_state: RetryCallState):
25
+ """
26
+ Loga uma mensagem ANTES de o Tenacity entrar em espera (sleep) entre tentativas.
27
+ """
28
+ outcome = retry_state.outcome
29
+ if not outcome or not outcome.failed:
30
+ logger.debug(
31
+ "before_sleep chamada sem 'outcome' ou para 'outcome' bem-sucedido."
32
+ )
33
+ return
34
+
35
+ exception = outcome.exception()
36
+ if not exception:
37
+ logger.debug("before_sleep chamada sem 'exception' real no outcome.")
38
+ return
39
+
40
+ next_action = retry_state.next_action
41
+ if not next_action or not hasattr(next_action, "sleep"):
42
+ logger.debug(
43
+ "before_sleep chamada sem 'next_action' ou 'sleep' em next_action."
44
+ )
45
+ return
46
+
47
+ sleep_duration = next_action.sleep
48
+
49
+ logger.warning(
50
+ f"Tentativa {retry_state.attempt_number} falhou com "
51
+ f"{type(exception).__name__}: {str(exception)[:150]}. Tentando novamente em "
52
+ f"{sleep_duration:.2f} segundos..."
53
+ )
54
+
55
+
56
+ def should_retry_exception(retry_state: RetryCallState) -> bool: # noqa
57
+ """Determina se uma exceção capturada justifica uma nova tentativa."""
58
+ if not retry_state.outcome or not retry_state.outcome.failed:
59
+ return False
60
+
61
+ exception = retry_state.outcome.exception()
62
+ if exception is None:
63
+ return False
64
+
65
+ # A decisão de retentativa pode ser muito mais concisa
66
+ match exception:
67
+ # CASOS ONDE NÃO DEVEMOS TENTAR NOVAMENTE
68
+ case HTTPError(code=404):
69
+ return False # Erro permanente
70
+ case HTTPError(code=504) if retry_state.attempt_number > 1:
71
+ return False # Já tentamos uma vez para Gateway Timeout
72
+
73
+ # CASOS ONDE DEVEMOS TENTAR NOVAMENTE
74
+ case HTTPError(code=429):
75
+ return True # Too Many Requests, vale a pena esperar
76
+ case HTTPError() if getattr(exception, "code", 0) >= 500: # noqa
77
+ return True # Erros de servidor (500, 502, 503, 504 na 1a vez)
78
+ case URLError():
79
+ return True # Erros de rede genéricos
80
+ case pd.errors.EmptyDataError() | pd.errors.ParserError():
81
+ return True # Talvez o arquivo foi baixado corrompido, tente de novo
82
+
83
+ # CASO PADRÃO: Erros inesperados ou erros de cliente (4xx) não especificados
84
+ case _:
85
+ return False
86
+
87
+
88
+ # --- Decorador Tenacity Principal ---
89
+ default_retry = tenacity.retry(
90
+ retry=should_retry_exception,
91
+ # Backoff exponencial é bom para 429
92
+ wait=tenacity.wait_exponential(multiplier=1, min=1, max=10),
93
+ stop=(tenacity.stop_after_attempt(3) | tenacity.stop_after_delay(15)),
94
+ before_sleep=_log_before_sleep,
95
+ reraise=True, # Importante para propagar o erro final se as tentativas falharem
96
+ )
@@ -1 +0,0 @@
1
- __version__ = "0.36.4"
@@ -1,174 +0,0 @@
1
- """
2
- Módulo de retry configurável para chamadas de API e processamento de dados.
3
-
4
- Este módulo fornece um decorador `tenacity.retry` pré-configurado (`default_retry`)
5
- para lidar com erros transitórios comuns ao interagir com APIs web e ao
6
- processar os dados resultantes (ex: parsing de CSV/JSON).
7
- """
8
-
9
- import logging
10
- from urllib.error import HTTPError, URLError
11
-
12
- # Dependências de terceiros
13
- import pandas as pd
14
- import tenacity
15
-
16
- # Importar tipos específicos necessários
17
- from tenacity import RetryCallState
18
-
19
- # --- Configuração do Logger ---
20
- logger = logging.getLogger(__name__)
21
-
22
-
23
- # --- Funções Auxiliares para Tenacity ---
24
- def _log_before_sleep(retry_state: RetryCallState):
25
- """
26
- Loga uma mensagem ANTES de o Tenacity entrar em espera (sleep) entre tentativas.
27
- """
28
- outcome = retry_state.outcome
29
- if not outcome or not outcome.failed:
30
- logger.debug(
31
- "before_sleep chamada sem 'outcome' ou para 'outcome' bem-sucedido."
32
- )
33
- return
34
-
35
- exception = outcome.exception()
36
- if not exception:
37
- logger.debug("before_sleep chamada sem 'exception' real no outcome.")
38
- return
39
-
40
- next_action = retry_state.next_action
41
- if not next_action or not hasattr(next_action, "sleep"):
42
- logger.debug(
43
- "before_sleep chamada sem 'next_action' ou 'sleep' em next_action."
44
- )
45
- return
46
-
47
- sleep_duration = next_action.sleep
48
-
49
- logger.warning(
50
- f"Tentativa {retry_state.attempt_number} falhou com "
51
- f"{type(exception).__name__}: {str(exception)[:150]}. Tentando novamente em "
52
- f"{sleep_duration:.2f} segundos..."
53
- )
54
-
55
-
56
- def should_retry_exception(retry_state: RetryCallState) -> bool:
57
- """Determina se uma exceção capturada justifica uma nova tentativa"""
58
- if not retry_state.outcome or not retry_state.outcome.failed:
59
- return False
60
-
61
- exception = retry_state.outcome.exception()
62
-
63
- if exception is None:
64
- # Isso não deveria acontecer se outcome.failed é True.
65
- logger.error(
66
- "should_retry_exception: outcome.failed é True,"
67
- "mas exception() retornou None."
68
- )
69
- return False
70
-
71
- attempt_number = retry_state.attempt_number
72
- # getattr é mais seguro caso a exceção não tenha 'url'
73
- url = getattr(exception, "url", "N/A")
74
-
75
- retry_decision = False
76
- # Inicializar como None para evitar log default se nenhum case corresponder
77
- log_message = None
78
- log_level = logging.ERROR # Default para não retentativa
79
-
80
- # Usando match/case como originalmente preferido
81
- match exception:
82
- case HTTPError(code=404):
83
- log_message = (
84
- f"Tentativa {attempt_number}: Recurso não encontrado (404) em {url}. "
85
- f"Não tentará novamente."
86
- )
87
- retry_decision = False
88
- log_level = logging.INFO
89
-
90
- case HTTPError(code=429): # ADICIONADO: Tratamento para Too Many Requests
91
- log_message = (
92
- f"Tentativa {attempt_number}: Too Many Requests (429) da API em {url}. "
93
- f"API pediu para aguardar. Tentando novamente."
94
- )
95
- retry_decision = True
96
- log_level = logging.WARNING
97
-
98
- # Gateway Timeout, primeira tentativa
99
- case HTTPError(code=504) if attempt_number == 1:
100
- log_message = (
101
- f"Tentativa {attempt_number}: Gateway Timeout (504) da API em {url}. "
102
- f"Tentará novamente uma vez."
103
- )
104
- retry_decision = True
105
- log_level = logging.WARNING
106
-
107
- case HTTPError(code=504): # Gateway Timeout, tentativas subsequentes
108
- log_message = (
109
- f"Tentativa {attempt_number}: Gateway Timeout (504) persistiu em {url}."
110
- f"API parece indisponível. Desistindo."
111
- )
112
- retry_decision = False
113
- log_level = logging.ERROR
114
-
115
- case HTTPError() as http_err: # Outros erros HTTP
116
- # Esta regra genérica para HTTPError retentará outros códigos HTTP.
117
- # Por exemplo, 500, 502, 503 (geralmente bom para retry)
118
- # mas também 400, 401, 403 (geralmente não bom para retry).
119
- # Se precisar de mais granularidade, adicione cases específicos acima deste.
120
- log_message = (
121
- f"Tentativa {attempt_number}: Erro HTTP {http_err.code} "
122
- f"({http_err.reason}) encontrado para {url}. "
123
- "Pode ser transitório. Tentando novamente."
124
- )
125
- retry_decision = True
126
- log_level = logging.WARNING
127
-
128
- # Erros de rede mais genéricos (e.g., DNS falhou, conexão recusada)
129
- case URLError():
130
- log_message = (
131
- f"Tentativa {attempt_number}: Erro de rede recuperável "
132
- f"({type(exception).__name__}: {str(exception)[:100]}) para {url}. "
133
- f"Tentando novamente."
134
- )
135
- retry_decision = True
136
- log_level = logging.WARNING
137
-
138
- # Usando o operador | para combinar tipos de exceção no case
139
- case pd.errors.EmptyDataError() | pd.errors.ParserError():
140
- log_message = (
141
- f"Tentativa {attempt_number}: Erro de parsing de dados "
142
- f"({type(exception).__name__}). Tentando novamente."
143
- )
144
- retry_decision = True
145
- log_level = logging.WARNING
146
-
147
- case _: # Exceção não mapeada/inesperada
148
- # Mensagem para o log de exceção
149
- log_message_exc = (
150
- f"Tentativa {attempt_number}: Erro não recuperável/inesperado "
151
- f"({type(exception).__name__}: {str(exception)[:100]}) "
152
- f"ao processar {url}. Desistindo."
153
- )
154
- # Sempre incluir traceback para erros inesperados
155
- logger.exception(log_message_exc)
156
- log_message = None # Evita log duplicado pela seção logger.log abaixo
157
- retry_decision = False
158
- log_level = logging.ERROR # Já é o default, mas explícito aqui
159
-
160
- if log_message: # Loga a mensagem formatada se uma foi definida
161
- logger.log(log_level, log_message)
162
-
163
- return retry_decision
164
-
165
-
166
- # --- Decorador Tenacity Principal ---
167
- default_retry = tenacity.retry(
168
- retry=should_retry_exception,
169
- # Backoff exponencial é bom para 429
170
- wait=tenacity.wait_exponential(multiplier=1, min=1, max=10),
171
- stop=(tenacity.stop_after_attempt(3) | tenacity.stop_after_delay(15)),
172
- before_sleep=_log_before_sleep,
173
- reraise=True, # Importante para propagar o erro final se as tentativas falharem
174
- )
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