PYield 0.10.2__tar.gz → 0.11.0__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 (37) hide show
  1. {pyield-0.10.2 → pyield-0.11.0}/PKG-INFO +6 -8
  2. {pyield-0.10.2 → pyield-0.11.0}/README.md +5 -7
  3. pyield-0.11.0/pyield/__about__.py +1 -0
  4. {pyield-0.10.2 → pyield-0.11.0}/pyield/__init__.py +3 -2
  5. {pyield-0.10.2 → pyield-0.11.0}/pyield/bday.py +6 -7
  6. {pyield-0.10.2 → pyield-0.11.0}/pyield/bonds/lft.py +15 -7
  7. {pyield-0.10.2 → pyield-0.11.0}/pyield/bonds/ltn.py +16 -10
  8. {pyield-0.10.2 → pyield-0.11.0}/pyield/bonds/ntnb.py +23 -17
  9. {pyield-0.10.2 → pyield-0.11.0}/pyield/bonds/ntnf.py +23 -17
  10. {pyield-0.10.2 → pyield-0.11.0}/pyield/bonds/utils.py +45 -8
  11. {pyield-0.10.2 → pyield-0.11.0}/pyield/date_converter.py +3 -13
  12. pyield-0.11.0/pyield/fetchers/__init__.py +6 -0
  13. pyield-0.10.2/pyield/fetchers/anbima_data.py → pyield-0.11.0/pyield/fetchers/anbima.py +77 -25
  14. {pyield-0.10.2 → pyield-0.11.0}/pyield/fetchers/futures_data/__init__.py +2 -3
  15. {pyield-0.10.2 → pyield-0.11.0}/pyield/fetchers/indicators.py +11 -15
  16. {pyield-0.10.2 → pyield-0.11.0}/pyield/interpolator.py +22 -23
  17. {pyield-0.10.2 → pyield-0.11.0}/pyproject.toml +1 -1
  18. pyield-0.10.2/pyield/__about__.py +0 -1
  19. pyield-0.10.2/pyield/fetchers/__init__.py +0 -6
  20. {pyield-0.10.2 → pyield-0.11.0}/LICENSE +0 -0
  21. {pyield-0.10.2 → pyield-0.11.0}/pyield/bonds/__init__.py +0 -0
  22. {pyield-0.10.2 → pyield-0.11.0}/pyield/fetchers/futures_data/common.py +0 -0
  23. {pyield-0.10.2 → pyield-0.11.0}/pyield/fetchers/futures_data/historical.py +0 -0
  24. {pyield-0.10.2 → pyield-0.11.0}/pyield/fetchers/futures_data/intraday.py +0 -0
  25. {pyield-0.10.2 → pyield-0.11.0}/pyield/fetchers/futures_data/xml.py +0 -0
  26. {pyield-0.10.2 → pyield-0.11.0}/pyield/fetchers/projections.py +0 -0
  27. {pyield-0.10.2 → pyield-0.11.0}/pyield/holidays/__init__.py +0 -0
  28. {pyield-0.10.2 → pyield-0.11.0}/pyield/holidays/br_holidays_new.txt +0 -0
  29. {pyield-0.10.2 → pyield-0.11.0}/pyield/holidays/br_holidays_old.txt +0 -0
  30. {pyield-0.10.2 → pyield-0.11.0}/pyield/holidays/holidays_manager.py +0 -0
  31. {pyield-0.10.2 → pyield-0.11.0}/pyield/py.typed +0 -0
  32. {pyield-0.10.2 → pyield-0.11.0}/tests/__init__.py +0 -0
  33. {pyield-0.10.2 → pyield-0.11.0}/tests/data/SPRD231222.zip +0 -0
  34. {pyield-0.10.2 → pyield-0.11.0}/tests/data/SPRD240426.zip +0 -0
  35. {pyield-0.10.2 → pyield-0.11.0}/tests/test_bday.py +0 -0
  36. {pyield-0.10.2 → pyield-0.11.0}/tests/test_futures.py +0 -0
  37. {pyield-0.10.2 → pyield-0.11.0}/tests/test_futures_xml.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: PYield
3
- Version: 0.10.2
3
+ Version: 0.11.0
4
4
  Summary: A Python library for analysis of fixed income instruments in Brazil
5
5
  Keywords: fixed-income, brazil, finance, analysis, bonds
6
6
  Author-Email: Carlos Carvalho <cr.cj@outlook.com>
@@ -47,15 +47,13 @@ Description-Content-Type: text/markdown
47
47
 
48
48
  # PYield: Brazilian Fixed Income Toolkit
49
49
 
50
- ## Introduction
50
+ PYield is a Python library designed for the analysis of Brazilian fixed income instruments. Leveraging the power of popular Python libraries like Pandas and Requests, PYield simplifies the process of obtaining and processing data from key sources such as ANBIMA, BCB, IBGE and B3.
51
51
 
52
- Welcome to PYield, a Python library designed for the analysis of fixed income instruments in Brazil. This library is tailored for financial analysts, researchers, and enthusiasts interested in the Brazilian fixed income market. Leveraging the power of popular Python libraries like Pandas and Requests, PYield simplifies the process of obtaining and processing data from key sources such as ANBIMA, BCB, IBGE and B3.
52
+ Documentation: [https://crdcj.github.io/PYield/](https://crdcj.github.io/PYield/)
53
53
 
54
- ## Documentation
54
+ Source Code: [https://github.com/crdcj/PYield](https://github.com/crdcj/PYield)
55
55
 
56
- For the full documentation, visit [here](https://crdcj.github.io/PYield/).
57
-
58
- ## Features
56
+ ## Key Features
59
57
 
60
58
  - **Data Collection**: Automated fetching of data from ANBIMA and B3.
61
59
  - **Data Processing**: Efficient processing and normalization of fixed income data.
@@ -94,7 +92,7 @@ date = pd.to_datetime("05-31-2024", format="%m-%d-%Y")
94
92
  >>> ntnb.quote("31-05-2024", "15-08-2060", 0.061878)
95
93
  99.5341
96
94
 
97
- # Calculate the DI Spread of a LTN bonds in a given date
95
+ # Calculate the DI Spread of NTN-F bonds in a given date
98
96
  >>> ntnf.di_spreads("17-07-2024")
99
97
  2025-01-01 -2.31
100
98
  2027-01-01 -1.88
@@ -4,15 +4,13 @@
4
4
 
5
5
  # PYield: Brazilian Fixed Income Toolkit
6
6
 
7
- ## Introduction
7
+ PYield is a Python library designed for the analysis of Brazilian fixed income instruments. Leveraging the power of popular Python libraries like Pandas and Requests, PYield simplifies the process of obtaining and processing data from key sources such as ANBIMA, BCB, IBGE and B3.
8
8
 
9
- Welcome to PYield, a Python library designed for the analysis of fixed income instruments in Brazil. This library is tailored for financial analysts, researchers, and enthusiasts interested in the Brazilian fixed income market. Leveraging the power of popular Python libraries like Pandas and Requests, PYield simplifies the process of obtaining and processing data from key sources such as ANBIMA, BCB, IBGE and B3.
9
+ Documentation: [https://crdcj.github.io/PYield/](https://crdcj.github.io/PYield/)
10
10
 
11
- ## Documentation
11
+ Source Code: [https://github.com/crdcj/PYield](https://github.com/crdcj/PYield)
12
12
 
13
- For the full documentation, visit [here](https://crdcj.github.io/PYield/).
14
-
15
- ## Features
13
+ ## Key Features
16
14
 
17
15
  - **Data Collection**: Automated fetching of data from ANBIMA and B3.
18
16
  - **Data Processing**: Efficient processing and normalization of fixed income data.
@@ -51,7 +49,7 @@ date = pd.to_datetime("05-31-2024", format="%m-%d-%Y")
51
49
  >>> ntnb.quote("31-05-2024", "15-08-2060", 0.061878)
52
50
  99.5341
53
51
 
54
- # Calculate the DI Spread of a LTN bonds in a given date
52
+ # Calculate the DI Spread of NTN-F bonds in a given date
55
53
  >>> ntnf.di_spreads("17-07-2024")
56
54
  2025-01-01 -2.31
57
55
  2027-01-01 -1.88
@@ -0,0 +1 @@
1
+ __version__ = "0.11.0"
@@ -1,11 +1,12 @@
1
1
  from . import bday, interpolator
2
2
  from .__about__ import __version__
3
3
  from .bonds import lft, ltn, ntnb, ntnf
4
- from .fetchers import anbima, futures, indicator, projection
4
+ from .fetchers import anbima_data, anbima_rates, futures, indicator, projection
5
5
 
6
6
  __all__ = [
7
7
  "__version__",
8
- "anbima",
8
+ "anbima_data",
9
+ "anbima_rates",
9
10
  "bday",
10
11
  "futures",
11
12
  "indicator",
@@ -1,5 +1,5 @@
1
1
  from datetime import datetime
2
- from typing import Any, Literal, overload
2
+ from typing import Literal, overload
3
3
 
4
4
  import numpy as np
5
5
  import pandas as pd
@@ -262,7 +262,6 @@ def generate(
262
262
  end: SingleDateTypes | None = None,
263
263
  inclusive: Literal["both", "neither", "left", "right"] = "both",
264
264
  holiday_list: Literal["old", "new", "infer"] = "infer",
265
- **kwargs: dict[str, Any],
266
265
  ) -> pd.Series:
267
266
  """
268
267
  Generates a Series of business days between a `start` and `end` date, considering
@@ -309,15 +308,15 @@ def generate(
309
308
  )
310
309
  selected_holidays_list = selected_holidays.to_list()
311
310
 
312
- result = pd.bdate_range(
313
- normalized_start,
314
- normalized_end,
311
+ # Get the result as a DatetimeIndex (dti)
312
+ result_dti = pd.bdate_range(
313
+ start=normalized_start,
314
+ end=normalized_end,
315
315
  freq="C",
316
316
  inclusive=inclusive,
317
317
  holidays=selected_holidays_list,
318
- **kwargs,
319
318
  )
320
- return pd.Series(result)
319
+ return pd.Series(result_dti.values)
321
320
 
322
321
 
323
322
  def is_business_day(date: SingleDateTypes | None = None) -> bool:
@@ -16,7 +16,7 @@ def anbima_data(reference_date: str | pd.Timestamp) -> pd.DataFrame:
16
16
  Returns:
17
17
  pd.DataFrame: A DataFrame containing the Anbima data for the reference date.
18
18
  """
19
- return ft.anbima(bond_type="LFT", reference_date=reference_date)
19
+ return ft.anbima_data(reference_date, "LFT")
20
20
 
21
21
 
22
22
  def anbima_rates(reference_date: str | pd.Timestamp) -> pd.Series:
@@ -29,12 +29,20 @@ def anbima_rates(reference_date: str | pd.Timestamp) -> pd.Series:
29
29
  Returns:
30
30
  pd.Series: A Series containing the rates indexed by maturity date.
31
31
  """
32
- df = anbima_data(reference_date)
33
- # Set MaturityDate as index
34
- df = df.set_index("MaturityDate")
35
- df.index.name = None
36
- # Return as Series
37
- return df["IndicativeRate"]
32
+ return ut.get_anbima_rates(reference_date, "LFT")
33
+
34
+
35
+ def anbima_historical_rates(maturity_date: str | pd.Timestamp) -> pd.Series:
36
+ """
37
+ Fetch historical LFT Anbima indicative rates for the given maturity date.
38
+
39
+ Args:
40
+ maturity_date (str | pd.Timestamp): The maturity date for fetching the data.
41
+
42
+ Returns:
43
+ pd.Series: A Series containing the rates indexed by reference date.
44
+ """
45
+ return ut.get_anbima_historical_rates("LFT", maturity_date)
38
46
 
39
47
 
40
48
  def quote(
@@ -18,7 +18,7 @@ def anbima_data(reference_date: str | pd.Timestamp) -> pd.DataFrame:
18
18
  Returns:
19
19
  pd.DataFrame: A DataFrame containing the Anbima data for the reference date.
20
20
  """
21
- return ft.anbima(bond_type="LTN", reference_date=reference_date)
21
+ return ft.anbima_data(reference_date, "LTN")
22
22
 
23
23
 
24
24
  def anbima_rates(reference_date: str | pd.Timestamp) -> pd.Series:
@@ -31,12 +31,20 @@ def anbima_rates(reference_date: str | pd.Timestamp) -> pd.Series:
31
31
  Returns:
32
32
  pd.Series: A Series containing the rates indexed by maturity date.
33
33
  """
34
- df = anbima_data(reference_date)
35
- # Set MaturityDate as index
36
- df = df.set_index("MaturityDate")
37
- df.index.name = None
38
- # Return as Series
39
- return df["IndicativeRate"]
34
+ return ut.get_anbima_rates(reference_date, "LTN")
35
+
36
+
37
+ def anbima_historical_rates(maturity_date: str | pd.Timestamp) -> pd.Series:
38
+ """
39
+ Fetch historical LTN Anbima indicative rates for the given maturity date.
40
+
41
+ Args:
42
+ maturity_date (str | pd.Timestamp): The maturity date for fetching the data.
43
+
44
+ Returns:
45
+ pd.Series: A Series containing the rates for the given maturity date.
46
+ """
47
+ return ut.get_anbima_historical_rates("LTN", maturity_date)
40
48
 
41
49
 
42
50
  def price(
@@ -82,13 +90,12 @@ def price(
82
90
  return ut.truncate(FACE_VALUE / discount_factor, 6)
83
91
 
84
92
 
85
- def di_spreads(reference_date: str | pd.Timestamp | None = None) -> pd.Series:
93
+ def di_spreads(reference_date: str | pd.Timestamp) -> pd.Series:
86
94
  """
87
95
  Calculates the DI spread for the LTN based on ANBIMA's indicative rates.
88
96
 
89
97
  This function fetches the indicative rates for the NTN-F bonds and the DI futures
90
98
  rates and calculates the spread between these rates in basis points.
91
- If no reference date is provided, the function uses the last business day available.
92
99
 
93
100
  Parameters:
94
101
  reference_date (str | pd.Timestamp, optional): The reference date for the
@@ -105,5 +112,4 @@ def di_spreads(reference_date: str | pd.Timestamp | None = None) -> pd.Series:
105
112
  df.query("BondType == 'LTN'", inplace=True)
106
113
  df.sort_values(["MaturityDate"], ignore_index=True, inplace=True)
107
114
  df.set_index("MaturityDate", inplace=True)
108
- df.index.name = None
109
115
  return df["DISpread"]
@@ -5,6 +5,7 @@ from .. import bday
5
5
  from .. import date_converter as dc
6
6
  from .. import fetchers as ft
7
7
  from .. import interpolator as it
8
+ from . import ltn
8
9
  from . import utils as ut
9
10
 
10
11
  """
@@ -29,7 +30,7 @@ def anbima_data(reference_date: str | pd.Timestamp) -> pd.DataFrame:
29
30
  Returns:
30
31
  pd.DataFrame: A DataFrame containing the Anbima data for the reference date.
31
32
  """
32
- return ft.anbima(bond_type="NTN-B", reference_date=reference_date)
33
+ return ft.anbima_data(reference_date, "NTN-B")
33
34
 
34
35
 
35
36
  def anbima_rates(reference_date: str | pd.Timestamp) -> pd.Series:
@@ -42,12 +43,20 @@ def anbima_rates(reference_date: str | pd.Timestamp) -> pd.Series:
42
43
  Returns:
43
44
  pd.Series: A Series containing the rates indexed by maturity date.
44
45
  """
45
- df = anbima_data(reference_date)
46
- # Set MaturityDate as index
47
- df = df.set_index("MaturityDate")
48
- df.index.name = None
49
- # Return as Series
50
- return df["IndicativeRate"]
46
+ return ut.get_anbima_rates(reference_date, "NTN-B")
47
+
48
+
49
+ def anbima_historical_rates(maturity_date: str | pd.Timestamp) -> pd.Series:
50
+ """
51
+ Fetch historical NTN-B Anbima indicative rates for the given maturity date.
52
+
53
+ Args:
54
+ maturity_date (str | pd.Timestamp): The maturity date for fetching the data.
55
+
56
+ Returns:
57
+ pd.Series: A Series containing the rates for the given maturity date.
58
+ """
59
+ return ut.get_anbima_historical_rates("NTN-B", maturity_date)
51
60
 
52
61
 
53
62
  def _coupon_dates_map(
@@ -319,10 +328,8 @@ def anbima_spot_rates(
319
328
  pd.DataFrame: DataFrame containing the maturity dates and corresponding real
320
329
  spot rates.
321
330
  """
322
- df_ytm = anbima_rates(reference_date)
323
- maturity_dates = df_ytm["MaturityDate"]
324
- ytm_rates = df_ytm["IndicativeRate"]
325
- return spot_rates(settlement_date, maturity_dates, ytm_rates)
331
+ ytm_rates = anbima_rates(reference_date)
332
+ return spot_rates(settlement_date, ytm_rates)
326
333
 
327
334
 
328
335
  def _get_nir_df(reference_date: pd.Timestamp) -> pd.DataFrame:
@@ -368,13 +375,12 @@ def _get_nir_df(reference_date: pd.Timestamp) -> pd.DataFrame:
368
375
  if reference_date == today:
369
376
  # If the reference date is today, use the previous business day
370
377
  anbima_date = bday.offset(reference_date, -1)
371
- df_pre = ut.di_spreads(reference_date=anbima_date)
372
- df_pre.query("BondType == 'LTN'", inplace=True)
373
- df_pre["MaturityDate"] = bday.offset(df_pre["MaturityDate"], 0)
374
- df_pre["DISpread"] /= 10_000 # Remove BPS (basis points) from the spread
375
- df_pre.drop(columns=["BondType"], inplace=True)
376
378
 
377
- df = pd.merge_asof(df, df_pre, left_on="ExpirationDate", right_on="MaturityDate")
379
+ df_ltn = ltn.di_spreads(reference_date=anbima_date).reset_index()
380
+ df_ltn["MaturityDate"] = bday.offset(df_ltn["MaturityDate"], 0)
381
+ df_ltn["DISpread"] /= 10_000 # Remove BPS (basis points) from the spread
382
+
383
+ df = pd.merge_asof(df, df_ltn, left_on="ExpirationDate", right_on="MaturityDate")
378
384
  df["NIR_PRE"] = df["NIR_DI"] + df["DISpread"]
379
385
 
380
386
  return df
@@ -142,18 +142,19 @@ def _coupon_dates_map(
142
142
  reference_year = start.year
143
143
  first_coupon_date = pd.Timestamp(f"{reference_year}-01-01")
144
144
 
145
- # Generate coupon dates
146
- dates = pd.date_range(start=first_coupon_date, end=end, freq="6MS")
145
+ # Generate coupon dates as a DatetimeIndex (dti)
146
+ dates_dti = pd.date_range(start=first_coupon_date, end=end, freq="6MS")
147
+
148
+ # Convert to Series and adjust for business days if necessary
149
+ dates = pd.Series(dates_dti.values)
147
150
 
148
151
  # First coupon date must be after the reference date
149
152
  dates = dates[dates >= start]
150
153
 
151
- # Convert to Series and adjust for business days if necessary
152
- dates = pd.Series(dates).reset_index(drop=True)
153
154
  if adjust_for_bdays:
154
155
  dates = bday.offset(dates, 0)
155
156
 
156
- return dates
157
+ return dates.reset_index(drop=True)
157
158
 
158
159
 
159
160
  def anbima_data(reference_date: str | pd.Timestamp) -> pd.DataFrame:
@@ -166,7 +167,7 @@ def anbima_data(reference_date: str | pd.Timestamp) -> pd.DataFrame:
166
167
  Returns:
167
168
  pd.DataFrame: A DataFrame containing the Anbima data for the reference date.
168
169
  """
169
- return ft.anbima(bond_type="NTN-F", reference_date=reference_date)
170
+ return ft.anbima_data(reference_date, "NTN-F")
170
171
 
171
172
 
172
173
  def anbima_rates(reference_date: str | pd.Timestamp) -> pd.Series:
@@ -179,12 +180,20 @@ def anbima_rates(reference_date: str | pd.Timestamp) -> pd.Series:
179
180
  Returns:
180
181
  pd.Series: A Series containing the rates indexed by maturity date.
181
182
  """
182
- df = anbima_data(reference_date)
183
- # Set MaturityDate as index
184
- df = df.set_index("MaturityDate")
185
- df.index.name = None
186
- # Return as Series
187
- return df["IndicativeRate"]
183
+ return ut.get_anbima_rates(reference_date, "NTN-F")
184
+
185
+
186
+ def anbima_historical_rates(maturity_date: str | pd.Timestamp) -> pd.Series:
187
+ """
188
+ Fetch historical NTN-F Anbima indicative rates for the given maturity date.
189
+
190
+ Args:
191
+ maturity_date (str | pd.Timestamp): The maturity date for fetching the data.
192
+
193
+ Returns:
194
+ pd.Series: A Series containing the rates for the given maturity date.
195
+ """
196
+ return ut.get_anbima_historical_rates("NTN-F", maturity_date)
188
197
 
189
198
 
190
199
  def _calculate_coupons_pv(
@@ -279,18 +288,16 @@ def spot_rates(
279
288
  return df_spot
280
289
 
281
290
 
282
- def di_spreads(reference_date: str | pd.Timestamp | None = None) -> pd.Series:
291
+ def di_spreads(reference_date: str | pd.Timestamp) -> pd.Series:
283
292
  """
284
293
  Calculates the DI spread for the NTN-F based on ANBIMA's indicative rates.
285
294
 
286
295
  This function fetches the indicative rates for the NTN-F bonds and the DI futures
287
296
  rates and calculates the spread between these rates in basis points.
288
- If no reference date is provided, the function uses the last business day available.
289
297
 
290
298
  Parameters:
291
299
  reference_date (str | pd.Timestamp, optional): The reference date for the
292
- spread calculation. If None or not provided, defaults to the previous
293
- business day according to the Brazilian calendar.
300
+ spread calculation.
294
301
 
295
302
  Returns:
296
303
  pd.Series: A pandas series containing the calculated spreads in basis points
@@ -302,5 +309,4 @@ def di_spreads(reference_date: str | pd.Timestamp | None = None) -> pd.Series:
302
309
  df.query("BondType == 'NTN-F'", inplace=True)
303
310
  df.sort_values(["MaturityDate"], ignore_index=True, inplace=True)
304
311
  df.set_index("MaturityDate", inplace=True)
305
- df.index.name = None
306
312
  return df["DISpread"]
@@ -1,9 +1,20 @@
1
+ from typing import overload
2
+
1
3
  import numpy as np
2
4
  import pandas as pd
3
5
 
6
+ from .. import date_converter as dc
4
7
  from .. import fetchers as ft
5
8
 
6
9
 
10
+ @overload
11
+ def truncate(values: float, decimal_places: int) -> float: ...
12
+
13
+
14
+ @overload
15
+ def truncate(values: pd.Series, decimal_places: int) -> pd.Series: ...
16
+
17
+
7
18
  def truncate(values: float | pd.Series, decimal_places: int) -> float | pd.Series:
8
19
  """
9
20
  Truncate a float or a Pandas Series to the specified decimal place.
@@ -68,20 +79,46 @@ def di_spreads(reference_date: pd.Timestamp) -> pd.DataFrame:
68
79
  df_di["MaturityDate"] = df_di["MaturityDate"].dt.to_period("M").dt.to_timestamp()
69
80
 
70
81
  # Fetch bond rates, filtering for LTN and NTN-F types
71
- df_anbima = ft.anbima(["LTN", "NTN-F"], reference_date)
72
- # Keep only the relevant columns for the output
73
- keep_columns = ["ReferenceDate", "BondType", "MaturityDate", "IndicativeRate"]
74
- df_anbima = df_anbima[keep_columns].copy()
82
+ df_ltn = ft.anbima_rates(reference_date, "LTN")
83
+ df_ntnf = ft.anbima_rates(reference_date, "NTN-F")
84
+ df_pre = pd.concat([df_ltn, df_ntnf], ignore_index=True)
75
85
 
76
86
  # Merge bond and DI rates by maturity date to calculate spreads
77
- df_final = pd.merge(df_anbima, df_di, how="left", on="MaturityDate")
87
+ df_spreads = pd.merge(df_pre, df_di, how="left", on="MaturityDate")
78
88
 
79
89
  # Calculate the DI spread as the difference between indicative and settlement rates
80
- df_final["DISpread"] = df_final["IndicativeRate"] - df_final["SettlementRate"]
90
+ df_spreads["DISpread"] = df_spreads["IndicativeRate"] - df_spreads["SettlementRate"]
81
91
 
82
92
  # Convert spread to basis points for clarity
83
- df_final["DISpread"] = (10_000 * df_final["DISpread"]).round(2)
93
+ df_spreads["DISpread"] = (10_000 * df_spreads["DISpread"]).round(2)
84
94
 
85
95
  # Prepare and return the final sorted DataFrame
86
96
  select_columns = ["BondType", "ReferenceDate", "MaturityDate", "DISpread"]
87
- return df_final[select_columns].sort_values(["MaturityDate"], ignore_index=True)
97
+ return df_spreads[select_columns].sort_values(["MaturityDate"], ignore_index=True)
98
+
99
+
100
+ def get_anbima_rates(
101
+ reference_date: str | pd.Timestamp,
102
+ bond_type: str,
103
+ ) -> pd.Series:
104
+ df = ft.anbima_rates(reference_date, bond_type)
105
+ df.drop(columns=["BondType"], inplace=True)
106
+ # Set MaturityDate as index
107
+ df = df.set_index("MaturityDate")
108
+ # Return as Series
109
+ return df["IndicativeRate"]
110
+
111
+
112
+ def get_anbima_historical_rates(
113
+ bond_type: str,
114
+ maturity_date: str | pd.Timestamp,
115
+ ) -> pd.Series:
116
+ maturity_date = dc.convert_date(maturity_date)
117
+ df = ft.anbima_rates(bond_type=bond_type)
118
+ df.query("MaturityDate == @maturity_date", inplace=True)
119
+ df.drop(columns=["BondType", "MaturityDate"], inplace=True)
120
+ df.sort_values(["ReferenceDate"], ignore_index=True, inplace=True)
121
+ # Set ReferenceDate as index
122
+ df = df.set_index("ReferenceDate")
123
+ # Return as Series
124
+ return df["IndicativeRate"]
@@ -3,8 +3,6 @@ import re
3
3
  import numpy as np
4
4
  import pandas as pd
5
5
 
6
- from . import bday
7
-
8
6
 
9
7
  def _starts_with_year(date_str: str) -> bool:
10
8
  """Check if the date string starts with a four-digit year."""
@@ -14,17 +12,13 @@ def _starts_with_year(date_str: str) -> bool:
14
12
  return bool(re.match(r"^\d{4}-", date_str))
15
13
 
16
14
 
17
- def convert_date(
18
- input_date: str | pd.Timestamp | np.datetime64 | None = None,
19
- ) -> pd.Timestamp:
15
+ def convert_date(input_date: str | pd.Timestamp | np.datetime64) -> pd.Timestamp:
20
16
  """
21
- Convert a date to pandas Timestamp adjusted to midnight. If no date is
22
- provided, it defaults to the last business day available.
17
+ Convert a date to pandas Timestamp adjusted to midnight.
23
18
 
24
19
  Args:
25
20
  reference_date (str | pd.Timestamp | np.datetime64 | None): The date to
26
- convert. If None, it defaults to the last business day. If str, it should be
27
- with day first format (e.g. "31-05-2024").
21
+ convert. If str, it should be with day first format (e.g. "31-05-2024").
28
22
 
29
23
  Returns:
30
24
  pd.Timestamp: A normalized pandas Timestamp.
@@ -54,10 +48,6 @@ def convert_date(
54
48
  case np.datetime64():
55
49
  # Convert numpy datetime to pandas Timestamp
56
50
  output_date = pd.Timestamp(input_date)
57
- case None:
58
- # If no date is provided, use the last business day available
59
- today = pd.Timestamp.today()
60
- output_date = bday.offset(dates=today, offset=0, roll="backward")
61
51
  case _:
62
52
  raise ValueError(f"Date format not recognized: {input_date}")
63
53
  # Normalize the final date to midnight
@@ -0,0 +1,6 @@
1
+ from .anbima import anbima_data, anbima_rates
2
+ from .futures_data import futures
3
+ from .indicators import indicator
4
+ from .projections import projection
5
+
6
+ __all__ = ["futures", "anbima_data", "anbima_rates", "indicator", "projection"]
@@ -9,6 +9,9 @@ from .. import date_converter as dc
9
9
  # URL Constants
10
10
  ANBIMA_URL = "https://www.anbima.com.br/informacoes/merc-sec/arqs/"
11
11
  # URL example: https://www.anbima.com.br/informacoes/merc-sec/arqs/ms240614.txt
12
+ RATES_URL = (
13
+ "https://raw.githubusercontent.com/crdcj/PYield/main/data/anbima_rates.csv.gz"
14
+ )
12
15
 
13
16
 
14
17
  def _get_file_content(reference_date: pd.Timestamp) -> str:
@@ -90,9 +93,9 @@ def _process_raw_df(df_raw: pd.DataFrame) -> pd.DataFrame:
90
93
  return df.sort_values(["BondType", "MaturityDate"], ignore_index=True)
91
94
 
92
95
 
93
- def anbima(
94
- bond_type: str | list[str] | None = None,
95
- reference_date: str | pd.Timestamp | None = None,
96
+ def anbima_data(
97
+ reference_date: str | pd.Timestamp,
98
+ bond_type: str | None = None,
96
99
  ) -> pd.DataFrame:
97
100
  """
98
101
  Fetches indicative treasury rates from ANBIMA for a specified reference date.
@@ -101,24 +104,20 @@ def anbima(
101
104
  ANBIMA, processing them into a structured pandas DataFrame.
102
105
 
103
106
  Args:
104
- bond_type (str, optional): The type of bond to filter by. Defaults to None.
105
107
  reference_date (str | pd.Timestamp | None, optional): The date for which to
106
- fetch the indicative rates. If a string is provided, it should be in the
107
- format 'dd-mm-yyyy'. Defaults last business day if None.
108
+ fetch the indicative rates. If a string is provided, it should be in the
109
+ format 'dd-mm-yyyy'.
110
+ bond_type (str, optional): The type of bond to filter by. Defaults to None.
108
111
 
109
112
  Returns:
110
113
  pd.DataFrame: A DataFrame containing the processed indicative rates for the
111
114
  given reference date.
112
115
 
113
- Raises:
114
- ValueError: If the data could not be fetched for the given reference date or if
115
- an unsupported bond type is provided.
116
-
117
116
  Examples:
118
- # Fetch ANBIMA data for all bonds using the last business day available
119
- >>> yd.anbima("18-06-2024")
120
- # Fetch ANBIMA data for NTN-B bonds using a specific reference date
121
- >>> yd.anbima("NTN-B", "18-06-2024")
117
+ # Fetch ANBIMA data for all bonds in a specific reference date
118
+ >>> anbima_rates("18-06-2024")
119
+ # Fetch ANBIMA data for NTN-B bonds in a specific reference date
120
+ >>> anbima_rates("18-06-2024", "NTN-B")
122
121
  """
123
122
  # Normalize the reference date
124
123
  normalized_date = dc.convert_date(reference_date)
@@ -132,18 +131,71 @@ def anbima(
132
131
 
133
132
  df = _process_raw_df(df)
134
133
 
135
- # If bond type is not specified, return the full DataFrame
136
134
  if bond_type is None:
137
135
  return df
138
-
139
- # Format bond type as a list of uppercase strings
140
- if isinstance(bond_type, str):
141
- bond_list = [bond_type]
142
- elif isinstance(bond_type, list):
143
- bond_list = bond_type
144
136
  else:
145
- msg = "Invalid bond type format. Must be a string or a list of strings."
146
- raise ValueError(msg)
147
- bond_list = [bt.upper() for bt in bond_list]
137
+ df.query("BondType == @bond_type", inplace=True)
138
+ return df.reset_index(drop=True)
139
+
140
+
141
+ class RatesData:
142
+ _df = pd.DataFrame()
143
+
144
+ @classmethod
145
+ def _initialize_dataframe(cls):
146
+ if cls._df.empty:
147
+ print("Loading ANBIMA rates data for the first time.")
148
+ cls._df = pd.read_csv(
149
+ RATES_URL, parse_dates=["ReferenceDate", "MaturityDate"]
150
+ )
151
+ cls._df["IndicativeRate"] /= 100
152
+
153
+ @classmethod
154
+ def _get_dataframe(cls):
155
+ cls._initialize_dataframe()
156
+ return cls._df.copy()
157
+
158
+ @classmethod
159
+ def rates(
160
+ cls,
161
+ reference_date: pd.Timestamp | None = None,
162
+ bond_type: str | None = None,
163
+ ) -> pd.DataFrame:
164
+ df = cls._get_dataframe()
165
+ if reference_date is not None:
166
+ df.query("ReferenceDate == @reference_date", inplace=True)
167
+ if bond_type is not None:
168
+ df.query("BondType == @bond_type", inplace=True)
169
+
170
+ return df.sort_values(["BondType", "MaturityDate"], ignore_index=True)
171
+
172
+
173
+ def anbima_rates(
174
+ reference_date: str | pd.Timestamp | None = None,
175
+ bond_type: str | None = None,
176
+ ) -> pd.DataFrame:
177
+ """
178
+ Fetches indicative treasury rates from ANBIMA for a specified reference date.
179
+
180
+ This function retrieves the indicative rates for Brazilian treasury securities from
181
+ ANBIMA, processing them into a structured pandas DataFrame.
148
182
 
149
- return df.query("BondType in @bond_list").reset_index(drop=True)
183
+ Args:
184
+ reference_date (str | pd.Timestamp | None, optional): The date for which to
185
+ fetch the indicative rates. If a string is provided, it should be in the
186
+ format 'dd-mm-yyyy'.
187
+ bond_type (str, optional): The type of bond to filter by. Defaults to None.
188
+
189
+ Returns:
190
+ pd.DataFrame: A DataFrame containing the processed indicative rates for the
191
+ given reference date.
192
+
193
+ Examples:
194
+ # Fetch ANBIMA rates for all bonds in a specific reference date
195
+ >>> yd.anbima("18-06-2024")
196
+ # Fetch ANBIMA data for NTN-B bonds in a specific reference date
197
+ >>> yd.anbima("NTN-B", "18-06-2024")
198
+ """
199
+ if reference_date is not None:
200
+ reference_date = dc.convert_date(reference_date)
201
+ return RatesData.rates(reference_date, bond_type)
@@ -9,7 +9,7 @@ SUPPORTED_FUTURES = ["DI1", "DDI", "FRC", "DAP", "DOL", "WDO", "IND", "WIN"]
9
9
 
10
10
  def futures(
11
11
  contract_code: str,
12
- reference_date: str | pd.Timestamp | None = None,
12
+ reference_date: str | pd.Timestamp,
13
13
  ) -> pd.DataFrame:
14
14
  """
15
15
  Fetches data for a specified futures contract based on type and reference date.
@@ -26,8 +26,7 @@ def futures(
26
26
  - "IND": Ibovespa Futures from B3.
27
27
  - "WIN": Mini Ibovespa Futures from B3.
28
28
  reference_date (str | None): The reference date for which data is fetched.
29
- Defaults to the last business day avaible if None. If the reference date is
30
- a string, it should be in 'DD-MM-YYYY' format.
29
+ If the reference date is a string, it should be in 'DD-MM-YYYY' format.
31
30
 
32
31
  Returns:
33
32
  pd.DataFrame: A DataFrame containing the fetched data for the specified futures
@@ -8,8 +8,9 @@ from .. import date_converter as dc
8
8
 
9
9
  def indicator(
10
10
  indicator_type: Literal["IPCA_MR", "SELIC_TARGET", "DI", "VNA_LFT"],
11
- reference_date: str | pd.Timestamp | None = None,
11
+ reference_date: str | pd.Timestamp,
12
12
  ) -> float | None:
13
+ reference_date = dc.convert_date(reference_date)
13
14
  ind_type = str(indicator_type).upper()
14
15
  if ind_type == "IPCA_MR":
15
16
  return ipca_monthly_rate(reference_date)
@@ -23,7 +24,7 @@ def indicator(
23
24
  raise ValueError(f"Invalid indicator type: {ind_type}")
24
25
 
25
26
 
26
- def ipca_monthly_rate(reference_date: str | pd.Timestamp | None = None) -> float | None:
27
+ def ipca_monthly_rate(reference_date: pd.Timestamp) -> float | None:
27
28
  """
28
29
  Fetches the IPCA (Índice Nacional de Preços ao Consumidor Amplo) monthly rate
29
30
  from the IBGE (Instituto Brasileiro de Geografia e Estatística) for a given
@@ -31,8 +32,7 @@ def ipca_monthly_rate(reference_date: str | pd.Timestamp | None = None) -> float
31
32
 
32
33
  Args:
33
34
  reference_date (str | pd.Timestamp | None): The reference date for which data
34
- is fetched. Defaults to the last business day if None. If the reference date
35
- is a string, it should be in 'DD-MM-YYYY' format.
35
+ is fetched. If a string is passed, it should be in 'DD-MM-YYYY' format.
36
36
 
37
37
  Returns:
38
38
  float | None: The IPCA monthly rate for the specified date as a float.
@@ -50,9 +50,8 @@ def ipca_monthly_rate(reference_date: str | pd.Timestamp | None = None) -> float
50
50
  0.0038 # Indicates an IPCA monthly rate of 0.38% p.m.
51
51
 
52
52
  """
53
- normalized_date = dc.convert_date(reference_date)
54
53
  # Format the date as 'YYYYMM' for the API endpoint
55
- ipca_date = normalized_date.strftime("%Y%m")
54
+ ipca_date = reference_date.strftime("%Y%m")
56
55
 
57
56
  # Construct the API URL using the formatted date
58
57
  api_url = f"https://servicodados.ibge.gov.br/api/v3/agregados/6691/periodos/{ipca_date}/variaveis/63?localidades=N1[all]"
@@ -74,15 +73,14 @@ def ipca_monthly_rate(reference_date: str | pd.Timestamp | None = None) -> float
74
73
  return None
75
74
 
76
75
 
77
- def selic_target(reference_date: str | pd.Timestamp | None = None) -> float | None:
76
+ def selic_target(reference_date: pd.Timestamp) -> float | None:
78
77
  """
79
78
  Examples:
80
79
  >>> selic_taget("31-05-2024")
81
80
  0.1075 # Indicates a SELIC target rate of 10.75% p.a.
82
81
  """
83
- normalized_date = dc.convert_date(reference_date)
84
82
  # https://api.bcb.gov.br/dados/serie/bcdata.sgs.432/dados?formato=json&dataInicial=12/04/2024&dataFinal=12/04/2024
85
- selic_date = normalized_date.strftime("%d/%m/%Y")
83
+ selic_date = reference_date.strftime("%d/%m/%Y")
86
84
  api_url = f"https://api.bcb.gov.br/dados/serie/bcdata.sgs.432/dados?formato=json&dataInicial={selic_date}&dataFinal={selic_date}"
87
85
  response = requests.get(api_url, timeout=10)
88
86
  response.raise_for_status()
@@ -94,15 +92,14 @@ def selic_target(reference_date: str | pd.Timestamp | None = None) -> float | No
94
92
  return None
95
93
 
96
94
 
97
- def di(reference_date: str | pd.Timestamp | None = None) -> float | None:
95
+ def di(reference_date: pd.Timestamp) -> float | None:
98
96
  """
99
97
  Examples:
100
98
  >>> di("31-05-2024")
101
99
  0.00040168 # Indicates a DI daily rate of 0.02% p.d.
102
100
  """
103
- normalized_date = dc.convert_date(reference_date)
104
101
  # https://api.bcb.gov.br/dados/serie/bcdata.sgs.11/dados?formato=json&dataInicial=12/04/2024&dataFinal=12/04/2024
105
- di_date = normalized_date.strftime("%d/%m/%Y")
102
+ di_date = reference_date.strftime("%d/%m/%Y")
106
103
  api_url = f"https://api.bcb.gov.br/dados/serie/bcdata.sgs.11/dados?formato=json&dataInicial={di_date}&dataFinal={di_date}"
107
104
  response = requests.get(api_url, timeout=10)
108
105
  response.raise_for_status()
@@ -114,11 +111,10 @@ def di(reference_date: str | pd.Timestamp | None = None) -> float | None:
114
111
  return None
115
112
 
116
113
 
117
- def vna_lft(reference_date: str | pd.Timestamp | None = None) -> float | None:
118
- normalized_date = dc.convert_date(reference_date)
114
+ def vna_lft(reference_date: pd.Timestamp) -> float | None:
119
115
  # url example: https://www3.bcb.gov.br/novoselic/rest/arquivosDiarios/pub/download/3/20240418APC238
120
116
  url_base = "https://www3.bcb.gov.br/novoselic/rest/arquivosDiarios/pub/download/3/"
121
- url_file = f"{normalized_date.strftime('%Y%m%d')}APC238"
117
+ url_file = f"{reference_date.strftime('%Y%m%d')}APC238"
122
118
  url_vna = url_base + url_file
123
119
 
124
120
  response = requests.get(url_vna, timeout=10)
@@ -9,8 +9,8 @@ class Interpolator:
9
9
  def __init__(
10
10
  self,
11
11
  method: Literal["flat_forward", "linear"],
12
- known_bdays: pd.Series | pd.Index | list,
13
- known_rates: pd.Series | pd.Index | list,
12
+ known_bdays: pd.Series | list,
13
+ known_rates: pd.Series | list,
14
14
  ):
15
15
  """
16
16
  Initialize the Interpolator with given atributes.
@@ -37,20 +37,19 @@ class Interpolator:
37
37
  self.method = method
38
38
  self.known_bdays = known_bdays
39
39
  self.known_rates = known_rates
40
- self._validate_and_process_inputs()
40
+ self._set_known_bdays_and_rates()
41
41
 
42
- def _validate_and_process_inputs(self) -> None:
42
+ def _set_known_bdays_and_rates(self) -> None:
43
43
  """Validate and process the inputs of the Interpolator."""
44
44
  if self.method not in {"flat_forward", "linear"}:
45
45
  raise ValueError(f"Unknown interpolation method: {self.method}.")
46
46
 
47
47
  known_bdays = self.known_bdays
48
- if not isinstance(known_bdays, list):
49
- known_bdays = known_bdays.to_list()
50
-
51
48
  known_rates = self.known_rates
52
- if not isinstance(known_rates, list):
53
- known_rates = self.known_rates.to_list()
49
+ if isinstance(known_bdays, pd.Series):
50
+ known_bdays = known_bdays.to_list()
51
+ if isinstance(known_rates, pd.Series):
52
+ known_rates = known_rates.to_list()
54
53
 
55
54
  if len(known_bdays) != len(known_rates):
56
55
  raise ValueError("known_bdays and known_rates must have the same length.")
@@ -58,20 +57,20 @@ class Interpolator:
58
57
  df = pd.DataFrame({"bday": known_bdays, "rate": known_rates})
59
58
  df = df.dropna().drop_duplicates(subset="bday").sort_values("bday")
60
59
 
61
- self.known_bdays = df["bday"].to_list()
62
- self.known_rates = df["rate"].to_list()
60
+ self._known_bdays = df["bday"].to_list()
61
+ self._known_rates = df["rate"].to_list()
63
62
 
64
63
  def _flat_forward(self, bday: int) -> float:
65
64
  """Performs the interest rate interpolation using the flat forward method."""
66
65
 
67
66
  # Find i such that known_bdays[i-1] < bday < known_bdays[i]
68
- i = bisect.bisect_left(self.known_bdays, bday)
67
+ i = bisect.bisect_left(self._known_bdays, bday)
69
68
 
70
69
  # Get previous and next known rates and business days
71
- prev_rate = self.known_rates[i - 1]
72
- prev_bday = self.known_bdays[i - 1]
73
- next_rate = self.known_rates[i]
74
- next_bday = self.known_bdays[i]
70
+ prev_rate = self._known_rates[i - 1]
71
+ prev_bday = self._known_bdays[i - 1]
72
+ next_rate = self._known_rates[i]
73
+ next_bday = self._known_bdays[i]
75
74
 
76
75
  # Perform flat forward interpolation
77
76
  a = (1 + prev_rate) ** (prev_bday / 252)
@@ -81,7 +80,7 @@ class Interpolator:
81
80
 
82
81
  def _linear(self, bday: int) -> float:
83
82
  """Performs linear interpolation."""
84
- np_float = np.interp(bday, self.known_bdays, self.known_rates)
83
+ np_float = np.interp(bday, self._known_bdays, self._known_rates)
85
84
  return float(np_float)
86
85
 
87
86
  def interpolate(self, bday: int) -> float:
@@ -108,12 +107,12 @@ class Interpolator:
108
107
  0.04833068080970859
109
108
  """
110
109
  # Check for edge cases
111
- if bday < self.known_bdays[0]:
112
- return self.known_rates[0]
113
- elif bday > self.known_bdays[-1]:
114
- return self.known_rates[-1]
115
- elif bday in self.known_bdays:
116
- return self.known_rates[self.known_bdays.index(bday)]
110
+ if bday < self._known_bdays[0]:
111
+ return self._known_rates[0]
112
+ elif bday > self._known_bdays[-1]:
113
+ return self._known_rates[-1]
114
+ elif bday in self._known_bdays:
115
+ return self._known_rates[self._known_bdays.index(bday)]
117
116
 
118
117
  if self.method == "flat_forward":
119
118
  return self._flat_forward(bday)
@@ -32,7 +32,7 @@ dependencies = [
32
32
  "requests>=2.31.0",
33
33
  ]
34
34
  dynamic = []
35
- version = "0.10.2"
35
+ version = "0.11.0"
36
36
 
37
37
  [project.license]
38
38
  file = "LICENSE"
@@ -1 +0,0 @@
1
- __version__ = "0.10.2"
@@ -1,6 +0,0 @@
1
- from .anbima_data import anbima
2
- from .futures_data import futures
3
- from .indicators import indicator
4
- from .projections import projection
5
-
6
- __all__ = ["futures", "anbima", "indicator", "projection"]
File without changes
File without changes
File without changes
File without changes
File without changes