PYield 0.4.1__tar.gz → 0.5.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pyield-0.4.1 → pyield-0.5.1}/PKG-INFO +8 -17
- {pyield-0.4.1 → pyield-0.5.1}/README.md +7 -16
- pyield-0.5.1/pyield/__about__.py +1 -0
- {pyield-0.4.1 → pyield-0.5.1}/pyield/__init__.py +3 -3
- pyield-0.5.1/pyield/anbima.py +218 -0
- pyield-0.5.1/pyield/calendar.py +320 -0
- pyield-0.5.1/pyield/di/__init__.py +6 -0
- pyield-0.5.1/pyield/di/core.py +179 -0
- pyield-0.4.1/pyield/di_web.py → pyield-0.5.1/pyield/di/web.py +26 -27
- pyield-0.4.1/pyield/di_xml.py → pyield-0.5.1/pyield/di/xml.py +27 -27
- pyield-0.5.1/pyield/holidays/__init__.py +3 -0
- pyield-0.4.1/pyield/br_holidays.py → pyield-0.5.1/pyield/holidays/core.py +4 -5
- {pyield-0.4.1 → pyield-0.5.1}/pyproject.toml +1 -1
- {pyield-0.4.1 → pyield-0.5.1}/tests/test_br_calendar.py +7 -7
- {pyield-0.4.1 → pyield-0.5.1}/tests/test_di.py +9 -9
- pyield-0.4.1/pyield/__about__.py +0 -1
- pyield-0.4.1/pyield/anbima.py +0 -193
- pyield-0.4.1/pyield/br_calendar.py +0 -305
- pyield-0.4.1/pyield/di_futures.py +0 -164
- {pyield-0.4.1 → pyield-0.5.1}/LICENSE +0 -0
- {pyield-0.4.1/pyield → pyield-0.5.1/pyield/holidays}/br_holidays_new.txt +0 -0
- {pyield-0.4.1/pyield → pyield-0.5.1/pyield/holidays}/br_holidays_old.txt +0 -0
- {pyield-0.4.1 → pyield-0.5.1}/pyield/py.typed +0 -0
- {pyield-0.4.1 → pyield-0.5.1}/tests/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: PYield
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.1
|
|
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>
|
|
@@ -48,10 +48,11 @@ Description-Content-Type: text/markdown
|
|
|
48
48
|
|
|
49
49
|
## Introduction
|
|
50
50
|
|
|
51
|
-
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
|
|
51
|
+
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.
|
|
52
|
+
|
|
52
53
|
## Features
|
|
53
54
|
|
|
54
|
-
- **Data Collection**: Automated fetching of data from
|
|
55
|
+
- **Data Collection**: Automated fetching of data from ANBIMA and B3.
|
|
55
56
|
- **Data Processing**: Efficient processing and normalization of fixed income data.
|
|
56
57
|
- **Analysis Tools**: Built-in functions for common analysis tasks in fixed income markets.
|
|
57
58
|
- **Easy Integration**: Seamless integration with Python data analysis workflows.
|
|
@@ -63,8 +64,10 @@ You can install PYield using pip:
|
|
|
63
64
|
```sh
|
|
64
65
|
pip install pyield
|
|
65
66
|
```
|
|
67
|
+
|
|
66
68
|
## How to use PYield
|
|
67
|
-
|
|
69
|
+
|
|
70
|
+
### DI Futures Data
|
|
68
71
|
```python
|
|
69
72
|
import pyield as yd
|
|
70
73
|
|
|
@@ -79,6 +82,7 @@ import pyield as yd
|
|
|
79
82
|
2024-03-08 F38 2038-01-04 3462 ... <NA> <NA> <NA> 10.859
|
|
80
83
|
2024-03-08 F39 2039-01-03 3713 ... <NA> <NA> <NA> 10.85
|
|
81
84
|
```
|
|
85
|
+
|
|
82
86
|
### Business Days Tools (Brazilian holidays are automatically considered)
|
|
83
87
|
```python
|
|
84
88
|
# Generate a pandas series with the business days between two dates
|
|
@@ -105,16 +109,3 @@ Timestamp('2023-12-29 00:00:00')
|
|
|
105
109
|
>>> yd.count_bdays(start='2023-12-29', end='2024-01-02')
|
|
106
110
|
1
|
|
107
111
|
```
|
|
108
|
-
|
|
109
|
-
## Documentation
|
|
110
|
-
|
|
111
|
-
For detailed documentation on all features and functionalities, please visit PYield Documentation.
|
|
112
|
-
Contributing
|
|
113
|
-
|
|
114
|
-
Contributions to PYield are welcome! Please read our Contributing Guidelines for details on how to submit pull requests, report issues, or suggest enhancements.
|
|
115
|
-
License
|
|
116
|
-
|
|
117
|
-
PYield is licensed under the MIT License.
|
|
118
|
-
Acknowledgments
|
|
119
|
-
|
|
120
|
-
PYield was developed with the support of the Python community and financial analysts in Brazil. Special thanks to the maintainers of Pandas and Requests for their invaluable libraries.
|
|
@@ -6,10 +6,11 @@
|
|
|
6
6
|
|
|
7
7
|
## Introduction
|
|
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
|
|
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
|
+
|
|
10
11
|
## Features
|
|
11
12
|
|
|
12
|
-
- **Data Collection**: Automated fetching of data from
|
|
13
|
+
- **Data Collection**: Automated fetching of data from ANBIMA and B3.
|
|
13
14
|
- **Data Processing**: Efficient processing and normalization of fixed income data.
|
|
14
15
|
- **Analysis Tools**: Built-in functions for common analysis tasks in fixed income markets.
|
|
15
16
|
- **Easy Integration**: Seamless integration with Python data analysis workflows.
|
|
@@ -21,8 +22,10 @@ You can install PYield using pip:
|
|
|
21
22
|
```sh
|
|
22
23
|
pip install pyield
|
|
23
24
|
```
|
|
25
|
+
|
|
24
26
|
## How to use PYield
|
|
25
|
-
|
|
27
|
+
|
|
28
|
+
### DI Futures Data
|
|
26
29
|
```python
|
|
27
30
|
import pyield as yd
|
|
28
31
|
|
|
@@ -37,6 +40,7 @@ import pyield as yd
|
|
|
37
40
|
2024-03-08 F38 2038-01-04 3462 ... <NA> <NA> <NA> 10.859
|
|
38
41
|
2024-03-08 F39 2039-01-03 3713 ... <NA> <NA> <NA> 10.85
|
|
39
42
|
```
|
|
43
|
+
|
|
40
44
|
### Business Days Tools (Brazilian holidays are automatically considered)
|
|
41
45
|
```python
|
|
42
46
|
# Generate a pandas series with the business days between two dates
|
|
@@ -63,16 +67,3 @@ Timestamp('2023-12-29 00:00:00')
|
|
|
63
67
|
>>> yd.count_bdays(start='2023-12-29', end='2024-01-02')
|
|
64
68
|
1
|
|
65
69
|
```
|
|
66
|
-
|
|
67
|
-
## Documentation
|
|
68
|
-
|
|
69
|
-
For detailed documentation on all features and functionalities, please visit PYield Documentation.
|
|
70
|
-
Contributing
|
|
71
|
-
|
|
72
|
-
Contributions to PYield are welcome! Please read our Contributing Guidelines for details on how to submit pull requests, report issues, or suggest enhancements.
|
|
73
|
-
License
|
|
74
|
-
|
|
75
|
-
PYield is licensed under the MIT License.
|
|
76
|
-
Acknowledgments
|
|
77
|
-
|
|
78
|
-
PYield was developed with the support of the Python community and financial analysts in Brazil. Special thanks to the maintainers of Pandas and Requests for their invaluable libraries.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.5.1"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
from .__about__ import __version__
|
|
2
|
-
from .
|
|
3
|
-
from .
|
|
2
|
+
from .di import get_di, read_di
|
|
3
|
+
from .calendar import count_bdays, generate_bdays, offset_bdays, is_bday
|
|
4
4
|
from .anbima import get_treasury_rates, calculate_treasury_di_spreads
|
|
5
5
|
|
|
6
6
|
__all__ = [
|
|
@@ -10,7 +10,7 @@ __all__ = [
|
|
|
10
10
|
"count_bdays",
|
|
11
11
|
"generate_bdays",
|
|
12
12
|
"offset_bdays",
|
|
13
|
-
"
|
|
13
|
+
"is_bday",
|
|
14
14
|
"get_treasury_rates",
|
|
15
15
|
"calculate_treasury_di_spreads",
|
|
16
16
|
]
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import io
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import requests
|
|
5
|
+
|
|
6
|
+
from . import di
|
|
7
|
+
from . import calendar as cl
|
|
8
|
+
|
|
9
|
+
# URL Constants
|
|
10
|
+
ANBIMA_NON_MEMBER_URL = "https://www.anbima.com.br/informacoes/merc-sec/arqs/"
|
|
11
|
+
ANBIMA_MEMBER_URL = "http://www.anbima.associados.rtm/merc_sec/arqs/"
|
|
12
|
+
|
|
13
|
+
# Constant for conversion to basis points
|
|
14
|
+
BPS_CONVERSION_FACTOR = 10_000
|
|
15
|
+
|
|
16
|
+
|
|
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
|
+
def _get_anbima_content(reference_date: pd.Timestamp) -> str:
|
|
41
|
+
url_date = reference_date.strftime("%y%m%d")
|
|
42
|
+
member_url = f"{ANBIMA_MEMBER_URL}ms{url_date}.txt"
|
|
43
|
+
non_member_url = f"{ANBIMA_NON_MEMBER_URL}ms{url_date}.txt"
|
|
44
|
+
|
|
45
|
+
# Tries to access the member URL first
|
|
46
|
+
try:
|
|
47
|
+
response = requests.get(member_url)
|
|
48
|
+
# Checks if the response was successful (status code 200)
|
|
49
|
+
response.raise_for_status()
|
|
50
|
+
return response.text
|
|
51
|
+
except requests.exceptions.RequestException:
|
|
52
|
+
# Blind attempt to access the member URL
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
# If the member URL fails, tries to access the non-member URL
|
|
56
|
+
try:
|
|
57
|
+
response = requests.get(non_member_url)
|
|
58
|
+
response.raise_for_status() # Checks if the second attempt was successful
|
|
59
|
+
return response.text
|
|
60
|
+
except requests.exceptions.RequestException:
|
|
61
|
+
# Both URLs failed
|
|
62
|
+
return ""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _get_raw_data(reference_date: pd.Timestamp) -> pd.DataFrame:
|
|
66
|
+
url_content = _get_anbima_content(reference_date)
|
|
67
|
+
if url_content == "":
|
|
68
|
+
date_str = reference_date.strftime("%d-%m-%Y")
|
|
69
|
+
raise ValueError(f"Could not fetch ANBIMA data for {date_str}.")
|
|
70
|
+
|
|
71
|
+
df = pd.read_csv(
|
|
72
|
+
io.StringIO(url_content),
|
|
73
|
+
sep="@",
|
|
74
|
+
encoding="latin-1",
|
|
75
|
+
skiprows=2,
|
|
76
|
+
decimal=",",
|
|
77
|
+
thousands=".",
|
|
78
|
+
na_values=["--"],
|
|
79
|
+
dtype_backend="numpy_nullable",
|
|
80
|
+
)
|
|
81
|
+
return df
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _process_raw_data(df_raw: pd.DataFrame) -> pd.DataFrame:
|
|
85
|
+
"""
|
|
86
|
+
Process raw data from ANBIMA by filtering selected columns, renaming them, and adjusting data formats.
|
|
87
|
+
|
|
88
|
+
Parameters:
|
|
89
|
+
- df (pd.DataFrame): Raw data DataFrame to process.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
- pd.DataFrame: Processed DataFrame.
|
|
93
|
+
"""
|
|
94
|
+
# Filter selected columns and rename them
|
|
95
|
+
selected_columns_dict = {
|
|
96
|
+
"Titulo": "BondType",
|
|
97
|
+
"Data Referencia": "ReferenceDate",
|
|
98
|
+
# "Codigo SELIC": "SelicCode",
|
|
99
|
+
# "Data Base/Emissao": "IssueBaseDate",
|
|
100
|
+
"Data Vencimento": "MaturityDate",
|
|
101
|
+
"Tx. Compra": "BidRate",
|
|
102
|
+
"Tx. Venda": "AskRate",
|
|
103
|
+
"Tx. Indicativas": "IndicativeRate",
|
|
104
|
+
"PU": "Price",
|
|
105
|
+
# "Desvio padrao": "StdDev",
|
|
106
|
+
# "Interv. Ind. Inf. (D0)",
|
|
107
|
+
# "Interv. Ind. Sup. (D0)",
|
|
108
|
+
# "Interv. Ind. Inf. (D+1)",
|
|
109
|
+
# "Interv. Ind. Sup. (D+1)",
|
|
110
|
+
# "Criterio": "Criteria",
|
|
111
|
+
}
|
|
112
|
+
select_columns = list(selected_columns_dict.keys())
|
|
113
|
+
df = df_raw[select_columns].copy()
|
|
114
|
+
df = df.rename(columns=selected_columns_dict)
|
|
115
|
+
|
|
116
|
+
# Remove percentage from rates
|
|
117
|
+
rate_cols = ["BidRate", "AskRate", "IndicativeRate"]
|
|
118
|
+
df[rate_cols] = df[rate_cols] / 100
|
|
119
|
+
|
|
120
|
+
df["ReferenceDate"] = pd.to_datetime(df["ReferenceDate"], format="%Y%m%d")
|
|
121
|
+
df["MaturityDate"] = pd.to_datetime(df["MaturityDate"], format="%Y%m%d")
|
|
122
|
+
|
|
123
|
+
return df.sort_values(["BondType", "MaturityDate"], ignore_index=True)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def get_treasury_rates(
|
|
127
|
+
reference_date: str | pd.Timestamp | None = None,
|
|
128
|
+
return_raw=False,
|
|
129
|
+
) -> pd.DataFrame:
|
|
130
|
+
"""
|
|
131
|
+
Fetches and processes indicative treasury rates from ANBIMA for a specified reference date.
|
|
132
|
+
|
|
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.
|
|
137
|
+
|
|
138
|
+
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.
|
|
142
|
+
|
|
143
|
+
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.
|
|
147
|
+
|
|
148
|
+
Examples:
|
|
149
|
+
# Fetch processed indicative rates for the previous business day
|
|
150
|
+
>>> get_treasury_rates()
|
|
151
|
+
|
|
152
|
+
# Fetch raw indicative rates for a specific date
|
|
153
|
+
>>> get_treasury_rates("2023-12-28")
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
normalized_date = _normalize_date(reference_date)
|
|
157
|
+
df = _get_raw_data(normalized_date)
|
|
158
|
+
|
|
159
|
+
if not return_raw:
|
|
160
|
+
df = _process_raw_data(df)
|
|
161
|
+
|
|
162
|
+
return df
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def calculate_treasury_di_spreads(
|
|
166
|
+
reference_date: str | pd.Timestamp | None = None,
|
|
167
|
+
) -> pd.DataFrame:
|
|
168
|
+
"""
|
|
169
|
+
Calculates the DI spread for Brazilian treasury bonds (LTN and NTN-F) based on ANBIMA's indicative rates.
|
|
170
|
+
|
|
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.
|
|
174
|
+
|
|
175
|
+
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.
|
|
178
|
+
|
|
179
|
+
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.
|
|
182
|
+
|
|
183
|
+
Examples:
|
|
184
|
+
# Calculate DI spreads for the previous business day
|
|
185
|
+
>>> calculate_treasury_di_spreads()
|
|
186
|
+
|
|
187
|
+
# Calculate DI spreads for a specific reference date
|
|
188
|
+
>>> calculate_treasury_di_spreads("2023-12-15")
|
|
189
|
+
"""
|
|
190
|
+
# Validate the reference date, defaulting to the previous business day if not provided
|
|
191
|
+
normalized_date = _normalize_date(reference_date)
|
|
192
|
+
|
|
193
|
+
# Fetch DI rates and adjust the maturity date format for compatibility
|
|
194
|
+
df_di = di.get_di(normalized_date)[["ExpirationDate", "SettlementRate"]]
|
|
195
|
+
|
|
196
|
+
# Renaming the columns to match the ANBIMA structure
|
|
197
|
+
df_di.rename(columns={"ExpirationDate": "MaturityDate"}, inplace=True)
|
|
198
|
+
|
|
199
|
+
# Adjusting maturity date to match bond data format
|
|
200
|
+
df_di["MaturityDate"] = df_di["MaturityDate"].dt.to_period("M").dt.to_timestamp()
|
|
201
|
+
|
|
202
|
+
# Fetch bond rates, filtering for LTN and NTN-F types
|
|
203
|
+
df_anbima = get_treasury_rates(normalized_date, False)
|
|
204
|
+
df_anbima.query("BondType in ['LTN', 'NTN-F']", inplace=True)
|
|
205
|
+
|
|
206
|
+
# Merge bond and DI rates by maturity date to calculate spreads
|
|
207
|
+
df_final = pd.merge(df_anbima, df_di, how="left", on="MaturityDate")
|
|
208
|
+
|
|
209
|
+
# Calculating the DI spread as the difference between indicative and settlement rates
|
|
210
|
+
df_final["DISpread"] = df_final["IndicativeRate"] - df_final["SettlementRate"]
|
|
211
|
+
|
|
212
|
+
# Convert spread to basis points for clarity
|
|
213
|
+
df_final["DISpread"] = (BPS_CONVERSION_FACTOR * df_final["DISpread"]).round(2)
|
|
214
|
+
|
|
215
|
+
# Prepare and return the final sorted DataFrame
|
|
216
|
+
select_columns = ["BondType", "ReferenceDate", "MaturityDate", "DISpread"]
|
|
217
|
+
df_final = df_final[select_columns].copy()
|
|
218
|
+
return df_final.sort_values(["BondType", "MaturityDate"], ignore_index=True)
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
from typing import Literal, overload, Union
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
from .holidays import BrHolidays
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
SingleDateTypes = Union[str, np.datetime64, pd.Timestamp, datetime]
|
|
12
|
+
|
|
13
|
+
SeriesDateTypes = Union[list, tuple, np.ndarray, pd.Series, pd.Index, pd.DatetimeIndex]
|
|
14
|
+
|
|
15
|
+
TO_TIMESTAMP_TYPES = (str, np.datetime64, datetime)
|
|
16
|
+
TO_SERIES_TYPES = (list, tuple, np.ndarray, pd.Series, pd.Index, pd.DatetimeIndex)
|
|
17
|
+
|
|
18
|
+
# Initialize the BrHolidays class
|
|
19
|
+
br_holidays = BrHolidays()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@overload
|
|
23
|
+
def _normalize_input_dates(
|
|
24
|
+
dates: SingleDateTypes | None,
|
|
25
|
+
) -> pd.Timestamp: ...
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@overload
|
|
29
|
+
def _normalize_input_dates(
|
|
30
|
+
dates: SeriesDateTypes,
|
|
31
|
+
) -> pd.Series: ...
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _normalize_input_dates(
|
|
35
|
+
dates: SingleDateTypes | SeriesDateTypes | None = None,
|
|
36
|
+
) -> pd.Timestamp | pd.Series:
|
|
37
|
+
if dates is None:
|
|
38
|
+
return pd.Timestamp.today().normalize()
|
|
39
|
+
elif isinstance(dates, pd.Timestamp):
|
|
40
|
+
return dates.normalize()
|
|
41
|
+
elif isinstance(dates, TO_TIMESTAMP_TYPES):
|
|
42
|
+
return pd.Timestamp(dates).normalize()
|
|
43
|
+
elif isinstance(dates, TO_SERIES_TYPES):
|
|
44
|
+
result = pd.to_datetime(dates)
|
|
45
|
+
return pd.Series(result).dt.normalize()
|
|
46
|
+
else:
|
|
47
|
+
raise ValueError("Invalid date format.")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_bday(date: SingleDateTypes | None = None) -> bool:
|
|
51
|
+
"""
|
|
52
|
+
Checks if the input date is a business day.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
date (str | np.datetime64 | pd.Timestamp | datetime, optional): The date to
|
|
56
|
+
check. If None, the current date is used.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
bool: True if the input date is a business day, False otherwise.
|
|
60
|
+
|
|
61
|
+
Examples:
|
|
62
|
+
>>> yd.is_bday('2023-12-25') # Christmas
|
|
63
|
+
False
|
|
64
|
+
>>> yd.is_bday() # Check if today is a business day
|
|
65
|
+
True
|
|
66
|
+
"""
|
|
67
|
+
normalized_date = _normalize_input_dates(date)
|
|
68
|
+
# Shift the date if it is not a business day
|
|
69
|
+
adjusted_date = offset_bdays(normalized_date, 0)
|
|
70
|
+
return normalized_date == adjusted_date
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _convert_to_numpy_date(
|
|
74
|
+
dates: pd.Timestamp | pd.Series,
|
|
75
|
+
) -> np.datetime64 | np.ndarray:
|
|
76
|
+
"""
|
|
77
|
+
Converts the input dates to a numpy datetime64[D] format.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
dates (Timestamp | Series): A single date or a Series of dates.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
np.datetime64 | np.ndarray: The input dates in a numpy datetime64[D] format.
|
|
84
|
+
"""
|
|
85
|
+
if isinstance(dates, pd.Timestamp):
|
|
86
|
+
return np.datetime64(dates, "D")
|
|
87
|
+
else:
|
|
88
|
+
return dates.to_numpy().astype("datetime64[D]")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@overload
|
|
92
|
+
def offset_bdays(
|
|
93
|
+
dates: SingleDateTypes | None = None,
|
|
94
|
+
offset: int = 0,
|
|
95
|
+
roll: Literal["forward", "backward"] = "forward",
|
|
96
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
97
|
+
) -> pd.Timestamp: ...
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@overload
|
|
101
|
+
def offset_bdays(
|
|
102
|
+
dates: SeriesDateTypes,
|
|
103
|
+
offset: int = 0,
|
|
104
|
+
roll: Literal["forward", "backward"] = "forward",
|
|
105
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
106
|
+
) -> pd.Series: ...
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def offset_bdays(
|
|
110
|
+
dates: SingleDateTypes | SeriesDateTypes | None = None,
|
|
111
|
+
offset: int = 0,
|
|
112
|
+
roll: Literal["forward", "backward"] = "forward",
|
|
113
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
114
|
+
) -> pd.Timestamp | pd.Series:
|
|
115
|
+
"""
|
|
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.
|
|
120
|
+
|
|
121
|
+
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".
|
|
131
|
+
|
|
132
|
+
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.
|
|
135
|
+
|
|
136
|
+
Examples:
|
|
137
|
+
>>> date = '2023-12-23' # Saturday before Christmas
|
|
138
|
+
>>> yd.offset_bdays(date, 0)
|
|
139
|
+
Timestamp('2023-12-26')
|
|
140
|
+
|
|
141
|
+
>>> date = '2023-12-22' # Friday before Christmas
|
|
142
|
+
>>> yd.offset_bdays(date, 0)
|
|
143
|
+
Timestamp('2023-12-22') # No offset because it's a business day
|
|
144
|
+
|
|
145
|
+
>>> yd.offset_bdays(date, 1)
|
|
146
|
+
Timestamp('2023-12-26') # Offset to the next business day
|
|
147
|
+
|
|
148
|
+
>>> yd.offset_bdays(date, -1)
|
|
149
|
+
Timestamp('2023-12-21') # Offset to the previous business day
|
|
150
|
+
|
|
151
|
+
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`
|
|
154
|
+
documentation: https://numpy.org/doc/stable/reference/generated/numpy.busday_offset.html
|
|
155
|
+
"""
|
|
156
|
+
normalized_dates = _normalize_input_dates(dates)
|
|
157
|
+
|
|
158
|
+
selected_holidays = br_holidays.get_applicable_holidays(
|
|
159
|
+
normalized_dates, holiday_list
|
|
160
|
+
)
|
|
161
|
+
selected_holidays_np = _convert_to_numpy_date(selected_holidays)
|
|
162
|
+
|
|
163
|
+
dates_np = _convert_to_numpy_date(normalized_dates)
|
|
164
|
+
offsetted_dates_np = np.busday_offset(
|
|
165
|
+
dates_np, offsets=offset, roll=roll, holidays=selected_holidays_np
|
|
166
|
+
)
|
|
167
|
+
if isinstance(offsetted_dates_np, np.datetime64):
|
|
168
|
+
return pd.Timestamp(offsetted_dates_np, unit="ns")
|
|
169
|
+
else:
|
|
170
|
+
result = pd.to_datetime(offsetted_dates_np, unit="ns")
|
|
171
|
+
return pd.Series(result)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@overload
|
|
175
|
+
def count_bdays(
|
|
176
|
+
start: SingleDateTypes | None = None,
|
|
177
|
+
end: SingleDateTypes | None = None,
|
|
178
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
179
|
+
) -> int: ...
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@overload
|
|
183
|
+
def count_bdays(
|
|
184
|
+
start: SeriesDateTypes,
|
|
185
|
+
end: SingleDateTypes | None,
|
|
186
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
187
|
+
) -> pd.Series: ...
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@overload
|
|
191
|
+
def count_bdays(
|
|
192
|
+
start: SingleDateTypes | None,
|
|
193
|
+
end: SeriesDateTypes,
|
|
194
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
195
|
+
) -> pd.Series: ...
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@overload
|
|
199
|
+
def count_bdays(
|
|
200
|
+
start: SeriesDateTypes,
|
|
201
|
+
end: SeriesDateTypes,
|
|
202
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
203
|
+
) -> pd.Series: ...
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def count_bdays(
|
|
207
|
+
start: SingleDateTypes | SeriesDateTypes | None = None,
|
|
208
|
+
end: SingleDateTypes | SeriesDateTypes | None = None,
|
|
209
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
210
|
+
) -> int | pd.Series:
|
|
211
|
+
"""
|
|
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.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
start (str | np.datetime64 | pd.Timestamp | datetime | list | tuple | np.ndarray | pd.Series | pd.Index | pd.DatetimeIndex, optional):
|
|
220
|
+
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.
|
|
223
|
+
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".
|
|
226
|
+
|
|
227
|
+
Returns:
|
|
228
|
+
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`.
|
|
230
|
+
|
|
231
|
+
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.
|
|
236
|
+
|
|
237
|
+
Examples:
|
|
238
|
+
>>> yd.count_bdays('2023-12-15', '2024-01-01')
|
|
239
|
+
10
|
|
240
|
+
|
|
241
|
+
>>> start = '2023-01-01'
|
|
242
|
+
>>> end = pd.to_datetime(['2023-01-31', '2023-03-01'])
|
|
243
|
+
>>> yd.count_bdays(start, end)
|
|
244
|
+
pd.Series([22, 40], dtype='int64')
|
|
245
|
+
"""
|
|
246
|
+
normalized_start = _normalize_input_dates(start)
|
|
247
|
+
normalized_end = _normalize_input_dates(end)
|
|
248
|
+
|
|
249
|
+
# Determine which list of holidays to use
|
|
250
|
+
selected_holidays = br_holidays.get_applicable_holidays(
|
|
251
|
+
normalized_start, holiday_list
|
|
252
|
+
)
|
|
253
|
+
selected_holidays_np = _convert_to_numpy_date(selected_holidays)
|
|
254
|
+
|
|
255
|
+
# Convert inputs to numpy datetime64[D] before calling numpy.busday_count
|
|
256
|
+
start_np = _convert_to_numpy_date(normalized_start)
|
|
257
|
+
end_np = _convert_to_numpy_date(normalized_end)
|
|
258
|
+
|
|
259
|
+
result_np = np.busday_count(start_np, end_np, holidays=selected_holidays_np)
|
|
260
|
+
if isinstance(result_np, np.int64):
|
|
261
|
+
return int(result_np)
|
|
262
|
+
else:
|
|
263
|
+
return pd.Series(result_np, dtype="Int64")
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def generate_bdays(
|
|
267
|
+
start: SingleDateTypes | None = None,
|
|
268
|
+
end: SingleDateTypes | None = None,
|
|
269
|
+
inclusive: Literal["both", "neither", "left", "right"] = "both",
|
|
270
|
+
holiday_list: Literal["old", "new", "infer"] = "infer",
|
|
271
|
+
**kwargs,
|
|
272
|
+
) -> pd.Series:
|
|
273
|
+
"""
|
|
274
|
+
Generates a Series of business days between a `start` and `end` date, considering
|
|
275
|
+
the list of Brazilian holidays. It supports customization of holiday lists and
|
|
276
|
+
inclusion options for start and end dates. It wraps `pandas.bdate_range`.
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
start (str | np.datetime64 | pd.Timestamp | datetime, optional):
|
|
280
|
+
The start date for generating business days. Defaults to None, using the current date.
|
|
281
|
+
end (str | np.datetime64 | pd.Timestamp | datetime, optional):
|
|
282
|
+
The end date for generating business days. Defaults to None, using the current date.
|
|
283
|
+
inclusive (Literal["both", "neither", "left", "right"], optional):
|
|
284
|
+
Determines which of the start and end dates are included in the result.
|
|
285
|
+
Valid options are 'both', 'neither', 'left', 'right'. Defaults to 'both'.
|
|
286
|
+
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".
|
|
289
|
+
**kwargs:
|
|
290
|
+
Additional keyword arguments passed to `pandas.bdate_range` for customization.
|
|
291
|
+
|
|
292
|
+
Returns:
|
|
293
|
+
pd.Series: A Series representing a range of business days between the specified start and end dates,
|
|
294
|
+
considering the specified holidays.
|
|
295
|
+
|
|
296
|
+
Examples:
|
|
297
|
+
>>> 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]')
|
|
299
|
+
|
|
300
|
+
Note:
|
|
301
|
+
For detailed information on parameters and error handling, refer to `pandas.bdate_range` documentation:
|
|
302
|
+
https://pandas.pydata.org/docs/reference/api/pandas.bdate_range.html.
|
|
303
|
+
"""
|
|
304
|
+
normalized_start = _normalize_input_dates(start)
|
|
305
|
+
normalized_end = _normalize_input_dates(end)
|
|
306
|
+
|
|
307
|
+
selected_holidays = br_holidays.get_applicable_holidays(
|
|
308
|
+
normalized_start, holiday_list
|
|
309
|
+
)
|
|
310
|
+
selected_holidays_list = selected_holidays.to_list()
|
|
311
|
+
|
|
312
|
+
result = pd.bdate_range(
|
|
313
|
+
normalized_start,
|
|
314
|
+
normalized_end,
|
|
315
|
+
freq="C",
|
|
316
|
+
inclusive=inclusive,
|
|
317
|
+
holidays=selected_holidays_list,
|
|
318
|
+
**kwargs,
|
|
319
|
+
)
|
|
320
|
+
return pd.Series(result)
|