PYield 0.35.8__tar.gz → 0.36.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.
- {pyield-0.35.8 → pyield-0.36.0}/PKG-INFO +1 -1
- pyield-0.36.0/pyield/__about__.py +1 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/__init__.py +2 -1
- {pyield-0.35.8 → pyield-0.36.0}/pyield/anbima/tpf.py +1 -1
- {pyield-0.35.8 → pyield-0.36.0}/pyield/b3/di1.py +5 -2
- {pyield-0.35.8 → pyield-0.36.0}/pyield/b3/futures/common.py +5 -2
- {pyield-0.35.8 → pyield-0.36.0}/pyield/b3/futures/historical.py +9 -7
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bc/auction.py +2 -4
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bday.py +137 -138
- pyield-0.36.0/pyield/tn/pre.py +146 -0
- pyield-0.35.8/pyield/__about__.py +0 -1
- {pyield-0.35.8 → pyield-0.36.0}/.gitignore +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/LICENSE +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/README.md +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/anbima/__init__.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/anbima/ettj.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/anbima/ima.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/anbima/imaq.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/anbima/ipca.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/b3/__init__.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/b3/di_over.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/b3/futures/__init__.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/b3/futures/intraday.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/b3/futures/xml.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bc/__init__.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bc/bcdata.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bc/ptax.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bc/repo.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bc/trades_intraday.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bc/trades_monthly.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/bc/vna.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/conftest.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/data_cache.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/date_converter.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/fwd.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/holidays/__init__.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/holidays/br_holidays_new.txt +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/holidays/br_holidays_old.txt +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/holidays/brholidays.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/ibge/__init__.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/ibge/ipca.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/interpolator.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/py.typed +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/retry.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/tn/__init__.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/tn/auction.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/tn/lft.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/tn/ltn.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/tn/ntnb.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/tn/ntnc.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/tn/ntnf.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyield/tn/tools.py +0 -0
- {pyield-0.35.8 → pyield-0.36.0}/pyproject.toml +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.36.0"
|
|
@@ -5,7 +5,7 @@ from pyield.__about__ import __version__
|
|
|
5
5
|
from pyield.b3 import di1, futures
|
|
6
6
|
from pyield.fwd import forward, forwards
|
|
7
7
|
from pyield.interpolator import Interpolator
|
|
8
|
-
from pyield.tn import lft, ltn, ntnb, ntnc, ntnf
|
|
8
|
+
from pyield.tn import lft, ltn, ntnb, ntnc, ntnf, pre
|
|
9
9
|
|
|
10
10
|
__all__ = [
|
|
11
11
|
"__version__",
|
|
@@ -25,6 +25,7 @@ __all__ = [
|
|
|
25
25
|
"ntnb",
|
|
26
26
|
"ntnc",
|
|
27
27
|
"ntnf",
|
|
28
|
+
"pre",
|
|
28
29
|
]
|
|
29
30
|
|
|
30
31
|
# Configura o logger do pacote principal com um NullHandler
|
|
@@ -81,7 +81,7 @@ def data(
|
|
|
81
81
|
|
|
82
82
|
if pre_filter:
|
|
83
83
|
df_pre = (
|
|
84
|
-
get_cached_dataset("
|
|
84
|
+
get_cached_dataset("tpf")
|
|
85
85
|
.query("BondType in ['LTN', 'NTN-F']")
|
|
86
86
|
.drop_duplicates(subset=["ReferenceDate", "MaturityDate"])
|
|
87
87
|
.sort_values(["ReferenceDate", "MaturityDate"])
|
|
@@ -327,8 +327,9 @@ def interpolate_rate(
|
|
|
327
327
|
>>> di1.interpolate_rate("25-04-2025", "01-01-2050", extrapolate=True)
|
|
328
328
|
0.13881
|
|
329
329
|
"""
|
|
330
|
+
date = dc.convert_input_dates(date)
|
|
330
331
|
expiration = dc.convert_input_dates(expiration)
|
|
331
|
-
if not date:
|
|
332
|
+
if not date or not expiration:
|
|
332
333
|
return float("NaN")
|
|
333
334
|
|
|
334
335
|
# Get the DI contract DataFrame
|
|
@@ -357,6 +358,8 @@ def interpolate_rate(
|
|
|
357
358
|
extrapolate=extrapolate,
|
|
358
359
|
)
|
|
359
360
|
bd = bday.count(date, expiration)
|
|
361
|
+
if pd.isna(bd):
|
|
362
|
+
return float("NaN")
|
|
360
363
|
return ff_interp(bd)
|
|
361
364
|
|
|
362
365
|
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import pandas as pd
|
|
2
|
+
from pandas.api.typing import NaTType
|
|
2
3
|
|
|
3
4
|
from pyield import bday
|
|
4
5
|
|
|
5
6
|
|
|
6
|
-
def get_expiration_date(
|
|
7
|
+
def get_expiration_date(
|
|
8
|
+
expiration_code: str, expiration_day: int = 1
|
|
9
|
+
) -> pd.Timestamp | NaTType:
|
|
7
10
|
"""
|
|
8
11
|
Converts an expiration code into its corresponding expiration date.
|
|
9
12
|
|
|
@@ -64,4 +67,4 @@ def get_expiration_date(expiration_code: str, expiration_day: int = 1) -> pd.Tim
|
|
|
64
67
|
return adj_expiration
|
|
65
68
|
|
|
66
69
|
except (KeyError, ValueError):
|
|
67
|
-
return pd.NaT
|
|
70
|
+
return pd.NaT
|
|
@@ -3,6 +3,7 @@ import logging
|
|
|
3
3
|
|
|
4
4
|
import pandas as pd
|
|
5
5
|
import requests
|
|
6
|
+
from pandas.api.typing import NaTType
|
|
6
7
|
|
|
7
8
|
from pyield import bday
|
|
8
9
|
from pyield.b3.futures import common
|
|
@@ -12,7 +13,9 @@ logger = logging.getLogger(__name__)
|
|
|
12
13
|
COUNT_CONVENTIONS = {"DAP": 252, "DI1": 252, "DDI": 360}
|
|
13
14
|
|
|
14
15
|
|
|
15
|
-
def get_old_expiration_date(
|
|
16
|
+
def get_old_expiration_date(
|
|
17
|
+
expiration_code: str, date: pd.Timestamp
|
|
18
|
+
) -> pd.Timestamp | NaTType:
|
|
16
19
|
"""
|
|
17
20
|
Internal function to convert an old DI contract code into its ExpirationDate date.
|
|
18
21
|
Valid for contract codes up to 21-05-2006.
|
|
@@ -68,7 +71,7 @@ def get_old_expiration_date(expiration_code: str, date: pd.Timestamp) -> pd.Time
|
|
|
68
71
|
return bday.offset(dates=expiration_date, offset=0)
|
|
69
72
|
|
|
70
73
|
except (KeyError, ValueError):
|
|
71
|
-
return pd.NaT
|
|
74
|
+
return pd.NaT
|
|
72
75
|
|
|
73
76
|
|
|
74
77
|
def _convert_prices_to_rates(
|
|
@@ -184,19 +187,18 @@ def process_df(
|
|
|
184
187
|
df["TradeDate"] = date
|
|
185
188
|
# Convert to datetime64[ns] since it is pandas default type for timestamps
|
|
186
189
|
df["TradeDate"] = df["TradeDate"].astype("datetime64[ns]")
|
|
187
|
-
|
|
188
190
|
df["TickerSymbol"] = contract_code + df["ExpirationCode"]
|
|
189
191
|
|
|
190
192
|
# Contract code format was changed in 22/05/2006
|
|
191
193
|
if date < pd.Timestamp("2006-05-22"):
|
|
192
194
|
df["ExpirationDate"] = df["ExpirationCode"].apply(
|
|
193
|
-
get_old_expiration_date,
|
|
194
|
-
)
|
|
195
|
+
lambda code: get_old_expiration_date(code, date)
|
|
196
|
+
) # type: ignore
|
|
195
197
|
else:
|
|
196
198
|
expiration_day = 15 if contract_code == "DAP" else 1
|
|
197
199
|
df["ExpirationDate"] = df["ExpirationCode"].apply(
|
|
198
|
-
common.get_expiration_date,
|
|
199
|
-
)
|
|
200
|
+
lambda code: common.get_expiration_date(code, expiration_day)
|
|
201
|
+
) # type: ignore
|
|
200
202
|
|
|
201
203
|
df["DaysToExp"] = (df["ExpirationDate"] - date).dt.days
|
|
202
204
|
# Convert to nullable integer, since it is the default type in the library
|
|
@@ -351,10 +351,8 @@ def auctions(
|
|
|
351
351
|
# Mapeamento do auction_type para o valor esperado pela API
|
|
352
352
|
auction_type_mapping = {"sell": "Venda", "buy": "Compra"}
|
|
353
353
|
if auction_type:
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
# Adiciona o parâmetro tipoOferta à URL se auction_type for fornecido
|
|
357
|
-
if auction_type_api_value:
|
|
354
|
+
auction_type_api_value = auction_type_mapping[auction_type]
|
|
355
|
+
# Adiciona o parâmetro tipoOferta à URL se auction_type for fornecido
|
|
358
356
|
url += f"&@tipoOferta='{auction_type_api_value}'"
|
|
359
357
|
|
|
360
358
|
url += "&$format=text/csv" # Adiciona o formato CSV ao final
|
|
@@ -3,6 +3,7 @@ from zoneinfo import ZoneInfo
|
|
|
3
3
|
|
|
4
4
|
import numpy as np
|
|
5
5
|
import pandas as pd
|
|
6
|
+
from pandas.api.typing import NaTType, NAType
|
|
6
7
|
|
|
7
8
|
import pyield.date_converter as dc
|
|
8
9
|
import pyield.holidays as hl
|
|
@@ -23,32 +24,24 @@ NEW_HOLIDAYS_ARRAY = br_holidays.get_holiday_array(holiday_option="new")
|
|
|
23
24
|
@overload
|
|
24
25
|
def offset(
|
|
25
26
|
dates: DateScalar, offset: IntegerScalar, roll: Literal["forward", "backward"] = ...
|
|
26
|
-
) -> pd.Timestamp: ...
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
) -> pd.Timestamp | NaTType: ...
|
|
29
28
|
@overload
|
|
30
29
|
def offset(
|
|
31
|
-
dates: DateArray,
|
|
30
|
+
dates: DateArray,
|
|
31
|
+
offset: IntegerArray | IntegerScalar,
|
|
32
|
+
roll: Literal["forward", "backward"] = ...,
|
|
32
33
|
) -> pd.Series: ...
|
|
33
|
-
|
|
34
|
-
|
|
35
34
|
@overload
|
|
36
35
|
def offset(
|
|
37
36
|
dates: DateScalar, offset: IntegerArray, roll: Literal["forward", "backward"] = ...
|
|
38
37
|
) -> pd.Series: ...
|
|
39
38
|
|
|
40
39
|
|
|
41
|
-
|
|
42
|
-
def offset(
|
|
43
|
-
dates: DateArray, offset: IntegerScalar, roll: Literal["forward", "backward"] = ...
|
|
44
|
-
) -> pd.Series: ...
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
def offset(
|
|
40
|
+
def offset( # noqa
|
|
48
41
|
dates: DateScalar | DateArray,
|
|
49
42
|
offset: IntegerScalar | IntegerArray,
|
|
50
43
|
roll: Literal["forward", "backward"] = "forward",
|
|
51
|
-
) -> pd.Timestamp | pd.Series:
|
|
44
|
+
) -> pd.Timestamp | pd.Series | NaTType:
|
|
52
45
|
"""
|
|
53
46
|
First adjusts the date to fall on a valid day according to the roll rule, then
|
|
54
47
|
applies offsets to the given dates to the next or previous business day, considering
|
|
@@ -56,8 +49,11 @@ def offset(
|
|
|
56
49
|
dates. It is a wrapper for `numpy.busday_offset` adapted for Pandas data types and
|
|
57
50
|
brazilian holidays.
|
|
58
51
|
|
|
59
|
-
**Important Note:**
|
|
60
|
-
holidays applies to the calculation.
|
|
52
|
+
**Important Note:** Each date in the `dates` input is evaluated individually to
|
|
53
|
+
determine which list of holidays applies to the calculation. Transition date
|
|
54
|
+
is 2023-12-26, which means:
|
|
55
|
+
- Dates before 2023-12-26 use the old holiday list.
|
|
56
|
+
- Dates on or after 2023-12-26 use the new holiday list.
|
|
61
57
|
|
|
62
58
|
Args:
|
|
63
59
|
dates (DateScalar | DateArray): The date(s) to offset. Can be a scalar date type
|
|
@@ -85,46 +81,45 @@ def offset(
|
|
|
85
81
|
|
|
86
82
|
Offset to the next business day if not a bday (offset=0 and roll="forward")
|
|
87
83
|
|
|
88
|
-
|
|
84
|
+
Offset Saturday before Christmas to the next b. day (Tuesday after Christmas)
|
|
89
85
|
>>> bday.offset("23-12-2023", 0)
|
|
90
86
|
Timestamp('2023-12-26 00:00:00')
|
|
91
87
|
|
|
92
|
-
|
|
88
|
+
Offset Friday before Christmas (no offset because it's a business day)
|
|
93
89
|
>>> bday.offset("22-12-2023", 0)
|
|
94
90
|
Timestamp('2023-12-22 00:00:00')
|
|
95
91
|
|
|
96
92
|
Offset to the previous business day if not a bday (offset=0 and roll="backward")
|
|
97
93
|
|
|
98
|
-
|
|
94
|
+
No offset because it's a business day
|
|
99
95
|
>>> bday.offset("22-12-2023", 0, roll="backward")
|
|
100
96
|
Timestamp('2023-12-22 00:00:00')
|
|
101
97
|
|
|
102
|
-
|
|
98
|
+
Offset to the first business day before "23-12-2023"
|
|
103
99
|
>>> bday.offset("23-12-2023", 0, roll="backward")
|
|
104
100
|
Timestamp('2023-12-22 00:00:00')
|
|
105
101
|
|
|
106
102
|
Jump to the next business day (1 offset and roll="forward")
|
|
107
103
|
|
|
108
|
-
|
|
104
|
+
Offset Friday to the next business day (Friday is jumped -> Monday)
|
|
109
105
|
>>> bday.offset("27-09-2024", 1)
|
|
110
106
|
Timestamp('2024-09-30 00:00:00')
|
|
111
107
|
|
|
112
|
-
|
|
108
|
+
Offset Saturday to the next business day (Monday is jumped -> Tuesday)
|
|
113
109
|
>>> bday.offset("28-09-2024", 1)
|
|
114
110
|
Timestamp('2024-10-01 00:00:00')
|
|
115
111
|
|
|
116
112
|
Jump to the previous business day (-1 offset and roll="backward")
|
|
117
113
|
|
|
118
|
-
|
|
114
|
+
Offset Friday to the previous business day (Friday is jumped -> Thursday)
|
|
119
115
|
>>> bday.offset("27-09-2024", -1, roll="backward")
|
|
120
116
|
Timestamp('2024-09-26 00:00:00')
|
|
121
117
|
|
|
122
|
-
|
|
118
|
+
Offset Saturday to the previous business day (Friday is jumped -> Thursday)
|
|
123
119
|
>>> bday.offset("28-09-2024", -1, roll="backward")
|
|
124
120
|
Timestamp('2024-09-26 00:00:00')
|
|
125
121
|
|
|
126
122
|
List of dates and offsets
|
|
127
|
-
|
|
128
123
|
>>> bday.offset(["19-09-2024", "20-09-2024"], 1) # a list of dates
|
|
129
124
|
0 2024-09-20
|
|
130
125
|
1 2024-09-23
|
|
@@ -136,7 +131,6 @@ def offset(
|
|
|
136
131
|
dtype: datetime64[ns]
|
|
137
132
|
|
|
138
133
|
Null values are propagated
|
|
139
|
-
|
|
140
134
|
>>> bday.offset(pd.NaT, 1) # NaT input
|
|
141
135
|
NaT
|
|
142
136
|
|
|
@@ -150,6 +144,17 @@ def offset(
|
|
|
150
144
|
1 NaT
|
|
151
145
|
dtype: datetime64[ns]
|
|
152
146
|
|
|
147
|
+
Original pandas index is preserved
|
|
148
|
+
>>> dates = pd.Series(
|
|
149
|
+
... ["19-09-2024", "20-09-2024", "21-09-2024"],
|
|
150
|
+
... index=["a", "b", "c"],
|
|
151
|
+
... )
|
|
152
|
+
>>> bday.offset(dates, 1)
|
|
153
|
+
a 2024-09-20
|
|
154
|
+
b 2024-09-23
|
|
155
|
+
c 2024-09-24
|
|
156
|
+
dtype: datetime64[ns]
|
|
157
|
+
|
|
153
158
|
Note:
|
|
154
159
|
This function uses `numpy.busday_offset` under the hood, which means it follows
|
|
155
160
|
the same conventions and limitations for business day calculations. For detailed
|
|
@@ -157,92 +162,88 @@ def offset(
|
|
|
157
162
|
documentation:
|
|
158
163
|
https://numpy.org/doc/stable/reference/generated/numpy.busday_offset.html
|
|
159
164
|
"""
|
|
165
|
+
# Padroniza as entradas para objetos do Pandas
|
|
160
166
|
dates_pd = dc.convert_input_dates(dates)
|
|
167
|
+
offset_pd = pd.Series(offset) if isinstance(offset, IntegerArray) else offset
|
|
161
168
|
|
|
162
|
-
#
|
|
163
|
-
if dates_pd
|
|
164
|
-
if
|
|
165
|
-
|
|
166
|
-
return pd.Series([pd.NaT] * len(offset), dtype="datetime64[ns]")
|
|
167
|
-
else:
|
|
168
|
-
return pd.NaT
|
|
169
|
+
# 1. VALIDAÇÃO ESTRUTURAL
|
|
170
|
+
if isinstance(dates_pd, pd.Series) and isinstance(offset_pd, pd.Series):
|
|
171
|
+
if not dates_pd.index.equals(offset_pd.index):
|
|
172
|
+
raise ValueError("Input dates have different indices!")
|
|
169
173
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
174
|
+
# 2. LÓGICA PRINCIPAL
|
|
175
|
+
|
|
176
|
+
# --- CASO 1: AMBOS OS INPUTS SÃO ESCALARES ---
|
|
177
|
+
if not isinstance(dates_pd, pd.Series) and not isinstance(offset_pd, pd.Series):
|
|
178
|
+
if pd.isna(dates_pd) or pd.isna(offset_pd):
|
|
179
|
+
return pd.NaT
|
|
176
180
|
|
|
177
|
-
|
|
178
|
-
dc.to_numpy_date_type(
|
|
179
|
-
offsets=
|
|
181
|
+
offsetted_date_np = np.busday_offset(
|
|
182
|
+
dates=dc.to_numpy_date_type(dates_pd),
|
|
183
|
+
offsets=offset_pd,
|
|
180
184
|
roll=roll,
|
|
181
|
-
holidays=
|
|
185
|
+
holidays=br_holidays.get_holiday_array(dates_pd),
|
|
182
186
|
)
|
|
183
187
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
roll=roll,
|
|
188
|
-
holidays=NEW_HOLIDAYS_ARRAY,
|
|
188
|
+
assert isinstance(offsetted_date_np, np.datetime64), (
|
|
189
|
+
"Assumption violated: np.busday_offset did not return a scalar "
|
|
190
|
+
f"np.datetime64 for scalar inputs. Got: {type(offsetted_date_np)}"
|
|
189
191
|
)
|
|
192
|
+
return pd.Timestamp(offsetted_date_np).as_unit("ns")
|
|
190
193
|
|
|
191
|
-
|
|
192
|
-
offsetted_old_dates = pd.to_datetime(offsetted_old_dates)
|
|
193
|
-
offsetted_new_dates = pd.to_datetime(offsetted_new_dates)
|
|
194
|
+
# --- CASO 2: PELO MENOS UM DOS INPUTS É UMA SÉRIE ---
|
|
194
195
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
196
|
+
# Garante que ambas as variáveis sejam Series para alinhamento automático.
|
|
197
|
+
# O Pandas faz o "broadcast" do escalar para o tamanho da Series.
|
|
198
|
+
if isinstance(offset_pd, pd.Series):
|
|
199
|
+
dates_pd = pd.Series(dates_pd, index=offset_pd.index)
|
|
200
|
+
else:
|
|
201
|
+
assert isinstance(dates_pd, pd.Series) # Linter satisfaction
|
|
202
|
+
offset_pd = pd.Series(offset_pd, index=dates_pd.index)
|
|
198
203
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
offsetted_new_dates.index = new_dates.index
|
|
204
|
+
# Inicializa a série de resultados com o índice correto e tipo que suporta NaT.
|
|
205
|
+
result = pd.Series(index=dates_pd.index, dtype="datetime64[ns]")
|
|
202
206
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
207
|
+
# Divide the input in order to apply the correct holiday list
|
|
208
|
+
mask_not_null = dates_pd.notna() & offset_pd.notna()
|
|
209
|
+
mask_old_holidays = mask_not_null & (dates_pd < br_holidays.TRANSITION_DATE)
|
|
210
|
+
mask_new_holidays = mask_not_null & (dates_pd >= br_holidays.TRANSITION_DATE)
|
|
206
211
|
|
|
207
|
-
|
|
208
|
-
|
|
212
|
+
if mask_old_holidays.any():
|
|
213
|
+
np_offset_values = np.busday_offset(
|
|
214
|
+
dates=dc.to_numpy_date_type(dates_pd[mask_old_holidays]),
|
|
215
|
+
offsets=offset_pd[mask_old_holidays],
|
|
216
|
+
roll=roll,
|
|
217
|
+
holidays=OLD_HOLIDAYS_ARRAY,
|
|
218
|
+
)
|
|
219
|
+
pd_offset_values = pd.to_datetime(np_offset_values).astype("datetime64[ns]")
|
|
220
|
+
result.loc[mask_old_holidays] = pd_offset_values
|
|
209
221
|
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
dc.to_numpy_date_type(dates_pd),
|
|
213
|
-
offsets=
|
|
222
|
+
if mask_new_holidays.any():
|
|
223
|
+
np_offset_values = np.busday_offset(
|
|
224
|
+
dates=dc.to_numpy_date_type(dates_pd[mask_new_holidays]),
|
|
225
|
+
offsets=offset_pd[mask_new_holidays],
|
|
214
226
|
roll=roll,
|
|
215
|
-
holidays=
|
|
227
|
+
holidays=NEW_HOLIDAYS_ARRAY,
|
|
216
228
|
)
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
else:
|
|
220
|
-
return pd.Series(offsetted_dates_np).astype("datetime64[ns]")
|
|
229
|
+
pd_offset_values = pd.to_datetime(np_offset_values).astype("datetime64[ns]")
|
|
230
|
+
result.loc[mask_new_holidays] = pd_offset_values
|
|
221
231
|
|
|
222
|
-
|
|
223
|
-
raise ValueError("Invalid input type for 'dates'.")
|
|
232
|
+
return result
|
|
224
233
|
|
|
225
234
|
|
|
226
235
|
@overload
|
|
227
|
-
def count(start: DateScalar, end: DateScalar) -> int: ...
|
|
228
|
-
|
|
229
|
-
|
|
236
|
+
def count(start: DateScalar, end: DateScalar) -> int | NAType: ...
|
|
230
237
|
@overload
|
|
231
|
-
def count(start: DateArray, end: DateScalar) -> pd.Series: ...
|
|
232
|
-
|
|
233
|
-
|
|
238
|
+
def count(start: DateArray, end: DateScalar | DateArray) -> pd.Series: ...
|
|
234
239
|
@overload
|
|
235
240
|
def count(start: DateScalar, end: DateArray) -> pd.Series: ...
|
|
236
241
|
|
|
237
242
|
|
|
238
|
-
|
|
239
|
-
def count(start: DateArray, end: DateArray) -> pd.Series: ...
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
def count( # noqa
|
|
243
|
+
def count(
|
|
243
244
|
start: DateScalar | DateArray,
|
|
244
245
|
end: DateScalar | DateArray,
|
|
245
|
-
) -> int | pd.Series:
|
|
246
|
+
) -> int | pd.Series | NAType:
|
|
246
247
|
"""
|
|
247
248
|
Counts the number of business days between a `start` date (inclusive) and an `end`
|
|
248
249
|
date (exclusive). The function can handle single dates, arrays of dates and
|
|
@@ -250,8 +251,11 @@ def count( # noqa
|
|
|
250
251
|
on the inputs. It accounts for specified holidays, effectively excluding them from
|
|
251
252
|
the business day count.
|
|
252
253
|
|
|
253
|
-
**Important Note:**
|
|
254
|
-
applies to the calculation.
|
|
254
|
+
**Important Note:** Each date in the `start` input is evaluated individually to
|
|
255
|
+
determine which list of holidays (old or new) applies to the calculation. The
|
|
256
|
+
transition date is 2023-12-26, which means:
|
|
257
|
+
- Dates before 2023-12-26 use the old holiday list.
|
|
258
|
+
- Dates on or after 2023-12-26 use the new holiday list.
|
|
255
259
|
|
|
256
260
|
Args:
|
|
257
261
|
start (DateScalar | DateArray): The start date(s) for counting (inclusive).
|
|
@@ -284,26 +288,25 @@ def count( # noqa
|
|
|
284
288
|
>>> bday.count("15-12-2023", "01-01-2024")
|
|
285
289
|
10
|
|
286
290
|
|
|
287
|
-
|
|
291
|
+
Total business days in January and February since the start of the year
|
|
288
292
|
>>> bday.count(start="01-01-2024", end=["01-02-2024", "01-03-2024"])
|
|
289
293
|
0 22
|
|
290
294
|
1 41
|
|
291
295
|
dtype: Int64
|
|
292
296
|
|
|
293
|
-
|
|
297
|
+
The remaining business days in January and February to the end of the year
|
|
294
298
|
>>> bday.count(["01-01-2024", "01-02-2024"], "01-01-2025")
|
|
295
299
|
0 253
|
|
296
300
|
1 231
|
|
297
301
|
dtype: Int64
|
|
298
302
|
|
|
299
|
-
|
|
303
|
+
The total business days in January and February of 2024
|
|
300
304
|
>>> bday.count(["01-01-2024", "01-02-2024"], ["01-02-2024", "01-03-2024"])
|
|
301
305
|
0 22
|
|
302
306
|
1 19
|
|
303
307
|
dtype: Int64
|
|
304
308
|
|
|
305
309
|
Null values are propagated
|
|
306
|
-
|
|
307
310
|
>>> bday.count(pd.NaT, "01-01-2024") # NaT start
|
|
308
311
|
<NA>
|
|
309
312
|
|
|
@@ -316,7 +319,6 @@ def count( # noqa
|
|
|
316
319
|
dtype: Int64
|
|
317
320
|
|
|
318
321
|
Original pandas index is preserved
|
|
319
|
-
|
|
320
322
|
>>> start_dates = pd.Series(
|
|
321
323
|
... ["01-01-2024", "01-02-2024", "01-03-2024"],
|
|
322
324
|
... index=["a", "b", "c"],
|
|
@@ -333,68 +335,61 @@ def count( # noqa
|
|
|
333
335
|
|
|
334
336
|
# 1. VALIDAÇÃO ESTRUTURAL
|
|
335
337
|
if isinstance(start_pd, pd.Series) and isinstance(end_pd, pd.Series):
|
|
336
|
-
if len(start_pd) != len(end_pd):
|
|
337
|
-
raise ValueError("Input Series must have the same length.")
|
|
338
338
|
if not start_pd.index.equals(end_pd.index):
|
|
339
339
|
raise ValueError("Input dates have different indices!")
|
|
340
340
|
|
|
341
341
|
# 2. LÓGICA PRINCIPAL
|
|
342
|
-
is_scalar_input = not (
|
|
343
|
-
isinstance(start_pd, pd.Series) or isinstance(end_pd, pd.Series)
|
|
344
|
-
)
|
|
345
342
|
|
|
346
343
|
# --- CASO 1: AMBAS AS ENTRADAS SÃO ESCALARES ---
|
|
347
|
-
if
|
|
344
|
+
if not isinstance(start_pd, pd.Series) and not isinstance(end_pd, pd.Series):
|
|
348
345
|
if pd.isna(start_pd) or pd.isna(end_pd):
|
|
349
346
|
return pd.NA
|
|
350
347
|
|
|
351
|
-
holidays = br_holidays.get_holiday_array(start_pd)
|
|
352
348
|
result = np.busday_count(
|
|
353
349
|
begindates=dc.to_numpy_date_type(start_pd),
|
|
354
350
|
enddates=dc.to_numpy_date_type(end_pd),
|
|
355
|
-
holidays=
|
|
351
|
+
holidays=br_holidays.get_holiday_array(start_pd),
|
|
356
352
|
)
|
|
357
353
|
return int(result)
|
|
358
354
|
|
|
359
355
|
# --- CASO 2: PELO MENOS UMA ENTRADA É UMA SÉRIE ---
|
|
356
|
+
|
|
357
|
+
# Garante que ambas as variáveis sejam Series para alinhamento automático.
|
|
358
|
+
# O Pandas faz o "broadcast" do escalar para o tamanho da Series.
|
|
359
|
+
if isinstance(end_pd, pd.Series):
|
|
360
|
+
start_pd = pd.Series(start_pd, index=end_pd.index)
|
|
360
361
|
else:
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
)
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
enddates=dc.to_numpy_date_type(end_pd[mask_new_holidays]),
|
|
393
|
-
holidays=NEW_HOLIDAYS_ARRAY,
|
|
394
|
-
)
|
|
395
|
-
|
|
396
|
-
# As linhas onde not_null_mask era False já contêm o valor <NA> default.
|
|
397
|
-
return result
|
|
362
|
+
assert isinstance(start_pd, pd.Series) # Linter satisfaction
|
|
363
|
+
end_pd = pd.Series(end_pd, index=start_pd.index)
|
|
364
|
+
|
|
365
|
+
# Inicializa a série de resultados com o índice correto e tipo que suporta NA.
|
|
366
|
+
# Nulos nas entradas (start_pd ou end_pd) resultarão em NA aqui.
|
|
367
|
+
result = pd.Series(index=start_pd.index, dtype="Int64")
|
|
368
|
+
|
|
369
|
+
# Cria máscaras para linhas não-nulas, divididas pelo calendário de feriados.
|
|
370
|
+
# A lógica de feriados depende APENAS da data de início.
|
|
371
|
+
not_null_mask = start_pd.notna() & end_pd.notna()
|
|
372
|
+
mask_old_holidays = not_null_mask & (start_pd < br_holidays.TRANSITION_DATE)
|
|
373
|
+
mask_new_holidays = not_null_mask & (start_pd >= br_holidays.TRANSITION_DATE)
|
|
374
|
+
|
|
375
|
+
# Calcula e atribui os resultados para o subconjunto "OLD"
|
|
376
|
+
if mask_old_holidays.any():
|
|
377
|
+
result.loc[mask_old_holidays] = np.busday_count(
|
|
378
|
+
begindates=dc.to_numpy_date_type(start_pd[mask_old_holidays]),
|
|
379
|
+
enddates=dc.to_numpy_date_type(end_pd[mask_old_holidays]),
|
|
380
|
+
holidays=OLD_HOLIDAYS_ARRAY,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
# Calcula e atribui os resultados para o subconjunto "NEW"
|
|
384
|
+
if mask_new_holidays.any():
|
|
385
|
+
result.loc[mask_new_holidays] = np.busday_count(
|
|
386
|
+
begindates=dc.to_numpy_date_type(start_pd[mask_new_holidays]),
|
|
387
|
+
enddates=dc.to_numpy_date_type(end_pd[mask_new_holidays]),
|
|
388
|
+
holidays=NEW_HOLIDAYS_ARRAY,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
# As linhas onde not_null_mask era False já contêm o valor <NA> default.
|
|
392
|
+
return result
|
|
398
393
|
|
|
399
394
|
|
|
400
395
|
def generate(
|
|
@@ -514,4 +509,8 @@ def last_business_day() -> pd.Timestamp:
|
|
|
514
509
|
"""
|
|
515
510
|
# Get the current date in Brazil without timezone information
|
|
516
511
|
bz_today = pd.Timestamp.now(TIMEZONE_BZ).normalize().tz_localize(None)
|
|
517
|
-
|
|
512
|
+
result = offset(bz_today, 0, roll="backward")
|
|
513
|
+
assert isinstance(result, pd.Timestamp), (
|
|
514
|
+
"Assumption violated: offset did not return a Timestamp for the current date."
|
|
515
|
+
)
|
|
516
|
+
return result
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
|
|
3
|
+
from pyield import anbima, bday
|
|
4
|
+
from pyield.date_converter import DateScalar
|
|
5
|
+
from pyield.tn import ntnf
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def spot_rates(date: DateScalar) -> pd.DataFrame:
|
|
9
|
+
"""
|
|
10
|
+
Create the PRE curve (zero coupon rates) for Brazilian fixed rate bonds.
|
|
11
|
+
|
|
12
|
+
This function combines LTN rates (which are already zero coupon) with
|
|
13
|
+
spot rates derived from NTN-F bonds using the bootstrap method.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
date (DateScalar): The reference date for fetching the data.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
pd.DataFrame: DataFrame with columns "MaturityDate", "BDToMat", and "SpotRate".
|
|
20
|
+
Contains zero coupon rates for all available maturities.
|
|
21
|
+
|
|
22
|
+
Raises:
|
|
23
|
+
ValueError: If any maturity date cannot be processed or business days cannot be
|
|
24
|
+
calculated.
|
|
25
|
+
|
|
26
|
+
Examples:
|
|
27
|
+
>>> from pyield import pre
|
|
28
|
+
>>> pre.spot_rates("18-06-2025")
|
|
29
|
+
MaturityDate BDToMat SpotRate
|
|
30
|
+
0 2025-07-01 8 0.14835
|
|
31
|
+
1 2025-10-01 74 0.147463
|
|
32
|
+
2 2026-01-01 138 0.147752
|
|
33
|
+
3 2026-04-01 199 0.147947
|
|
34
|
+
4 2026-07-01 260 0.147069
|
|
35
|
+
5 2026-10-01 325 0.144733
|
|
36
|
+
6 2027-01-01 387 0.142496
|
|
37
|
+
7 2027-04-01 447 0.140924
|
|
38
|
+
8 2027-07-01 510 0.139024
|
|
39
|
+
9 2028-01-01 638 0.136595
|
|
40
|
+
10 2028-07-01 762 0.135664
|
|
41
|
+
11 2029-01-01 886 0.136484
|
|
42
|
+
12 2030-01-01 1135 0.137279
|
|
43
|
+
13 2031-01-01 1387 0.138154
|
|
44
|
+
14 2032-01-01 1639 0.13876
|
|
45
|
+
15 2033-01-01 1891 0.1393
|
|
46
|
+
16 2035-01-01 2390 0.141068
|
|
47
|
+
"""
|
|
48
|
+
# Fetch LTN data (zero coupon bonds)
|
|
49
|
+
df_ltn = anbima.tpf_data(date, "LTN")
|
|
50
|
+
|
|
51
|
+
# Fetch NTN-F data (coupon bonds)
|
|
52
|
+
df_ntnf = anbima.tpf_data(date, "NTN-F")
|
|
53
|
+
|
|
54
|
+
# Check if we have data for both bond types
|
|
55
|
+
if df_ltn.empty and df_ntnf.empty:
|
|
56
|
+
return pd.DataFrame(columns=["MaturityDate", "BDToMat", "SpotRate"])
|
|
57
|
+
|
|
58
|
+
# If we only have LTN data, return it directly
|
|
59
|
+
if df_ntnf.empty:
|
|
60
|
+
pass
|
|
61
|
+
# return _process_ltn_only(date, df_ltn)
|
|
62
|
+
|
|
63
|
+
# If we only have NTN-F data, we can't bootstrap without LTN rates
|
|
64
|
+
if df_ltn.empty:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"Cannot construct PRE curve without LTN rates for bootstrapping"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# Use the existing spot_rates function to calculate zero coupon rates
|
|
70
|
+
df_spots = ntnf.spot_rates(
|
|
71
|
+
settlement=date,
|
|
72
|
+
ltn_maturities=df_ltn["MaturityDate"],
|
|
73
|
+
ltn_rates=df_ltn["IndicativeRate"],
|
|
74
|
+
ntnf_maturities=df_ntnf["MaturityDate"],
|
|
75
|
+
ntnf_rates=df_ntnf["IndicativeRate"],
|
|
76
|
+
show_coupons=False,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# Find LTN maturities that are not in the NTN-F result
|
|
80
|
+
ltn_mask = ~df_ltn["MaturityDate"].isin(df_spots["MaturityDate"])
|
|
81
|
+
ltn_not_in_ntnf = df_ltn.loc[
|
|
82
|
+
ltn_mask
|
|
83
|
+
].copy() # Use .loc and .copy() to avoid warning
|
|
84
|
+
|
|
85
|
+
if not ltn_not_in_ntnf.empty:
|
|
86
|
+
# Process additional LTN maturities
|
|
87
|
+
ltn_subset = _process_additional_ltn(date, ltn_not_in_ntnf)
|
|
88
|
+
|
|
89
|
+
# Ensure consistent data types
|
|
90
|
+
ltn_subset["BDToMat"] = ltn_subset["BDToMat"].astype("int64")
|
|
91
|
+
df_spots["BDToMat"] = df_spots["BDToMat"].astype("int64")
|
|
92
|
+
|
|
93
|
+
# Combine LTN and NTN-F derived spot rates
|
|
94
|
+
df_combined = pd.concat([df_spots, ltn_subset], ignore_index=True)
|
|
95
|
+
else:
|
|
96
|
+
df_combined = df_spots.copy()
|
|
97
|
+
df_combined["BDToMat"] = df_combined["BDToMat"].astype("int64")
|
|
98
|
+
|
|
99
|
+
# Final validation - ensure no NaN values in the result
|
|
100
|
+
_validate_final_result(df_combined)
|
|
101
|
+
|
|
102
|
+
# Sort by maturity date and return
|
|
103
|
+
return df_combined.sort_values("MaturityDate").reset_index(drop=True)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _process_additional_ltn(
|
|
107
|
+
date: DateScalar, ltn_not_in_ntnf: pd.DataFrame
|
|
108
|
+
) -> pd.DataFrame:
|
|
109
|
+
"""Process additional LTN maturities not covered by NTN-F bootstrap."""
|
|
110
|
+
# Validate and calculate business days
|
|
111
|
+
bdays_list = []
|
|
112
|
+
for idx, maturity in enumerate(ltn_not_in_ntnf["MaturityDate"]):
|
|
113
|
+
if pd.isna(maturity):
|
|
114
|
+
raise ValueError(
|
|
115
|
+
f"Additional LTN row {idx} has invalid (NaT) maturity date"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
bdays = bday.count(date, maturity)
|
|
120
|
+
if pd.isna(bdays):
|
|
121
|
+
raise ValueError(
|
|
122
|
+
f"Business days calculation returned NaN for additional LTN"
|
|
123
|
+
f"maturity {maturity}"
|
|
124
|
+
)
|
|
125
|
+
bdays_list.append(bdays)
|
|
126
|
+
except Exception as e:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
"Failed to calculate business days for additional LTN"
|
|
129
|
+
f" maturity {maturity}: {str(e)}"
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# Create result DataFrame (avoiding the warning by working with a proper copy)
|
|
133
|
+
result = ltn_not_in_ntnf[["MaturityDate", "IndicativeRate"]].copy()
|
|
134
|
+
result["BDToMat"] = bdays_list
|
|
135
|
+
result = result.rename(columns={"IndicativeRate": "SpotRate"})
|
|
136
|
+
|
|
137
|
+
return result[["MaturityDate", "BDToMat", "SpotRate"]]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _validate_final_result(df_combined: pd.DataFrame) -> None:
|
|
141
|
+
"""Validate the final combined DataFrame."""
|
|
142
|
+
if df_combined["BDToMat"].isna().any():
|
|
143
|
+
raise ValueError("Final result contains NaN values in BDToMat column")
|
|
144
|
+
|
|
145
|
+
if df_combined["SpotRate"].isna().any():
|
|
146
|
+
raise ValueError("Final result contains NaN values in SpotRate column")
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.35.8"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|