PYield 0.5.1__tar.gz → 0.6.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: PYield
3
- Version: 0.5.1
3
+ Version: 0.6.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>
@@ -44,7 +44,7 @@ Description-Content-Type: text/markdown
44
44
  [![Made with Python](https://img.shields.io/badge/Python->=3.11-blue?logo=python&logoColor=white)](https://python.org "Go to Python homepage")
45
45
  [![License](https://img.shields.io/badge/License-MIT-blue)](#license)
46
46
 
47
- # PYield: Brazilian Fixed Income Analysis Library
47
+ # PYield: Fixed Income Toolbox for Brazilian Markets
48
48
 
49
49
  ## Introduction
50
50
 
@@ -55,7 +55,7 @@ Welcome to PYield, a Python library designed for the analysis of fixed income in
55
55
  - **Data Collection**: Automated fetching of data from ANBIMA and B3.
56
56
  - **Data Processing**: Efficient processing and normalization of fixed income data.
57
57
  - **Analysis Tools**: Built-in functions for common analysis tasks in fixed income markets.
58
- - **Easy Integration**: Seamless integration with Python data analysis workflows.
58
+ - **Easy Integration**: Seamless integration with pandas data analysis workflows.
59
59
  - **Type Hints**: Full support for static type checking, enhancing development experience and code quality.
60
60
 
61
61
  ## Installation
@@ -67,30 +67,61 @@ pip install pyield
67
67
 
68
68
  ## How to use PYield
69
69
 
70
- ### DI Futures Data
70
+ ### Futures Data
71
71
  ```python
72
72
  import pyield as yd
73
73
 
74
- # Get a pandas dataframe with the DI processed data from B3 (default)
75
- >>> yd.get_di(trade_date='2024-03-08')
76
- TradeDate ExpirationCode ExpirationDate BDToExpiration ... LastRate LastAskRate LastBidRate SettlementRate
77
- 2024-03-08 J24 2024-04-01 15 ... 10.952 10.952 10.956 10.956
78
- 2024-03-08 K24 2024-05-02 37 ... 10.776 10.774 10.780 10.777
79
- 2024-03-08 M24 2024-06-03 58 ... 10.604 10.602 10.604 10.608
80
- ... ... ... ... ... ... ... ... ...
81
- 2024-03-08 F37 2037-01-02 3213 ... <NA> <NA> <NA> 10.859
82
- 2024-03-08 F38 2038-01-04 3462 ... <NA> <NA> <NA> 10.859
83
- 2024-03-08 F39 2039-01-03 3713 ... <NA> <NA> <NA> 10.85
74
+ # Get a DataFrame with the DI Futures data from B3
75
+ >>> yd.get_data(asset_code="DI1", reference_date='2024-03-08')
76
+
77
+ TradeDate ExpirationCode ExpirationDate BDToExpiration ... LastRate LastAskRate LastBidRate SettlementRate
78
+ 2024-03-08 J24 2024-04-01 15 ... 10.952 10.952 10.956 10.956
79
+ 2024-03-08 K24 2024-05-02 37 ... 10.776 10.774 10.780 10.777
80
+ 2024-03-08 M24 2024-06-03 58 ... 10.604 10.602 10.604 10.608
81
+ ... ... ... ... ... ... ... ... ...
82
+ 2024-03-08 F37 2037-01-02 3213 ... <NA> <NA> <NA> 10.859
83
+ 2024-03-08 F38 2038-01-04 3462 ... <NA> <NA> <NA> 10.859
84
+ 2024-03-08 F39 2039-01-03 3713 ... <NA> <NA> <NA> 10.85
85
+ ```
86
+
87
+ ### Treasury Bonds Data
88
+ ```python
89
+ # Get a DataFrame with the NTN-B data from ANBIMA
90
+ # Anbima data is available for the last 5 working days
91
+ # Obs: Anbima members have access to the full history
92
+ >>> yd.get_data(asset_code="NTN-B", reference_date='2024-04-12')
93
+
94
+ BondType ReferenceDate MaturityDate BidRate AskRate IndicativeRate Price
95
+ NTN-B 2024-04-12 2024-08-15 0.07540 0.07504 0.07523 4,271.43565
96
+ NTN-B 2024-04-12 2025-05-15 0.05945 0.05913 0.05930 4,361.34391
97
+ NTN-B 2024-04-12 2026-08-15 0.05927 0.05897 0.05910 4,301.40082
98
+ ... ... ... ... ... ... ...
99
+ NTN-B 2024-04-12 2050-08-15 0.06039 0.06006 0.06023 4,299.28233
100
+ NTN-B 2024-04-12 2055-05-15 0.06035 0.05998 0.06017 4,367.13360
101
+ NTN-B 2024-04-12 2060-08-15 0.06057 0.06016 0.06036 4,292.26323
102
+ ```
103
+
104
+ ### Spreads Calculation
105
+ ```python
106
+ # Calculate the spread between two DI Futures contracts and the pre-fix bonds
107
+ >>> yd.calculate_spreads(spread_type="di_vs_pre", reference_date="2024-4-11")
108
+
109
+ BondType ReferenceDate MaturityDate DISpread
110
+ LTN 2024-04-11 2024-07-01 -20.28000
111
+ LTN 2024-04-11 2024-10-01 -10.19000
112
+ LTN 2024-04-11 2025-01-01 -15.05000
113
+ ... ... ... ...
114
+ NTN-F 2024-04-11 2031-01-01 -0.66000
115
+ NTN-F 2024-04-11 2033-01-01 -5.69000
116
+ NTN-F 2024-04-11 2035-01-01 -1.27000
84
117
  ```
85
118
 
86
119
  ### Business Days Tools (Brazilian holidays are automatically considered)
87
120
  ```python
88
- # Generate a pandas series with the business days between two dates
89
- >>> yd.generate_bdays(start='2023-12-29', end='2024-01-03')
90
- 0 2023-12-29
91
- 1 2024-01-02
92
- 2 2024-01-03
93
- dtype: datetime64[ns]
121
+ # Count the number of business days between two dates
122
+ # Start date is included, end date is excluded
123
+ >>> yd.count_bdays(start='2023-12-29', end='2024-01-02')
124
+ 1
94
125
 
95
126
  # Get the next business day after a given date (offset=1)
96
127
  >>> yd.offset_bdays(dates="2023-12-29", offset=1)
@@ -104,8 +135,10 @@ Timestamp('2024-01-02 00:00:00')
104
135
  >>> yd.offset_bdays(dates="2023-12-29", offset=0)
105
136
  Timestamp('2023-12-29 00:00:00')
106
137
 
107
- # Count the number of business days between two dates
108
- # Start date is included, end date is excluded
109
- >>> yd.count_bdays(start='2023-12-29', end='2024-01-02')
110
- 1
138
+ # Generate a pandas series with the business days between two dates
139
+ >>> yd.generate_bdays(start='2023-12-29', end='2024-01-03')
140
+ 0 2023-12-29
141
+ 1 2024-01-02
142
+ 2 2024-01-03
143
+ dtype: datetime64[ns]
111
144
  ```
pyield-0.6.0/README.md ADDED
@@ -0,0 +1,102 @@
1
+ [![PyPI version](https://img.shields.io/pypi/v/pyield.svg)](https://pypi.python.org/pypi/pyield)
2
+ [![Made with Python](https://img.shields.io/badge/Python->=3.11-blue?logo=python&logoColor=white)](https://python.org "Go to Python homepage")
3
+ [![License](https://img.shields.io/badge/License-MIT-blue)](#license)
4
+
5
+ # PYield: Fixed Income Toolbox for Brazilian Markets
6
+
7
+ ## Introduction
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 and B3.
10
+
11
+ ## Features
12
+
13
+ - **Data Collection**: Automated fetching of data from ANBIMA and B3.
14
+ - **Data Processing**: Efficient processing and normalization of fixed income data.
15
+ - **Analysis Tools**: Built-in functions for common analysis tasks in fixed income markets.
16
+ - **Easy Integration**: Seamless integration with pandas data analysis workflows.
17
+ - **Type Hints**: Full support for static type checking, enhancing development experience and code quality.
18
+
19
+ ## Installation
20
+
21
+ You can install PYield using pip:
22
+ ```sh
23
+ pip install pyield
24
+ ```
25
+
26
+ ## How to use PYield
27
+
28
+ ### Futures Data
29
+ ```python
30
+ import pyield as yd
31
+
32
+ # Get a DataFrame with the DI Futures data from B3
33
+ >>> yd.get_data(asset_code="DI1", reference_date='2024-03-08')
34
+
35
+ TradeDate ExpirationCode ExpirationDate BDToExpiration ... LastRate LastAskRate LastBidRate SettlementRate
36
+ 2024-03-08 J24 2024-04-01 15 ... 10.952 10.952 10.956 10.956
37
+ 2024-03-08 K24 2024-05-02 37 ... 10.776 10.774 10.780 10.777
38
+ 2024-03-08 M24 2024-06-03 58 ... 10.604 10.602 10.604 10.608
39
+ ... ... ... ... ... ... ... ... ...
40
+ 2024-03-08 F37 2037-01-02 3213 ... <NA> <NA> <NA> 10.859
41
+ 2024-03-08 F38 2038-01-04 3462 ... <NA> <NA> <NA> 10.859
42
+ 2024-03-08 F39 2039-01-03 3713 ... <NA> <NA> <NA> 10.85
43
+ ```
44
+
45
+ ### Treasury Bonds Data
46
+ ```python
47
+ # Get a DataFrame with the NTN-B data from ANBIMA
48
+ # Anbima data is available for the last 5 working days
49
+ # Obs: Anbima members have access to the full history
50
+ >>> yd.get_data(asset_code="NTN-B", reference_date='2024-04-12')
51
+
52
+ BondType ReferenceDate MaturityDate BidRate AskRate IndicativeRate Price
53
+ NTN-B 2024-04-12 2024-08-15 0.07540 0.07504 0.07523 4,271.43565
54
+ NTN-B 2024-04-12 2025-05-15 0.05945 0.05913 0.05930 4,361.34391
55
+ NTN-B 2024-04-12 2026-08-15 0.05927 0.05897 0.05910 4,301.40082
56
+ ... ... ... ... ... ... ...
57
+ NTN-B 2024-04-12 2050-08-15 0.06039 0.06006 0.06023 4,299.28233
58
+ NTN-B 2024-04-12 2055-05-15 0.06035 0.05998 0.06017 4,367.13360
59
+ NTN-B 2024-04-12 2060-08-15 0.06057 0.06016 0.06036 4,292.26323
60
+ ```
61
+
62
+ ### Spreads Calculation
63
+ ```python
64
+ # Calculate the spread between two DI Futures contracts and the pre-fix bonds
65
+ >>> yd.calculate_spreads(spread_type="di_vs_pre", reference_date="2024-4-11")
66
+
67
+ BondType ReferenceDate MaturityDate DISpread
68
+ LTN 2024-04-11 2024-07-01 -20.28000
69
+ LTN 2024-04-11 2024-10-01 -10.19000
70
+ LTN 2024-04-11 2025-01-01 -15.05000
71
+ ... ... ... ...
72
+ NTN-F 2024-04-11 2031-01-01 -0.66000
73
+ NTN-F 2024-04-11 2033-01-01 -5.69000
74
+ NTN-F 2024-04-11 2035-01-01 -1.27000
75
+ ```
76
+
77
+ ### Business Days Tools (Brazilian holidays are automatically considered)
78
+ ```python
79
+ # Count the number of business days between two dates
80
+ # Start date is included, end date is excluded
81
+ >>> yd.count_bdays(start='2023-12-29', end='2024-01-02')
82
+ 1
83
+
84
+ # Get the next business day after a given date (offset=1)
85
+ >>> yd.offset_bdays(dates="2023-12-29", offset=1)
86
+ Timestamp('2024-01-02 00:00:00')
87
+
88
+ # Get the next business day if it is not a business day (offset=0)
89
+ >>> yd.offset_bdays(dates="2023-12-30", offset=0)
90
+ Timestamp('2024-01-02 00:00:00')
91
+
92
+ # Since 2023-12-29 is a business day, it returns the same date (offset=0)
93
+ >>> yd.offset_bdays(dates="2023-12-29", offset=0)
94
+ Timestamp('2023-12-29 00:00:00')
95
+
96
+ # Generate a pandas series with the business days between two dates
97
+ >>> yd.generate_bdays(start='2023-12-29', end='2024-01-03')
98
+ 0 2023-12-29
99
+ 1 2024-01-02
100
+ 2 2024-01-03
101
+ dtype: datetime64[ns]
102
+ ```
@@ -0,0 +1 @@
1
+ __version__ = "0.6.0"
@@ -0,0 +1,14 @@
1
+ from .__about__ import __version__
2
+ from .bday import count_bdays, generate_bdays, is_bday, offset_bdays
3
+ from .data_access import get_data
4
+ from .data_analysis import calculate_spreads
5
+
6
+ __all__ = [
7
+ "__version__",
8
+ "is_bday",
9
+ "generate_bdays",
10
+ "offset_bdays",
11
+ "count_bdays",
12
+ "get_data",
13
+ "calculate_spreads",
14
+ ]
@@ -1,16 +1,13 @@
1
- from typing import Literal, overload, Union
2
1
  from datetime import datetime
2
+ from typing import Literal, overload
3
3
 
4
4
  import numpy as np
5
5
  import pandas as pd
6
6
 
7
-
8
7
  from .holidays import BrHolidays
9
8
 
10
-
11
- SingleDateTypes = Union[str, np.datetime64, pd.Timestamp, datetime]
12
-
13
- SeriesDateTypes = Union[list, tuple, np.ndarray, pd.Series, pd.Index, pd.DatetimeIndex]
9
+ SingleDateTypes = str | np.datetime64 | pd.Timestamp | datetime
10
+ SeriesDateTypes = list | tuple | np.ndarray | pd.Series | pd.Index | pd.DatetimeIndex
14
11
 
15
12
  TO_TIMESTAMP_TYPES = (str, np.datetime64, datetime)
16
13
  TO_SERIES_TYPES = (list, tuple, np.ndarray, pd.Series, pd.Index, pd.DatetimeIndex)
@@ -113,25 +110,33 @@ def offset_bdays(
113
110
  holiday_list: Literal["old", "new", "infer"] = "infer",
114
111
  ) -> pd.Timestamp | pd.Series:
115
112
  """
116
- Offsets the dates to the next or previous business day, considering brazilian holidays.
117
- This function supports both single dates and collections of dates, handling them
118
- intelligently to return either a single offset date or a series of offset dates.
119
- It is a wrapper for `numpy.busday_offset` adapted for Pandas data types and holiday adjustments.
113
+ Offsets the dates to the next or previous business day, considering brazilian
114
+ holidays. This function supports both single dates and collections of dates,
115
+ handling them intelligently to return either a single offset date or a series of
116
+ offset dates. It is a wrapper for `numpy.busday_offset` adapted for Pandas data
117
+ types and holiday adjustments.
120
118
 
121
119
  Args:
122
- dates (str | np.datetime64 | pd.Timestamp | datetime | list | tuple | np.ndarray | pd.Series | pd.Index | pd.DatetimeIndex, optional):
123
- The date(s) to offset. Can be a single date in various formats (string, `datetime`, `Timestamp`, etc.)
124
- or a collection of dates (list, tuple, `Series`, etc.). If None, the current date is used.
125
- offset (int): The number of business days to offset the dates. Positive for future dates, negative for past dates.
126
- Zero will return the same date if it's a business day, or the next business day otherwise.
127
- roll (Literal["forward", "backward"], optional): Direction to roll the date if it falls on a holiday or weekend.
128
- 'forward' to the next business day, 'backward' to the previous. Defaults to 'forward'.
129
- holiday_list (Literal["old", "new", "infer"], optional): The list of holidays to consider. 'old' or 'new' use predefined lists,
130
- while 'infer' determines the most appropriate list based on the input dates. Defaults to "infer".
120
+ dates (str | np.datetime64 | pd.Timestamp | datetime | list | tuple | np.ndarray
121
+ | pd.Series | pd.Index | pd.DatetimeIndex, optional):
122
+ The date(s) to offset. Can be a single date in various formats (string,
123
+ `datetime`, `Timestamp`, etc.) or a collection of dates (list, tuple,
124
+ `Series`, etc.). If None, the current date is used.
125
+ offset (int): The number of business days to offset the dates. Positive for
126
+ future dates, negative for past dates. Zero will return the same date if
127
+ it's a business day, or the next business day otherwise.
128
+ roll (Literal["forward", "backward"], optional): Direction to roll the date if
129
+ it falls on a holiday or weekend. 'forward' to the next business day,
130
+ 'backward' to the previous. Defaults to 'forward'.
131
+ holiday_list (Literal["old", "new", "infer"], optional):
132
+ The list of holidays to consider. 'old' or 'new' use predefined lists, while
133
+ 'infer' determines the most appropriate list based on the input dates.
134
+ Defaults to "infer".
131
135
 
132
136
  Returns:
133
- pd.Timestamp | pd.Series: If a single date is provided, returns a single `Timestamp` of the offset date.
134
- If a series of dates is provided, returns a `Series` of offset dates.
137
+ pd.Timestamp | pd.Series: If a single date is provided, returns a single
138
+ `Timestamp` of the offset date. If a series of dates is provided, returns a
139
+ `Series` of offset dates.
135
140
 
136
141
  Examples:
137
142
  >>> date = '2023-12-23' # Saturday before Christmas
@@ -149,8 +154,9 @@ def offset_bdays(
149
154
  Timestamp('2023-12-21') # Offset to the previous business day
150
155
 
151
156
  Note:
152
- This function uses `numpy.busday_offset` under the hood, which means it follows the same conventions and limitations
153
- for business day calculations. For detailed information on error handling and behavior, refer to the `numpy.busday_offset`
157
+ This function uses `numpy.busday_offset` under the hood, which means it follows
158
+ the same conventions and limitations for business day calculations. For detailed
159
+ information on error handling and behavior, refer to the `numpy.busday_offset`
154
160
  documentation: https://numpy.org/doc/stable/reference/generated/numpy.busday_offset.html
155
161
  """
156
162
  normalized_dates = _normalize_input_dates(dates)
@@ -209,30 +215,40 @@ def count_bdays(
209
215
  holiday_list: Literal["old", "new", "infer"] = "infer",
210
216
  ) -> int | pd.Series:
211
217
  """
212
- Counts the number of business days between a `start` and `end` date(s), inclusively for
213
- the start date and exclusively for the end date. The function can handle single dates,
214
- arrays of dates, and mixed inputs, returning either a single integer or a Series
215
- depending on the inputs. It accounts for specified holidays, effectively excluding
216
- them from the business day count.
218
+ Counts the number of business days between a `start` and `end` date(s), inclusively
219
+ for the start date and exclusively for the end date. The function can handle single
220
+ dates, arrays of dates, and mixed inputs, returning either a single integer or a
221
+ Series depending on the inputs. It accounts for specified holidays, effectively
222
+ excluding them from the business day count.
217
223
 
218
224
  Args:
219
- start (str | np.datetime64 | pd.Timestamp | datetime | list | tuple | np.ndarray | pd.Series | pd.Index | pd.DatetimeIndex, optional):
225
+ start (str | np.datetime64 | pd.Timestamp | datetime | list | tuple |
226
+ np.ndarray | pd.Series | pd.Index | pd.DatetimeIndex, optional):
220
227
  The start date(s) for counting. Defaults to the current date if None.
221
- end (str | np.datetime64 | pd.Timestamp | datetime | list | tuple | np.ndarray | pd.Series | pd.Index | pd.DatetimeIndex, optional):
222
- The end date(s) for counting, which are excluded from the count themselves. Defaults to the current date if None.
228
+ end (str | np.datetime64 | pd.Timestamp | datetime | list | tuple |
229
+ np.ndarray | pd.Series | pd.Index | pd.DatetimeIndex, optional):
230
+ The end date(s) for counting, which are excluded from the count themselves.
231
+ Defaults to the current date if None.
223
232
  holiday_list (Literal["old", "new", "infer"], optional):
224
- Specifies which set of holidays to consider in the count. 'old' or 'new' refer to predefined holiday lists,
225
- while 'infer' automatically selects the list based on the most recent date in the input. Defaults to "infer".
233
+ Specifies which set of holidays to consider in the count. 'old' or 'new'
234
+ refer to predefined holiday lists, while 'infer' automatically selects the
235
+ list based on the most recent date in the input. Defaults to "infer".
226
236
 
227
237
  Returns:
228
238
  int | pd.Series: Returns an integer if `start` and `end` are single dates,
229
- or a Series if either or both are arrays of dates. The value(s) represent the count of business days between `start` and `end`.
239
+ or a Series if either or both are arrays of dates. The value(s) represent
240
+ the count of business days between `start` and `end`.
230
241
 
231
242
  Notes:
232
- - This function is a wrapper around `numpy.busday_count`, adapted to work directly with various Pandas and Numpy date formats.
233
- - It supports flexible date inputs, including single dates, lists, Series, and more, for both `start` and `end` parameters.
234
- - The return type depends on the input types: single dates return an int, while arrays of dates return a pd.Series with the count for each date range.
235
- - See `numpy.busday_count` documentation for more details on how holidays are handled and how business day counts are calculated: https://numpy.org/doc/stable/reference/generated/numpy.busday_count.html.
243
+ - This function is a wrapper around `numpy.busday_count`, adapted to work
244
+ directly with various Pandas and Numpy date formats.
245
+ - It supports flexible date inputs, including single dates, lists, Series, and
246
+ more, for both `start` and `end` parameters.
247
+ - The return type depends on the input types: single dates return an int, while
248
+ arrays of dates return a pd.Series with the count for each date range.
249
+ - See `numpy.busday_count` documentation for more details on how holidays are
250
+ handled and how business day counts are calculated:
251
+ https://numpy.org/doc/stable/reference/generated/numpy.busday_count.html.
236
252
 
237
253
  Examples:
238
254
  >>> yd.count_bdays('2023-12-15', '2024-01-01')
@@ -277,28 +293,34 @@ def generate_bdays(
277
293
 
278
294
  Args:
279
295
  start (str | np.datetime64 | pd.Timestamp | datetime, optional):
280
- The start date for generating business days. Defaults to None, using the current date.
296
+ The start date for generating business days. Defaults to None, using the
297
+ current date.
281
298
  end (str | np.datetime64 | pd.Timestamp | datetime, optional):
282
- The end date for generating business days. Defaults to None, using the current date.
299
+ The end date for generating business days. Defaults to None, using the
300
+ current date.
283
301
  inclusive (Literal["both", "neither", "left", "right"], optional):
284
302
  Determines which of the start and end dates are included in the result.
285
303
  Valid options are 'both', 'neither', 'left', 'right'. Defaults to 'both'.
286
304
  holiday_list (Literal["old", "new", "infer"], optional):
287
- Specifies the list of holidays to consider. 'old' or 'new' refer to predefined lists,
288
- 'infer' selects the list based on the most recent date in the range. Defaults to "infer".
305
+ Specifies the list of holidays to consider. 'old' or 'new' refer to
306
+ predefined lists, 'infer' selects the list based on the most recent date in
307
+ the range. Defaults to "infer".
289
308
  **kwargs:
290
- Additional keyword arguments passed to `pandas.bdate_range` for customization.
309
+ Additional keyword arguments passed to `pandas.bdate_range` for
310
+ customization.
291
311
 
292
312
  Returns:
293
- pd.Series: A Series representing a range of business days between the specified start and end dates,
294
- considering the specified holidays.
313
+ pd.Series: A Series representing a range of business days between the specified
314
+ start and end dates, considering the specified holidays.
295
315
 
296
316
  Examples:
297
317
  >>> yd.generate_bdays(start='2023-12-22', end='2024-01-02')
298
- pd.Series(['2023-12-22', '2023-12-26', '2023-12-27', '2023-12-28', '2023-12-29', '2024-01-02'], dtype='datetime64[ns]')
318
+ pd.Series(['2023-12-22', '2023-12-26', '2023-12-27', '2023-12-28', '2023-12-29',
319
+ '2024-01-02'], dtype='datetime64[ns]')
299
320
 
300
321
  Note:
301
- For detailed information on parameters and error handling, refer to `pandas.bdate_range` documentation:
322
+ For detailed information on parameters and error handling, refer to
323
+ `pandas.bdate_range` documentation:
302
324
  https://pandas.pydata.org/docs/reference/api/pandas.bdate_range.html.
303
325
  """
304
326
  normalized_start = _normalize_input_dates(start)
@@ -0,0 +1,51 @@
1
+ import pandas as pd
2
+
3
+ from . import di
4
+ from . import treasuries as tr
5
+ from .utils import _normalize_date
6
+
7
+
8
+ def get_data(
9
+ asset_code: str,
10
+ reference_date: str | pd.Timestamp | None = None,
11
+ **kwargs,
12
+ ) -> pd.DataFrame:
13
+ """
14
+ Fetches data for a specified asset type and reference date.
15
+
16
+ Args:
17
+ asset (str): The asset type. Available options are:
18
+ - "TRB": Fetches indicative rates for Brazilian treasury bonds from ANBIMA.
19
+ - "LTN": Fetches indicative rates for Brazilian LTN bonds from ANBIMA.
20
+ - "LFT": Fetches indicative rates for Brazilian LFT bonds from ANBIMA.
21
+ - "NTN-F": Fetches indicative rates for Brazilian NTN-F bonds from ANBIMA.
22
+ - "NTN-B": Fetches indicative rates for Brazilian NTN-B bonds from ANBIMA.
23
+ - "DI1": Fetches DI Futures rates from B3.
24
+ reference_date (str): Reference date for the data in YYYY-MM-DD format.
25
+
26
+ Returns:
27
+ pd.DataFrame: A DataFrame containing the fetched data.
28
+
29
+ Raises:
30
+ ValueError: If the specified source or asset type is not supported.
31
+ """
32
+ # Extract the internal use parameter with default value
33
+ return_raw = kwargs.get("return_raw", False)
34
+
35
+ # Validate the date, defaulting to the previous business day if not provided
36
+ normalized_date = _normalize_date(reference_date)
37
+
38
+ if asset_code.lower() == "trb":
39
+ # Fetch all indicative treasury rates from ANBIMA
40
+ return tr.fetch_data(reference_date=normalized_date, return_raw=return_raw)
41
+ elif asset_code.lower() in ["ltn", "lft", "ntn-f", "ntn-b"]:
42
+ # Fetch indicative rates for a specific type of Brazilian treasury bond
43
+ df = tr.fetch_data(reference_date=normalized_date)
44
+ return df.query(f"BondType == '{asset_code.upper()}'")
45
+
46
+ elif asset_code.lower() == "di1":
47
+ return di.fetch_data(
48
+ trade_date=normalized_date, source_type="bmf", return_raw=return_raw
49
+ )
50
+ else:
51
+ raise ValueError("Asset type not supported.")
@@ -0,0 +1,31 @@
1
+ import pandas as pd
2
+
3
+ from . import treasuries as tr
4
+ from .utils import _normalize_date
5
+
6
+
7
+ def calculate_spreads(spread_type: str, reference_date: pd.Timestamp) -> pd.DataFrame:
8
+ """
9
+ Calculates spreads between assets based on the specified spread type.
10
+ If no reference date is provided, the function uses the previous business day.
11
+
12
+ Parameters:
13
+ spread_type (str): The type of spread to calculate. Available options are:
14
+ - "DI_vs_PRE": the spread between DI Futures and Treasury Pre-Fixed bonds.
15
+ reference_date (str | pd.Timestamp, optional): The reference date for the
16
+ spread calculation. If None or not provided, defaults to the previous
17
+ business day according to the Brazilian calendar.
18
+
19
+ Returns:
20
+ pd.DataFrame: A DataFrame containing the calculated spread in basis points.
21
+ The data is sorted by asset type and maturity/expiration date.
22
+
23
+ Raises:
24
+ ValueError: If an invalid spread type is provided.
25
+ """
26
+ # Normalize the reference date
27
+ normalized_date = _normalize_date(reference_date)
28
+ if spread_type.lower() == "di_vs_pre":
29
+ return tr.calculate_di_spreads(normalized_date)
30
+ else:
31
+ raise ValueError("Invalid spread type.")
@@ -0,0 +1,6 @@
1
+ from .core import fetch_data, read_data
2
+
3
+ __all__ = [
4
+ "fetch_data",
5
+ "read_data",
6
+ ]
@@ -1,11 +1,10 @@
1
- from typing import Literal
2
1
  from pathlib import Path
2
+ from typing import Literal
3
3
 
4
4
  import pandas as pd
5
5
 
6
- from . import web
7
- from . import xml
8
- from .. import calendar as cl
6
+ from .. import bday
7
+ from . import web, xml
9
8
 
10
9
 
11
10
  def _normalize_date(trade_date: str | pd.Timestamp | None = None) -> pd.Timestamp:
@@ -16,7 +15,7 @@ def _normalize_date(trade_date: str | pd.Timestamp | None = None) -> pd.Timestam
16
15
  elif trade_date is None:
17
16
  today = pd.Timestamp.today().normalize()
18
17
  # Get last business day before today
19
- normalized_date = cl.offset_bdays(today, -1)
18
+ normalized_date = bday.offset_bdays(today, -1)
20
19
  else:
21
20
  raise ValueError("Invalid date format.")
22
21
 
@@ -25,7 +24,7 @@ def _normalize_date(trade_date: str | pd.Timestamp | None = None) -> pd.Timestam
25
24
  raise ValueError("Trade date cannot be in the future.")
26
25
 
27
26
  # Raise error if the reference date is not a business day
28
- if not cl.is_bday(normalized_date):
27
+ if not bday.is_bday(normalized_date):
29
28
  raise ValueError("Trade date must be a business day.")
30
29
 
31
30
  return normalized_date
@@ -87,15 +86,15 @@ def get_expiration_date(expiration_code: str) -> pd.Timestamp:
87
86
  expiration = pd.Timestamp(year, month, 1)
88
87
 
89
88
  # Adjust to the next business day when expiration date is a weekend or a holiday
90
- adj_expiration = cl.offset_bdays(expiration, offset=0)
89
+ adj_expiration = bday.offset_bdays(expiration, offset=0)
91
90
 
92
91
  return adj_expiration
93
92
 
94
93
  except (KeyError, ValueError):
95
- raise ValueError("Invalid expiration code.")
94
+ return pd.NaT # type: ignore
96
95
 
97
96
 
98
- def get_di(
97
+ def fetch_data(
99
98
  trade_date: str | pd.Timestamp | None = None,
100
99
  source_type: Literal["bmf", "b3", "b3s"] = "bmf",
101
100
  return_raw: bool = False,
@@ -103,24 +102,26 @@ def get_di(
103
102
  """
104
103
  Fetches DI futures data for a specified trade date from B3.
105
104
 
106
- Retrieves and processes DI futures data from B3 for a given trade date. This function
107
- serves as the primary method for accessing DI data, with options to specify the source
108
- of the data and whether to return raw data.
105
+ Retrieves and processes DI futures data from B3 for a given trade date. This
106
+ function serves as the primary method for accessing DI data, with options to
107
+ specify the source of the data and whether to return raw data.
109
108
 
110
109
  Args:
111
- trade_date (str | pd.Timestamp | None, optional): The trade date for which to
112
- fetch DI data. If None or not provided, uses the previous business day.
113
- source_type (Literal["bmf", "b3", "b3s"], optional): Indicates the source of the
114
- data. Options include:
115
- - "bmf": Fetches data from the old BM&FBOVESPA website. Fastest option.
116
- - "b3": Fetches data from the complete Price Report (XML file) provided by B3.
117
- - "b3s": Fetches data from the simplified Price Report (XML file) provided by B3.
118
- Faster than "b3" but less detailed.
119
- Defaults to "bmf".
120
- return_raw (bool, optional): If True, returns the raw DI data without processing.
110
+ trade_date (str | pd.Timestamp | None, optional): The trade date for which to
111
+ fetch DI data. If None or not provided, uses the previous business day.
112
+ source_type (Literal["bmf", "b3", "b3s"], optional): Indicates the source of
113
+ the data. Defaults to "bmf". Options include:
114
+ - "bmf": Fetches data from the old BM&FBOVESPA website. Fastest option.
115
+ - "b3": Fetches data from the complete Price Report (XML file) provided
116
+ by B3.
117
+ - "b3s": Fetches data from the simplified Price Report (XML file)
118
+ provided by B3. Faster than "b3" but less detailed.
119
+ return_raw (bool, optional): If True, returns the raw DI data without
120
+ processing.
121
121
 
122
122
  Returns:
123
- pd.DataFrame: A DataFrame containing the DI futures data for the specified trade
123
+ pd.DataFrame: A DataFrame containing the DI futures data for the specified
124
+ trade
124
125
  date. Format and content depend on the source_type and return_raw flag.
125
126
 
126
127
  Examples:
@@ -141,12 +142,12 @@ def get_di(
141
142
  if source_type == "bmf":
142
143
  return web.get_di(normalized_trade_date, return_raw)
143
144
  elif source_type in ["b3", "b3s"]:
144
- return xml.get_di(normalized_trade_date, source_type, return_raw)
145
+ return xml.read_xml(normalized_trade_date, source_type, return_raw)
145
146
  else:
146
147
  raise ValueError("source_type must be either 'bmf', 'b3' or 'b3s'.")
147
148
 
148
149
 
149
- def read_di(file_path: Path, return_raw: bool = False) -> pd.DataFrame:
150
+ def read_data(file_path: Path, return_raw: bool = False) -> pd.DataFrame:
150
151
  """
151
152
  Reads DI futures data from a file and returns it as a pandas DataFrame.
152
153
 
@@ -1,40 +1,38 @@
1
1
  import io
2
2
  import warnings
3
- from typing import Optional
4
3
 
5
4
  import pandas as pd
6
5
  import requests
7
6
 
8
- from .. import calendar as cl
7
+ from .. import bday
9
8
  from . import core as cr
10
9
 
11
10
 
12
11
  def get_old_expiration_date(
13
- ExpirationCode: str, trade_date: pd.Timestamp
14
- ) -> Optional[pd.Timestamp]:
12
+ expiration_code: str, trade_date: pd.Timestamp
13
+ ) -> pd.Timestamp:
15
14
  """
16
- Internal function to convert an old DI contract code into its ExpirationDate date. Valid for
17
- contract codes up to 21-05-2006.
15
+ Internal function to convert an old DI contract code into its ExpirationDate date.
16
+ Valid for contract codes up to 21-05-2006.
18
17
 
19
18
  Args:
20
- ExpirationCode (str):
21
- An old DI ExpirationCode from B3, where the first three letters represent
22
- the month and the last digit represents the year. Example: "JAN3".
23
- trade_date (pd.Timestamp):
24
- The trade date for which the contract code is valid.
19
+ expiration_code (str): An old DI Expiration Code from B3, where the first three
20
+ letters represent the month and the last digit represents the year.
21
+ Example: "JAN3".
22
+ trade_date (pd.Timestamp): The trade date for which the contract code is valid.
25
23
 
26
24
  Returns:
27
25
  pd.Timestamp
28
- The contract's ExpirationDate date.
29
- Returns pd.NaT if the input is invalid.
26
+ The contract's ExpirationDate date. Returns pd.NaT if the input is invalid.
30
27
 
31
28
  Examples:
32
29
  >>> get_old_expiration_date("JAN3", pd.Timestamp("2001-05-21"))
33
30
  pd.Timestamp('2003-01-01')
31
+
34
32
  Notes:
35
- - In 22-05-2006, B3 changed the format of the DI contract codes. Before that date,
36
- the first three letters represented the month and the last digit represented the
37
- year.
33
+ - In 22-05-2006, B3 changed the format of the DI contract codes. Before that
34
+ date, the first three letters represented the month and the last digit
35
+ represented the year.
38
36
  """
39
37
 
40
38
  month_codes = {
@@ -52,26 +50,26 @@ def get_old_expiration_date(
52
50
  "DEZ": 12,
53
51
  }
54
52
  try:
55
- month_code = ExpirationCode[:3]
53
+ month_code = expiration_code[:3]
56
54
  month = month_codes[month_code]
57
55
 
58
- # Year codes must generated dynamically, since it depends on the trade date
56
+ # Year codes must generated dynamically, since it depends on the trade date.
59
57
  reference_year = trade_date.year
60
58
  year_codes = {}
61
59
  for year in range(reference_year, reference_year + 10):
62
60
  year_codes[str(year)[-1:]] = year
63
- year = year_codes[ExpirationCode[-1:]]
61
+ year = year_codes[expiration_code[-1:]]
64
62
 
65
- ExpirationDate = pd.Timestamp(year, month, 1)
66
- # Adjust to the next business day when ExpirationDate date is a weekend or a holiday
67
- # Must use the old holiday calendar, since this type of contract code was used until 2006
68
- return cl.offset_bdays(ExpirationDate, offset=0, holiday_list="old")
63
+ expiration_date = pd.Timestamp(year, month, 1)
64
+ # Adjust to the next business day when the date is a weekend or a holiday.
65
+ # Must use old holiday list, since this contract code was used until 2006.
66
+ return bday.offset_bdays(expiration_date, offset=0, holiday_list="old")
69
67
 
70
68
  except (KeyError, ValueError):
71
69
  return pd.NaT # type: ignore
72
70
 
73
71
 
74
- def _get_raw_di(trade_date: pd.Timestamp) -> pd.DataFrame:
72
+ def _get_raw_df(trade_date: pd.Timestamp) -> pd.DataFrame:
75
73
  """
76
74
  Internal function to fetch raw DI futures data from B3 for a specific trade date.
77
75
 
@@ -104,18 +102,19 @@ def _get_raw_di(trade_date: pd.Timestamp) -> pd.DataFrame:
104
102
  # Remove columns with all NaN values
105
103
  df = df.dropna(axis=1, how="all")
106
104
 
107
- # Force "VAR. PTOS." column to be string, since it can vary between str and float
105
+ # Force "VAR. PTOS." to be string, since it can also be read as float
108
106
  df["VAR. PTOS."] = df["VAR. PTOS."].astype(pd.StringDtype())
109
107
 
110
- # Force "AJUSTE CORRIG. (4)" column to be float, since it can vary between int and float
108
+ # Force "AJUSTE CORRIG. (4)" to be float, since it can be also read as int
111
109
  df["AJUSTE CORRIG. (4)"] = df["AJUSTE CORRIG. (4)"].astype(pd.Float64Dtype())
112
110
 
113
111
  return df
114
112
 
115
113
  except Exception as e:
116
- warnings.warn(
117
- f"A {type(e).__name__} occurred while reading the DI futures data for {trade_date.strftime('%d/%m/%Y')}. Returning an empty pd.DataFrame."
118
- )
114
+ trade_date_str = trade_date.strftime("%d/%m/%Y")
115
+ message = f"""A {type(e).__name__} occurred while reading the DI futures data
116
+ for {trade_date_str}. Returning an empty pd.DataFrame."""
117
+ warnings.warn(message, stacklevel=2)
119
118
  return pd.DataFrame()
120
119
 
121
120
 
@@ -125,7 +124,7 @@ def _convert_prices_to_rates(prices: pd.Series, bd: pd.Series) -> pd.Series:
125
124
 
126
125
  Args:
127
126
  prices (pd.Series): A pd.Series containing DI futures prices.
128
- bd (pd.Series): A pd.Series containing the number of business days to ExpirationDate.
127
+ bd (pd.Series): A serie containing the number of business days to expiration.
129
128
 
130
129
  Returns:
131
130
  pd.Series: A pd.Series containing DI futures rates.
@@ -156,7 +155,7 @@ def _convert_prices_in_older_contracts(df: pd.DataFrame) -> pd.DataFrame:
156
155
  return df
157
156
 
158
157
 
159
- def _process_di(df: pd.DataFrame, trade_date: pd.Timestamp) -> pd.DataFrame:
158
+ def _process_raw_df(df: pd.DataFrame, trade_date: pd.Timestamp) -> pd.DataFrame:
160
159
  """
161
160
  Internal function to process and transform raw DI futures data.
162
161
 
@@ -206,7 +205,7 @@ def _process_di(df: pd.DataFrame, trade_date: pd.Timestamp) -> pd.DataFrame:
206
205
  else:
207
206
  df["ExpirationDate"] = df["ExpirationCode"].apply(cr.get_expiration_date)
208
207
 
209
- df["BDToExpiration"] = cl.count_bdays(trade_date, df["ExpirationDate"])
208
+ df["BDToExpiration"] = bday.count_bdays(trade_date, df["ExpirationDate"])
210
209
  # Convert to nullable integer, since other columns use this data type
211
210
  df["BDToExpiration"] = df["BDToExpiration"].astype(pd.Int64Dtype())
212
211
  # Remove expired contracts
@@ -224,7 +223,7 @@ def _process_di(df: pd.DataFrame, trade_date: pd.Timestamp) -> pd.DataFrame:
224
223
  "LastAskRate",
225
224
  ]
226
225
  for col in cols_with_nan:
227
- df[cols_with_nan] = df[cols_with_nan].replace(0, pd.NA)
226
+ df[col] = df[col].replace(0, pd.NA)
228
227
 
229
228
  # Prior to 17/01/2002 (incluive), prices were not converted to rates
230
229
  if trade_date <= pd.Timestamp("2002-01-17"):
@@ -234,8 +233,8 @@ def _process_di(df: pd.DataFrame, trade_date: pd.Timestamp) -> pd.DataFrame:
234
233
  df["SettlementPrice"], df["BDToExpiration"]
235
234
  )
236
235
 
237
- # Remove percentage in all rate columns and round to 5 decimal places since it's the precision used by B3
238
- # Obs: 5 decimal places = 3 decimal places in percentage
236
+ # Remove percentage in all rate columns and round to 5 decimal places since it's the
237
+ # precision used by B3. Obs: 5 decimal places = 3 decimal places in percentage
239
238
  rate_cols = [col for col in df.columns if "Rate" in col]
240
239
  for col in rate_cols:
241
240
  df[col] = (df[col] / 100).round(5)
@@ -288,7 +287,7 @@ def get_di(trade_date: pd.Timestamp, return_raw: bool = False) -> pd.DataFrame:
288
287
  - OpenContracts: number of open contracts at the start of the trading day.
289
288
  - closed_contracts: number of closed contracts at the end of the trading day.
290
289
  """
291
- df_raw = _get_raw_di(trade_date)
290
+ df_raw = _get_raw_df(trade_date)
292
291
  if return_raw:
293
292
  return df_raw
294
- return _process_di(df_raw, trade_date)
293
+ return _process_raw_df(df_raw, trade_date)
@@ -2,13 +2,13 @@ import io
2
2
  import zipfile
3
3
  from pathlib import Path
4
4
 
5
- import requests
6
5
  import pandas as pd
7
- from pandas import Timestamp, DataFrame
6
+ import requests
8
7
  from lxml import etree
8
+ from pandas import DataFrame, Timestamp
9
9
 
10
+ from .. import bday
10
11
  from . import core as cr
11
- from .. import calendar as cd
12
12
 
13
13
 
14
14
  def _get_file_from_url(trade_date: Timestamp, source_type: str) -> io.BytesIO:
@@ -232,7 +232,7 @@ def _process_di_df(df_raw: DataFrame) -> DataFrame:
232
232
  expiration = df["TckrSymb"].str[3:].apply(cr.get_expiration_date)
233
233
  df.insert(2, "ExpirationDate", expiration)
234
234
 
235
- business_days = cd.count_bdays(df["TradDt"], df["ExpirationDate"])
235
+ business_days = bday.count_bdays(df["TradDt"], df["ExpirationDate"])
236
236
  df.insert(3, "BDToExpiration", business_days)
237
237
 
238
238
  # Convert to nullable integer, since other columns use this data type
@@ -244,7 +244,7 @@ def _process_di_df(df_raw: DataFrame) -> DataFrame:
244
244
  return df.sort_values(by=["ExpirationDate"], ignore_index=True)
245
245
 
246
246
 
247
- def get_di(trade_date: Timestamp, source_type: str, return_raw: bool) -> DataFrame:
247
+ def read_xml(trade_date: Timestamp, source_type: str, return_raw: bool) -> DataFrame:
248
248
  zip_file = _get_file_from_url(trade_date, source_type)
249
249
 
250
250
  xml_file = _extract_xml_from_zip(zip_file)
@@ -4,7 +4,6 @@ import pandas as pd
4
4
  import requests
5
5
 
6
6
  from . import di
7
- from . import calendar as cl
8
7
 
9
8
  # URL Constants
10
9
  ANBIMA_NON_MEMBER_URL = "https://www.anbima.com.br/informacoes/merc-sec/arqs/"
@@ -14,29 +13,6 @@ ANBIMA_MEMBER_URL = "http://www.anbima.associados.rtm/merc_sec/arqs/"
14
13
  BPS_CONVERSION_FACTOR = 10_000
15
14
 
16
15
 
17
- def _normalize_date(reference_date: str | pd.Timestamp | None = None) -> pd.Timestamp:
18
- if isinstance(reference_date, str):
19
- normalized_date = pd.Timestamp(reference_date).normalize()
20
- elif isinstance(reference_date, pd.Timestamp):
21
- normalized_date = reference_date.normalize()
22
- elif reference_date is None:
23
- today = pd.Timestamp.today().normalize()
24
- # Get last business day before today
25
- normalized_date = cl.offset_bdays(today, -1)
26
- else:
27
- raise ValueError("Invalid date format.")
28
-
29
- # Raise an error if the reference date is in the future
30
- if normalized_date > pd.Timestamp.today().normalize():
31
- raise ValueError("Reference date cannot be in the future.")
32
-
33
- # Raise error if the reference date is not a business day
34
- if not cl.is_bday(normalized_date):
35
- raise ValueError("Reference date must be a business day.")
36
-
37
- return normalized_date
38
-
39
-
40
16
  def _get_anbima_content(reference_date: pd.Timestamp) -> str:
41
17
  url_date = reference_date.strftime("%y%m%d")
42
18
  member_url = f"{ANBIMA_MEMBER_URL}ms{url_date}.txt"
@@ -62,7 +38,7 @@ def _get_anbima_content(reference_date: pd.Timestamp) -> str:
62
38
  return ""
63
39
 
64
40
 
65
- def _get_raw_data(reference_date: pd.Timestamp) -> pd.DataFrame:
41
+ def _get_raw_df(reference_date: pd.Timestamp) -> pd.DataFrame:
66
42
  url_content = _get_anbima_content(reference_date)
67
43
  if url_content == "":
68
44
  date_str = reference_date.strftime("%d-%m-%Y")
@@ -81,9 +57,10 @@ def _get_raw_data(reference_date: pd.Timestamp) -> pd.DataFrame:
81
57
  return df
82
58
 
83
59
 
84
- def _process_raw_data(df_raw: pd.DataFrame) -> pd.DataFrame:
60
+ def _process_raw_df(df_raw: pd.DataFrame) -> pd.DataFrame:
85
61
  """
86
- Process raw data from ANBIMA by filtering selected columns, renaming them, and adjusting data formats.
62
+ Process raw data from ANBIMA by filtering selected columns, renaming them and
63
+ adjusting data formats.
87
64
 
88
65
  Parameters:
89
66
  - df (pd.DataFrame): Raw data DataFrame to process.
@@ -123,27 +100,28 @@ def _process_raw_data(df_raw: pd.DataFrame) -> pd.DataFrame:
123
100
  return df.sort_values(["BondType", "MaturityDate"], ignore_index=True)
124
101
 
125
102
 
126
- def get_treasury_rates(
127
- reference_date: str | pd.Timestamp | None = None,
128
- return_raw=False,
129
- ) -> pd.DataFrame:
103
+ def fetch_data(reference_date: pd.Timestamp, return_raw=False) -> pd.DataFrame:
130
104
  """
131
- Fetches and processes indicative treasury rates from ANBIMA for a specified reference date.
105
+ Fetches indicative treasury rates from ANBIMA for a specified reference date.
132
106
 
133
- This function retrieves the indicative rates for Brazilian treasury securities from ANBIMA,
134
- processing them into a structured pandas DataFrame. If no reference date is provided, it defaults
135
- to the previous business day according to the Brazilian calendar. There is an option to return
136
- raw data directly from the source without processing.
107
+ This function retrieves the indicative rates for Brazilian treasury securities
108
+ from ANBIMA, processing them into a structured pandas DataFrame. If no reference
109
+ date is provided, it defaults to the previous business day according to the
110
+ Brazilian calendar. There is an option to return raw data directly from the source
111
+ without processing.
137
112
 
138
113
  Parameters:
139
- reference_date (str | pd.Timestamp, optional): The date for which to fetch the indicative rates.
140
- If None or not provided, the function defaults to the previous business day.
141
- return_raw (bool, optional): Flag to return raw data without processing. Defaults to False.
114
+ reference_date (str | pd.Timestamp, optional): The date for which to fetch the
115
+ indicative rates. If None or not provided, the function defaults to the
116
+ previous business day.
117
+ return_raw (bool, optional): Flag to return raw data without processing.
118
+ Defaults to False.
142
119
 
143
120
  Returns:
144
- pd.DataFrame: A DataFrame containing the processed indicative rates for the given reference date,
145
- or raw data if `return_raw` is True. The processed data includes bond type, reference date, maturity date,
146
- and various rates (bid, ask, indicative) among others, depending on the `return_raw` flag.
121
+ pd.DataFrame: A DataFrame containing the processed indicative rates for the
122
+ given reference date, or raw data if `return_raw` is True. The processed
123
+ data includes bond type, reference date, maturity date and various rates
124
+ (bid, ask, indicative) among others, depending on the `return_raw` flag.
147
125
 
148
126
  Examples:
149
127
  # Fetch processed indicative rates for the previous business day
@@ -152,33 +130,33 @@ def get_treasury_rates(
152
130
  # Fetch raw indicative rates for a specific date
153
131
  >>> get_treasury_rates("2023-12-28")
154
132
  """
155
-
156
- normalized_date = _normalize_date(reference_date)
157
- df = _get_raw_data(normalized_date)
133
+ df = _get_raw_df(reference_date)
158
134
 
159
135
  if not return_raw:
160
- df = _process_raw_data(df)
136
+ df = _process_raw_df(df)
161
137
 
162
138
  return df
163
139
 
164
140
 
165
- def calculate_treasury_di_spreads(
166
- reference_date: str | pd.Timestamp | None = None,
167
- ) -> pd.DataFrame:
141
+ def calculate_di_spreads(reference_date: pd.Timestamp) -> pd.DataFrame:
168
142
  """
169
- Calculates the DI spread for Brazilian treasury bonds (LTN and NTN-F) based on ANBIMA's indicative rates.
143
+ Calculates the DI spread for Brazilian treasury bonds (LTN and NTN-F) based on
144
+ ANBIMA's indicative rates.
170
145
 
171
- This function fetches the indicative rates for Brazilian treasury securities (LTN and NTN-F bonds)
172
- and the DI futures rates for a specified reference date, calculating the spread between these rates
173
- in basis points. If no reference date is provided, the function uses the previous business day.
146
+ This function fetches the indicative rates for Brazilian treasury securities (LTN
147
+ and NTN-F bonds) and the DI futures rates for a specified reference date,
148
+ calculating the spread between these rates in basis points. If no reference date is
149
+ provided, the function uses the previous business day.
174
150
 
175
151
  Parameters:
176
- reference_date (str | pd.Timestamp, optional): The reference date for the DI spread calculation.
177
- If None or not provided, defaults to the previous business day according to the Brazilian calendar.
152
+ reference_date (str | pd.Timestamp, optional): The reference date for the DI
153
+ spread calculation. If None or not provided, defaults to the previous
154
+ business day according to the Brazilian calendar.
178
155
 
179
156
  Returns:
180
- pd.DataFrame: A DataFrame containing the bond type, reference date, maturity date, and the calculated
181
- DI spread in basis points. The data is sorted by bond type and maturity date.
157
+ pd.DataFrame: A DataFrame containing the bond type, reference date, maturity
158
+ date, and the calculated DI spread in basis points. The data is sorted by
159
+ bond type and maturity date.
182
160
 
183
161
  Examples:
184
162
  # Calculate DI spreads for the previous business day
@@ -187,11 +165,8 @@ def calculate_treasury_di_spreads(
187
165
  # Calculate DI spreads for a specific reference date
188
166
  >>> calculate_treasury_di_spreads("2023-12-15")
189
167
  """
190
- # Validate the reference date, defaulting to the previous business day if not provided
191
- normalized_date = _normalize_date(reference_date)
192
-
193
168
  # Fetch DI rates and adjust the maturity date format for compatibility
194
- df_di = di.get_di(normalized_date)[["ExpirationDate", "SettlementRate"]]
169
+ df_di = di.fetch_data(reference_date)[["ExpirationDate", "SettlementRate"]]
195
170
 
196
171
  # Renaming the columns to match the ANBIMA structure
197
172
  df_di.rename(columns={"ExpirationDate": "MaturityDate"}, inplace=True)
@@ -200,13 +175,13 @@ def calculate_treasury_di_spreads(
200
175
  df_di["MaturityDate"] = df_di["MaturityDate"].dt.to_period("M").dt.to_timestamp()
201
176
 
202
177
  # Fetch bond rates, filtering for LTN and NTN-F types
203
- df_anbima = get_treasury_rates(normalized_date, False)
178
+ df_anbima = fetch_data(reference_date, False)
204
179
  df_anbima.query("BondType in ['LTN', 'NTN-F']", inplace=True)
205
180
 
206
181
  # Merge bond and DI rates by maturity date to calculate spreads
207
182
  df_final = pd.merge(df_anbima, df_di, how="left", on="MaturityDate")
208
183
 
209
- # Calculating the DI spread as the difference between indicative and settlement rates
184
+ # Calculate the DI spread as the difference between indicative and settlement rates
210
185
  df_final["DISpread"] = df_final["IndicativeRate"] - df_final["SettlementRate"]
211
186
 
212
187
  # Convert spread to basis points for clarity
@@ -0,0 +1,26 @@
1
+ import pandas as pd
2
+
3
+ from . import bday
4
+
5
+
6
+ def _normalize_date(reference_date: str | pd.Timestamp | None = None) -> pd.Timestamp:
7
+ if isinstance(reference_date, str):
8
+ normalized_date = pd.Timestamp(reference_date).normalize()
9
+ elif isinstance(reference_date, pd.Timestamp):
10
+ normalized_date = reference_date.normalize()
11
+ elif reference_date is None:
12
+ today = pd.Timestamp.today().normalize()
13
+ # Get last business day before today
14
+ normalized_date = bday.offset_bdays(today, -1)
15
+ else:
16
+ raise ValueError("Invalid date format.")
17
+
18
+ # Raise an error if the reference date is in the future
19
+ if normalized_date > pd.Timestamp.today().normalize():
20
+ raise ValueError("Reference date cannot be in the future.")
21
+
22
+ # Raise error if the reference date is not a business day
23
+ if not bday.is_bday(normalized_date):
24
+ raise ValueError("Reference date must be a business day.")
25
+
26
+ return normalized_date
@@ -31,7 +31,7 @@ dependencies = [
31
31
  "lxml",
32
32
  ]
33
33
  dynamic = []
34
- version = "0.5.1"
34
+ version = "0.6.0"
35
35
 
36
36
  [project.license]
37
37
  file = "LICENSE"
@@ -52,3 +52,13 @@ dev = [
52
52
  "pytest",
53
53
  "mypy",
54
54
  ]
55
+
56
+ [tool.ruff.lint]
57
+ select = [
58
+ "E",
59
+ "F",
60
+ "UP",
61
+ "B",
62
+ "SIM",
63
+ "I",
64
+ ]
@@ -1,14 +1,14 @@
1
1
  import pandas as pd
2
2
  import numpy as np
3
3
 
4
- from pyield import calendar as cl
4
+ import pyield as yd
5
5
 
6
6
 
7
7
  def test_count_bdays_1():
8
8
  start = "2023-01-01"
9
9
  end = "2023-01-08"
10
10
  # 01/01/2023 is a Sunday and a holiday
11
- assert cl.count_bdays(start, end) == 5
11
+ assert yd.count_bdays(start, end) == 5
12
12
 
13
13
 
14
14
  def test_count_bdays_2():
@@ -16,30 +16,30 @@ def test_count_bdays_2():
16
16
  end = "2024-01-02"
17
17
  # 25/12/2023 is a holiday
18
18
  # 01/01/2024 is a holiday
19
- assert cl.count_bdays(start, end) == 10
19
+ assert yd.count_bdays(start, end) == 10
20
20
 
21
21
 
22
22
  def test_count_bdays_with_series():
23
23
  start = "2023-01-01"
24
24
  end = pd.Series(["2023-01-08", "2023-01-22"])
25
25
  # Assuming no holidays in these periods
26
- assert np.array_equal(cl.count_bdays(start, end), np.array([5, 15]))
26
+ assert np.array_equal(yd.count_bdays(start, end), np.array([5, 15]))
27
27
 
28
28
 
29
29
  def test_count_bdays_negative_count():
30
30
  start = "2023-01-08"
31
31
  end = "2023-01-01"
32
32
  # Negative count expected
33
- assert cl.count_bdays(start, end) == -5
33
+ assert yd.count_bdays(start, end) == -5
34
34
 
35
35
 
36
36
  def test_count_bdays_new_holiday_list():
37
37
  start = "2024-11-20" # Zumbi Nacional Day
38
38
  end = "2024-11-21"
39
- assert cl.count_bdays(start, end) == 0
39
+ assert yd.count_bdays(start, end) == 0
40
40
 
41
41
 
42
42
  def test_count_bdays_old_holiday_list():
43
43
  start = "2020-11-20" # Was not a holiday in 2020
44
44
  end = "2020-11-21"
45
- assert cl.count_bdays(start, end) == 1
45
+ assert yd.count_bdays(start, end) == 1
@@ -43,7 +43,7 @@ def test_settlement_rate_with_old_holiday_list():
43
43
  }
44
44
 
45
45
  # 22-12-2023 is before the new holiday calendar
46
- df = cr.get_di(trade_date="2023-12-22")
46
+ df = cr.fetch_data(trade_date="2023-12-22")
47
47
  expiration_codes = list(settlement_rates.keys()) # noqa: F841
48
48
  result = df.query("ExpirationCode in @expiration_codes")["SettlementRate"].to_list()
49
49
  assert result == list(settlement_rates.values())
@@ -68,7 +68,7 @@ def test_settlement_rates_with_current_holiday_list():
68
68
  "F33": 0.10331,
69
69
  }
70
70
 
71
- df = cr.get_di(trade_date="2023-12-26")
71
+ df = cr.fetch_data(trade_date="2023-12-26")
72
72
  expiration_codes = list(settlement_rates.keys()) # noqa: F841
73
73
  results = df.query("ExpirationCode in @expiration_codes")[
74
74
  "SettlementRate"
@@ -79,4 +79,4 @@ def test_settlement_rates_with_current_holiday_list():
79
79
  def test_non_business_day():
80
80
  non_business_day = "2023-12-24"
81
81
  with pytest.raises(ValueError):
82
- cr.get_di(trade_date=non_business_day)
82
+ cr.fetch_data(trade_date=non_business_day)
pyield-0.5.1/README.md DELETED
@@ -1,69 +0,0 @@
1
- [![PyPI version](https://img.shields.io/pypi/v/pyield.svg)](https://pypi.python.org/pypi/pyield)
2
- [![Made with Python](https://img.shields.io/badge/Python->=3.11-blue?logo=python&logoColor=white)](https://python.org "Go to Python homepage")
3
- [![License](https://img.shields.io/badge/License-MIT-blue)](#license)
4
-
5
- # PYield: Brazilian Fixed Income Analysis Library
6
-
7
- ## Introduction
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 and B3.
10
-
11
- ## Features
12
-
13
- - **Data Collection**: Automated fetching of data from ANBIMA and B3.
14
- - **Data Processing**: Efficient processing and normalization of fixed income data.
15
- - **Analysis Tools**: Built-in functions for common analysis tasks in fixed income markets.
16
- - **Easy Integration**: Seamless integration with Python data analysis workflows.
17
- - **Type Hints**: Full support for static type checking, enhancing development experience and code quality.
18
-
19
- ## Installation
20
-
21
- You can install PYield using pip:
22
- ```sh
23
- pip install pyield
24
- ```
25
-
26
- ## How to use PYield
27
-
28
- ### DI Futures Data
29
- ```python
30
- import pyield as yd
31
-
32
- # Get a pandas dataframe with the DI processed data from B3 (default)
33
- >>> yd.get_di(trade_date='2024-03-08')
34
- TradeDate ExpirationCode ExpirationDate BDToExpiration ... LastRate LastAskRate LastBidRate SettlementRate
35
- 2024-03-08 J24 2024-04-01 15 ... 10.952 10.952 10.956 10.956
36
- 2024-03-08 K24 2024-05-02 37 ... 10.776 10.774 10.780 10.777
37
- 2024-03-08 M24 2024-06-03 58 ... 10.604 10.602 10.604 10.608
38
- ... ... ... ... ... ... ... ... ...
39
- 2024-03-08 F37 2037-01-02 3213 ... <NA> <NA> <NA> 10.859
40
- 2024-03-08 F38 2038-01-04 3462 ... <NA> <NA> <NA> 10.859
41
- 2024-03-08 F39 2039-01-03 3713 ... <NA> <NA> <NA> 10.85
42
- ```
43
-
44
- ### Business Days Tools (Brazilian holidays are automatically considered)
45
- ```python
46
- # Generate a pandas series with the business days between two dates
47
- >>> yd.generate_bdays(start='2023-12-29', end='2024-01-03')
48
- 0 2023-12-29
49
- 1 2024-01-02
50
- 2 2024-01-03
51
- dtype: datetime64[ns]
52
-
53
- # Get the next business day after a given date (offset=1)
54
- >>> yd.offset_bdays(dates="2023-12-29", offset=1)
55
- Timestamp('2024-01-02 00:00:00')
56
-
57
- # Get the next business day if it is not a business day (offset=0)
58
- >>> yd.offset_bdays(dates="2023-12-30", offset=0)
59
- Timestamp('2024-01-02 00:00:00')
60
-
61
- # Since 2023-12-29 is a business day, it returns the same date (offset=0)
62
- >>> yd.offset_bdays(dates="2023-12-29", offset=0)
63
- Timestamp('2023-12-29 00:00:00')
64
-
65
- # Count the number of business days between two dates
66
- # Start date is included, end date is excluded
67
- >>> yd.count_bdays(start='2023-12-29', end='2024-01-02')
68
- 1
69
- ```
@@ -1 +0,0 @@
1
- __version__ = "0.5.1"
@@ -1,16 +0,0 @@
1
- from .__about__ import __version__
2
- from .di import get_di, read_di
3
- from .calendar import count_bdays, generate_bdays, offset_bdays, is_bday
4
- from .anbima import get_treasury_rates, calculate_treasury_di_spreads
5
-
6
- __all__ = [
7
- "__version__",
8
- "get_di",
9
- "read_di",
10
- "count_bdays",
11
- "generate_bdays",
12
- "offset_bdays",
13
- "is_bday",
14
- "get_treasury_rates",
15
- "calculate_treasury_di_spreads",
16
- ]
@@ -1,6 +0,0 @@
1
- from .core import get_di, read_di
2
-
3
- __all__ = [
4
- "get_di",
5
- "read_di",
6
- ]
File without changes
File without changes
File without changes
File without changes