PYield 0.25.6__tar.gz → 0.26.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.25.6 → pyield-0.26.0}/PKG-INFO +1 -1
- pyield-0.26.0/pyield/__about__.py +1 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/__init__.py +1 -1
- {pyield-0.25.6 → pyield-0.26.0}/pyield/b3_futures/historical.py +4 -7
- {pyield-0.25.6 → pyield-0.26.0}/pyield/b3_futures/intraday.py +3 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/b3_futures/xml.py +1 -1
- {pyield-0.25.6 → pyield-0.26.0}/pyield/bday.py +11 -2
- {pyield-0.25.6 → pyield-0.26.0}/pyield/di.py +67 -70
- {pyield-0.25.6 → pyield-0.26.0}/pyield/interpolator.py +28 -21
- {pyield-0.25.6/pyield/bonds → pyield-0.26.0/pyield/tpf}/lft.py +3 -3
- {pyield-0.25.6/pyield/bonds → pyield-0.26.0/pyield/tpf}/ltn.py +5 -5
- {pyield-0.25.6/pyield/bonds → pyield-0.26.0/pyield/tpf}/ntnb.py +1 -1
- {pyield-0.25.6/pyield/bonds → pyield-0.26.0/pyield/tpf}/ntnf.py +9 -9
- pyield-0.25.6/pyield/bonds/bond_tools.py → pyield-0.26.0/pyield/tpf/tools.py +1 -1
- {pyield-0.25.6 → pyield-0.26.0}/pyproject.toml +0 -7
- pyield-0.25.6/pyield/__about__.py +0 -1
- {pyield-0.25.6 → pyield-0.26.0}/.gitignore +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/LICENSE +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/README.md +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/anbima.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/b3_futures/__init__.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/b3_futures/common.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/conftest.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/data_cache.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/date_converter.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/holidays/__init__.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/holidays/br_holidays_new.txt +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/holidays/br_holidays_old.txt +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/holidays/brholidays.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/indicators.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/projections.py +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/py.typed +0 -0
- {pyield-0.25.6 → pyield-0.26.0}/pyield/tools.py +0 -0
- {pyield-0.25.6/pyield/bonds → pyield-0.26.0/pyield/tpf}/__init__.py +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.26.0"
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
from pyield import anbima, bday, di, tools
|
|
2
2
|
from pyield.__about__ import __version__
|
|
3
3
|
from pyield.b3_futures import futures
|
|
4
|
-
from pyield.bonds import lft, ltn, ntnb, ntnf
|
|
5
4
|
from pyield.di import DIFutures
|
|
6
5
|
from pyield.indicators import indicator
|
|
7
6
|
from pyield.interpolator import Interpolator
|
|
8
7
|
from pyield.projections import projection
|
|
8
|
+
from pyield.tpf import lft, ltn, ntnb, ntnf
|
|
9
9
|
|
|
10
10
|
__all__ = [
|
|
11
11
|
"__version__",
|
|
@@ -135,18 +135,15 @@ def _fetch_raw_df(contract_code: str, trade_date: pd.Timestamp) -> pd.DataFrame:
|
|
|
135
135
|
dtype_backend="numpy_nullable",
|
|
136
136
|
)[0]
|
|
137
137
|
|
|
138
|
-
# Remove rows with all NaN values
|
|
139
|
-
df = df.dropna(how="all")
|
|
140
|
-
|
|
141
|
-
# Remove columns with all NaN values
|
|
142
|
-
df = df.dropna(axis=1, how="all")
|
|
138
|
+
# Remove rows and columns with all NaN values
|
|
139
|
+
df = df.dropna(axis=0, how="all").dropna(axis=1, how="all").copy()
|
|
143
140
|
|
|
144
141
|
# Force "VAR. PTOS." to be string, since it can also be read as float
|
|
145
|
-
df["VAR. PTOS."] = df["VAR. PTOS."].astype(
|
|
142
|
+
df["VAR. PTOS."] = df["VAR. PTOS."].astype("string")
|
|
146
143
|
|
|
147
144
|
# Force "AJUSTE CORRIG. (4)" to be float, since it can be also read as int
|
|
148
145
|
if "AJUSTE CORRIG. (4)" in df.columns:
|
|
149
|
-
df["AJUSTE CORRIG. (4)"] = df["AJUSTE CORRIG. (4)"].astype(
|
|
146
|
+
df["AJUSTE CORRIG. (4)"] = df["AJUSTE CORRIG. (4)"].astype("Float64")
|
|
150
147
|
|
|
151
148
|
return df
|
|
152
149
|
|
|
@@ -113,6 +113,9 @@ def _process_df(raw_df: pd.DataFrame) -> pd.DataFrame:
|
|
|
113
113
|
# Convert to nullable integer, since it is the default type in the library
|
|
114
114
|
df["DaysToExp"] = df["DaysToExp"].astype("Int64")
|
|
115
115
|
|
|
116
|
+
# The "FinancialVolume" column is in BRL, so we need to round it to cents
|
|
117
|
+
df["FinancialVolume"] = df["FinancialVolume"].round(2)
|
|
118
|
+
|
|
116
119
|
# Remove percentage in all rate columns
|
|
117
120
|
rate_cols = [col for col in df.columns if "Rate" in col]
|
|
118
121
|
df[rate_cols] = df[rate_cols].div(100).round(5)
|
|
@@ -196,7 +196,7 @@ def _process_df(df_raw: pd.DataFrame) -> pd.DataFrame:
|
|
|
196
196
|
|
|
197
197
|
df["DaysToExp"] = (df["ExpirationDate"] - df["TradeDate"]).dt.days
|
|
198
198
|
# Convert to nullable integer, since it is the default type in the library
|
|
199
|
-
df["DaysToExp"] = df["DaysToExp"].astype(
|
|
199
|
+
df["DaysToExp"] = df["DaysToExp"].astype("Int64")
|
|
200
200
|
# Remove expired contracts
|
|
201
201
|
df.query("DaysToExp > 0", inplace=True)
|
|
202
202
|
|
|
@@ -57,9 +57,12 @@ def offset(
|
|
|
57
57
|
dates. It is a wrapper for `numpy.busday_offset` adapted for Pandas data types and
|
|
58
58
|
brazilian holidays.
|
|
59
59
|
|
|
60
|
+
**Important Note:** The `dates` parameter is used to determine which list of
|
|
61
|
+
holidays applies to the calculation.
|
|
62
|
+
|
|
60
63
|
Args:
|
|
61
64
|
dates (DateScalar | DateArray): The date(s) to offset. Can be a scalar date type
|
|
62
|
-
or a collection of dates.
|
|
65
|
+
or a collection of dates. The holiday list is determined based on this date.
|
|
63
66
|
offset (int | Series | np.ndarray | list[int] | tuple[int], optional):
|
|
64
67
|
The number of business days to offset the dates. Positive for future dates,
|
|
65
68
|
negative for past dates. Zero will return the same date if it's a business
|
|
@@ -217,8 +220,12 @@ def count(
|
|
|
217
220
|
on the inputs. It accounts for specified holidays, effectively excluding them from
|
|
218
221
|
the business day count.
|
|
219
222
|
|
|
223
|
+
**Important Note:** The `start` date is used to determine which list of holidays
|
|
224
|
+
applies to the calculation.
|
|
225
|
+
|
|
220
226
|
Args:
|
|
221
|
-
start (DateScalar | DateArray): The start date(s) for counting.
|
|
227
|
+
start (DateScalar | DateArray): The start date(s) for counting. The holiday list
|
|
228
|
+
is selected based on this date.
|
|
222
229
|
end (DateScalar | DateArray): The end date(s) for counting, which
|
|
223
230
|
is excluded from the count themselves.
|
|
224
231
|
|
|
@@ -233,6 +240,8 @@ def count(
|
|
|
233
240
|
more, for both `start` and `end` parameters.
|
|
234
241
|
- The return type depends on the input types: single dates return an int, while
|
|
235
242
|
arrays of dates return a pd.Series with the count for each date range.
|
|
243
|
+
- The `start` date determines the holiday list, ensuring consistency with the
|
|
244
|
+
applicable calendar at the time.
|
|
236
245
|
- See `numpy.busday_count` documentation for more details on how holidays are
|
|
237
246
|
handled and how business day counts are calculated:
|
|
238
247
|
https://numpy.org/doc/stable/reference/generated/numpy.busday_count.html.
|
|
@@ -17,18 +17,18 @@ class DIFutures:
|
|
|
17
17
|
NTN-F bond maturities.
|
|
18
18
|
|
|
19
19
|
Args:
|
|
20
|
-
|
|
20
|
+
trade_date (DateScalar | None): The trade date to retrieve the
|
|
21
21
|
DI contract data. If None, the latest available historical trade date is
|
|
22
22
|
used.
|
|
23
|
-
month_start (bool): If True, adjusts the
|
|
24
|
-
of the month.
|
|
23
|
+
month_start (bool): If True, adjusts the expirations to the start of the month.
|
|
25
24
|
pre_filter (bool): If True, filters the DI contracts to match only
|
|
26
25
|
expirations with existing prefixed TN bond maturities (LTN and NTN-F).
|
|
27
26
|
all_columns (bool): If True, returns all available columns in the DI dataset.
|
|
27
|
+
If False, only the most common columns are returned.
|
|
28
28
|
|
|
29
29
|
Examples:
|
|
30
30
|
To create a `DIFutures` instance and retrieve data:
|
|
31
|
-
>>> dif = yd.DIFutures(
|
|
31
|
+
>>> dif = yd.DIFutures(trade_date="16-10-2024", month_start=True)
|
|
32
32
|
>>> df = dif.df # Retrieve DI contract dataframe for the specified date
|
|
33
33
|
>>> df.iloc[:5, :5] # Show the first five rows and columns
|
|
34
34
|
TradeDate ExpirationDate TickerSymbol BDaysToExp OpenContracts
|
|
@@ -56,13 +56,13 @@ class DIFutures:
|
|
|
56
56
|
)
|
|
57
57
|
"""
|
|
58
58
|
pd.Series: Sorted series of unique trade dates available in the DI dataset.
|
|
59
|
-
It does not include the
|
|
59
|
+
It does not include the intraday date. It can be used to check for available
|
|
60
60
|
historical data.
|
|
61
61
|
"""
|
|
62
62
|
|
|
63
63
|
def __init__(
|
|
64
64
|
self,
|
|
65
|
-
|
|
65
|
+
trade_date: DateScalar | None = None,
|
|
66
66
|
month_start: bool = False,
|
|
67
67
|
pre_filter: bool = False,
|
|
68
68
|
all_columns: bool = True,
|
|
@@ -77,7 +77,7 @@ class DIFutures:
|
|
|
77
77
|
self._df = pd.DataFrame()
|
|
78
78
|
self._dirty = True # Attribute to track if the df needs updating
|
|
79
79
|
|
|
80
|
-
self.
|
|
80
|
+
self.trade_date = trade_date
|
|
81
81
|
self.month_start = month_start
|
|
82
82
|
self.pre_filter = pre_filter
|
|
83
83
|
self.all_columns = all_columns
|
|
@@ -85,7 +85,7 @@ class DIFutures:
|
|
|
85
85
|
@property
|
|
86
86
|
def df(self) -> pd.DataFrame:
|
|
87
87
|
"""
|
|
88
|
-
|
|
88
|
+
Returns a copy of the DI contract DataFrame for the initialized trade date.
|
|
89
89
|
|
|
90
90
|
If the internal state is marked as 'dirty', the DataFrame will be (re)loaded
|
|
91
91
|
before returning, ensuring that the returned data reflects the latest attribute
|
|
@@ -97,20 +97,21 @@ class DIFutures:
|
|
|
97
97
|
if self._dirty:
|
|
98
98
|
self._df = self._update_df()
|
|
99
99
|
self._dirty = False
|
|
100
|
-
return self._df
|
|
100
|
+
return self._df.copy()
|
|
101
101
|
|
|
102
102
|
def _update_df(self) -> pd.DataFrame:
|
|
103
103
|
"""Retrieve DI contract DataFrame for the initialized trade date."""
|
|
104
|
-
df = (
|
|
105
|
-
get_di_dataset()
|
|
106
|
-
.query("TradeDate in @self._trade_dates")
|
|
107
|
-
.reset_index(drop=True)
|
|
108
|
-
)
|
|
109
|
-
|
|
110
104
|
bz_today = pd.Timestamp.today(tz="America/Sao_Paulo").normalize()
|
|
111
|
-
if bz_today
|
|
112
|
-
|
|
113
|
-
df =
|
|
105
|
+
if bz_today == self.trade_date:
|
|
106
|
+
# Try to get intraday data
|
|
107
|
+
df = b3.futures(contract_code="DI1", trade_date=bz_today)
|
|
108
|
+
else:
|
|
109
|
+
# Get historical data
|
|
110
|
+
df = (
|
|
111
|
+
get_di_dataset()
|
|
112
|
+
.query("TradeDate == @self._trade_date")
|
|
113
|
+
.reset_index(drop=True)
|
|
114
|
+
)
|
|
114
115
|
|
|
115
116
|
if df.empty:
|
|
116
117
|
return pd.DataFrame()
|
|
@@ -122,12 +123,13 @@ class DIFutures:
|
|
|
122
123
|
df_pre = (
|
|
123
124
|
get_anbima_dataset()
|
|
124
125
|
.query("BondType in ['LTN', 'NTN-F']")
|
|
125
|
-
.query("ReferenceDate
|
|
126
|
+
.query("ReferenceDate == @self._trade_date")[
|
|
126
127
|
["ReferenceDate", "MaturityDate"]
|
|
127
128
|
]
|
|
128
129
|
.drop_duplicates()
|
|
129
130
|
.reset_index(drop=True)
|
|
130
131
|
)
|
|
132
|
+
# Force the expiration date to be a business day as DI contracts
|
|
131
133
|
df_pre["MaturityDate"] = bday.offset(df_pre["MaturityDate"], 0)
|
|
132
134
|
df_pre = df_pre.rename(
|
|
133
135
|
columns={
|
|
@@ -146,8 +148,9 @@ class DIFutures:
|
|
|
146
148
|
if not self._all_columns:
|
|
147
149
|
cols = [
|
|
148
150
|
"TradeDate",
|
|
149
|
-
"ExpirationDate",
|
|
150
151
|
"TickerSymbol",
|
|
152
|
+
"ExpirationDate",
|
|
153
|
+
"BDaysToExp",
|
|
151
154
|
"OpenContracts",
|
|
152
155
|
"TradeVolume",
|
|
153
156
|
"DV01",
|
|
@@ -168,19 +171,17 @@ class DIFutures:
|
|
|
168
171
|
@property
|
|
169
172
|
def forwards(self) -> pd.DataFrame:
|
|
170
173
|
"""
|
|
171
|
-
Calculate the DI forward rates for the initialized trade
|
|
174
|
+
Calculate the DI forward rates for the initialized trade date.
|
|
172
175
|
|
|
173
176
|
This property returns a DataFrame with both the SettlementRate and the
|
|
174
|
-
calculated ForwardRate for DI contracts, based on the instance's trade
|
|
177
|
+
calculated ForwardRate for DI contracts, based on the instance's trade date and
|
|
175
178
|
applied filters.
|
|
176
179
|
|
|
177
180
|
Returns:
|
|
178
181
|
pd.DataFrame: A DataFrame containing the following columns:
|
|
179
182
|
- ExpirationDate: The expiration dates of the DI contracts.
|
|
180
|
-
- SettlementRate: The zero rate (interest rate) for each expiration
|
|
181
|
-
|
|
182
|
-
- ForwardRate: The forward rate calculated between successive expiration
|
|
183
|
-
dates.
|
|
183
|
+
- SettlementRate: The zero rate (interest rate) for each expiration.
|
|
184
|
+
- ForwardRate: The fwd rate calculated between successive expirations.
|
|
184
185
|
"""
|
|
185
186
|
df = self.df
|
|
186
187
|
if df.empty:
|
|
@@ -196,25 +197,26 @@ class DIFutures:
|
|
|
196
197
|
|
|
197
198
|
@staticmethod
|
|
198
199
|
def interpolate_rates(
|
|
199
|
-
|
|
200
|
-
|
|
200
|
+
trade_dates: DateScalar | DateArray,
|
|
201
|
+
expirations: DateScalar | DateArray,
|
|
201
202
|
extrapolate: bool = True,
|
|
202
203
|
) -> pd.Series:
|
|
203
204
|
"""
|
|
204
|
-
Interpolates DI rates for specified
|
|
205
|
+
Interpolates DI rates for specified trade dates and maturities. The method
|
|
206
|
+
is recomended to be used in datasets calculations with multiple dates.
|
|
205
207
|
|
|
206
|
-
This method calculates interpolated DI rates for a given set of
|
|
208
|
+
This method calculates interpolated DI rates for a given set of trade
|
|
207
209
|
dates and maturities using a flat-forward interpolation method. If no DI
|
|
208
210
|
rates are available for a reference date, the interpolated rate is set to NaN.
|
|
209
211
|
|
|
210
|
-
If
|
|
212
|
+
If trade_dates is provided as a scalar and expirations as an array, the
|
|
211
213
|
method assumes the scalar value is the same for all maturities. The same logic
|
|
212
|
-
applies when the maturities are scalar and the
|
|
214
|
+
applies when the maturities are scalar and the trade dates are an array.
|
|
213
215
|
|
|
214
216
|
Args:
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
217
|
+
trade_dates (DateScalar | DateArray): The trade dates for the rates.
|
|
218
|
+
expirations (DateScalar | DateArray): The expirations corresponding to the
|
|
219
|
+
trade dates.
|
|
218
220
|
extrapolate (bool): Whether to allow extrapolation beyond known DI rates.
|
|
219
221
|
|
|
220
222
|
Returns:
|
|
@@ -224,29 +226,29 @@ class DIFutures:
|
|
|
224
226
|
ValueError: If `reference_dates` and `maturities` have different lengths.
|
|
225
227
|
"""
|
|
226
228
|
# Convert input dates to a consistent format
|
|
227
|
-
|
|
228
|
-
|
|
229
|
+
trade_dates = dc.convert_input_dates(trade_dates)
|
|
230
|
+
expirations = dc.convert_input_dates(expirations)
|
|
229
231
|
|
|
230
232
|
# Ensure the lengths of input arrays are consistent
|
|
231
|
-
match (
|
|
233
|
+
match (trade_dates, expirations):
|
|
232
234
|
case pd.Timestamp(), pd.Series():
|
|
233
|
-
dfi = pd.DataFrame({"mat":
|
|
234
|
-
dfi["
|
|
235
|
+
dfi = pd.DataFrame({"mat": expirations})
|
|
236
|
+
dfi["tdate"] = trade_dates
|
|
235
237
|
|
|
236
238
|
case pd.Series(), pd.Timestamp():
|
|
237
|
-
dfi = pd.DataFrame({"
|
|
238
|
-
dfi["mat"] =
|
|
239
|
+
dfi = pd.DataFrame({"tdate": trade_dates})
|
|
240
|
+
dfi["mat"] = expirations
|
|
239
241
|
|
|
240
242
|
case pd.Series(), pd.Series():
|
|
241
|
-
if len(
|
|
243
|
+
if len(trade_dates) != len(expirations):
|
|
242
244
|
raise ValueError("Args. should have the same length.")
|
|
243
|
-
dfi = pd.DataFrame({"
|
|
245
|
+
dfi = pd.DataFrame({"tdate": trade_dates, "mat": expirations})
|
|
244
246
|
|
|
245
247
|
case pd.Timestamp(), pd.Timestamp():
|
|
246
|
-
dfi = pd.DataFrame({"
|
|
248
|
+
dfi = pd.DataFrame({"tdate": [trade_dates], "mat": [expirations]})
|
|
247
249
|
|
|
248
250
|
# Compute business days between reference dates and maturities
|
|
249
|
-
dfi["bdays"] = bday.count(dfi["
|
|
251
|
+
dfi["bdays"] = bday.count(dfi["tdate"], dfi["mat"])
|
|
250
252
|
|
|
251
253
|
# Initialize the interpolated rate column with NaN
|
|
252
254
|
dfi["irate"] = pd.NA
|
|
@@ -255,18 +257,18 @@ class DIFutures:
|
|
|
255
257
|
# Load DI rates dataset filtered by the provided reference dates
|
|
256
258
|
dfr = (
|
|
257
259
|
get_di_dataset()
|
|
258
|
-
.query("TradeDate in @dfi['
|
|
260
|
+
.query("TradeDate in @dfi['tdate'].unique()")
|
|
259
261
|
.reset_index(drop=True)
|
|
260
262
|
)
|
|
261
263
|
|
|
262
264
|
# Return an empty DataFrame if no rates are found
|
|
263
265
|
if dfr.empty:
|
|
264
|
-
return pd.
|
|
266
|
+
return pd.Series()
|
|
265
267
|
|
|
266
268
|
# Iterate over each unique reference date
|
|
267
|
-
for date in dfi["
|
|
269
|
+
for date in dfi["tdate"].unique():
|
|
268
270
|
# Filter DI rates for the current reference date
|
|
269
|
-
dfr_subset = dfr.query("TradeDate == @date").
|
|
271
|
+
dfr_subset = dfr.query("TradeDate == @date").reset_index(drop=True)
|
|
270
272
|
|
|
271
273
|
# Skip processing if no rates are available for the current date
|
|
272
274
|
if dfr_subset.empty:
|
|
@@ -281,7 +283,7 @@ class DIFutures:
|
|
|
281
283
|
)
|
|
282
284
|
|
|
283
285
|
# Apply interpolation to rows matching the current reference date
|
|
284
|
-
mask = dfi["
|
|
286
|
+
mask: pd.Series = dfi["tdate"] == date
|
|
285
287
|
dfi.loc[mask, "irate"] = dfi.loc[mask, "bdays"].apply(interp)
|
|
286
288
|
|
|
287
289
|
# Return the Series with interpolated rates
|
|
@@ -307,7 +309,7 @@ class DIFutures:
|
|
|
307
309
|
|
|
308
310
|
if not interpolate and extrapolate:
|
|
309
311
|
raise ValueError("Extrapolation is not allowed without interpolation.")
|
|
310
|
-
|
|
312
|
+
# Get the DI contract DataFrame
|
|
311
313
|
df = self.df
|
|
312
314
|
|
|
313
315
|
if df.empty:
|
|
@@ -324,40 +326,35 @@ class DIFutures:
|
|
|
324
326
|
if not interpolate:
|
|
325
327
|
return float("NaN")
|
|
326
328
|
|
|
327
|
-
|
|
329
|
+
ff_interp = interpolator.Interpolator(
|
|
328
330
|
method="flat_forward",
|
|
329
|
-
known_bdays=
|
|
331
|
+
known_bdays=df["BDaysToExp"],
|
|
330
332
|
known_rates=df["SettlementRate"],
|
|
331
333
|
extrapolate=extrapolate,
|
|
332
334
|
)
|
|
333
|
-
|
|
334
|
-
return
|
|
335
|
+
bd = bday.count(self._trade_date, expiration)
|
|
336
|
+
return ff_interp(bd)
|
|
335
337
|
|
|
336
338
|
@property
|
|
337
|
-
def
|
|
339
|
+
def trade_date(self) -> pd.Timestamp:
|
|
338
340
|
"""
|
|
339
|
-
The trade
|
|
341
|
+
The trade date to retrieve the DI contract data.
|
|
340
342
|
|
|
341
343
|
This property can be both read and set. When setting a value, it automatically
|
|
342
344
|
converts the input date format to a `pd.Timestamp`.
|
|
343
345
|
|
|
344
346
|
Returns:
|
|
345
|
-
|
|
347
|
+
pd.Timestamp: The trade date set for this instance.
|
|
346
348
|
"""
|
|
347
349
|
|
|
348
|
-
return self.
|
|
350
|
+
return self._trade_date
|
|
349
351
|
|
|
350
|
-
@
|
|
351
|
-
def
|
|
352
|
-
if value
|
|
353
|
-
|
|
352
|
+
@trade_date.setter
|
|
353
|
+
def trade_date(self, value: DateScalar | None):
|
|
354
|
+
if value:
|
|
355
|
+
self._trade_date = dc.convert_input_dates(value)
|
|
354
356
|
else:
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
if isinstance(trade_dates, pd.Timestamp):
|
|
358
|
-
self._trade_dates = [trade_dates]
|
|
359
|
-
elif isinstance(trade_dates, pd.Series):
|
|
360
|
-
self._trade_dates = trade_dates.drop_duplicates().sort_values().to_list()
|
|
357
|
+
self._trade_date = self.historical_trade_dates.max()
|
|
361
358
|
|
|
362
359
|
self._dirty = True
|
|
363
360
|
|
|
@@ -56,18 +56,13 @@ class Interpolator:
|
|
|
56
56
|
.sort_values("bday", ignore_index=True)
|
|
57
57
|
)
|
|
58
58
|
self._df = df
|
|
59
|
-
self._method = method
|
|
59
|
+
self._method = str(method)
|
|
60
60
|
self._known_bdays = tuple(df["bday"])
|
|
61
61
|
self._known_rates = tuple(df["rate"])
|
|
62
62
|
self._extrapolate = bool(extrapolate)
|
|
63
63
|
|
|
64
|
-
def _flat_forward(self, bday: int) -> float:
|
|
64
|
+
def _flat_forward(self, bday: int, i: int) -> float:
|
|
65
65
|
"""Performs the interest rate interpolation using the flat forward method."""
|
|
66
|
-
|
|
67
|
-
# Find i such that known_bdays[i-1] < bday < known_bdays[i]
|
|
68
|
-
i = bisect.bisect_left(self._known_bdays, bday)
|
|
69
|
-
|
|
70
|
-
# Get previous and next known rates and business days
|
|
71
66
|
prev_rate = self._known_rates[i - 1]
|
|
72
67
|
prev_bday = self._known_bdays[i - 1]
|
|
73
68
|
next_rate = self._known_rates[i]
|
|
@@ -92,20 +87,32 @@ class Interpolator:
|
|
|
92
87
|
float: The interest rate interpolated by the specified method for the given
|
|
93
88
|
number of business days.
|
|
94
89
|
"""
|
|
95
|
-
#
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
elif
|
|
106
|
-
return float(
|
|
107
|
-
|
|
108
|
-
|
|
90
|
+
# Create local references to facilitate code readability
|
|
91
|
+
known_bdays = self._known_bdays
|
|
92
|
+
known_rates = self._known_rates
|
|
93
|
+
extrapolate = self._extrapolate
|
|
94
|
+
method = self._method
|
|
95
|
+
|
|
96
|
+
# Lower bound extrapolation is always the first known rate
|
|
97
|
+
if bday < known_bdays[0]:
|
|
98
|
+
return known_rates[0]
|
|
99
|
+
# Upper bound extrapolation depends on the extrapolate flag
|
|
100
|
+
elif bday > known_bdays[-1]:
|
|
101
|
+
return known_rates[-1] if extrapolate else float("NaN")
|
|
102
|
+
|
|
103
|
+
# Early return for linear interpolation
|
|
104
|
+
if method == "linear":
|
|
105
|
+
return float(np.interp(bday, known_bdays, known_rates))
|
|
106
|
+
|
|
107
|
+
# Find i such that known_bdays[i-1] < bday < known_bdays[i]
|
|
108
|
+
idx = bisect.bisect_left(known_bdays, bday)
|
|
109
|
+
|
|
110
|
+
# Check if the interpolation point is known
|
|
111
|
+
if idx < len(known_bdays) and known_bdays[idx] == bday:
|
|
112
|
+
return known_rates[idx]
|
|
113
|
+
|
|
114
|
+
# Perform flat forward interpolation
|
|
115
|
+
return self._flat_forward(bday, idx)
|
|
109
116
|
|
|
110
117
|
def __call__(self, bday: int) -> float:
|
|
111
118
|
"""
|
|
@@ -2,8 +2,8 @@ import pandas as pd
|
|
|
2
2
|
|
|
3
3
|
from pyield import anbima, bday
|
|
4
4
|
from pyield import date_converter as dc
|
|
5
|
-
from pyield.bonds import bond_tools as bt
|
|
6
5
|
from pyield.date_converter import DateScalar
|
|
6
|
+
from pyield.tpf import tools as tt
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
def rates(reference_date: DateScalar) -> pd.DataFrame:
|
|
@@ -69,11 +69,11 @@ def quotation(
|
|
|
69
69
|
bdays = bday.count(settlement, maturity)
|
|
70
70
|
|
|
71
71
|
# Calculate the number of periods truncated as per Anbima rules
|
|
72
|
-
num_of_years =
|
|
72
|
+
num_of_years = tt.truncate(bdays / 252, 14)
|
|
73
73
|
|
|
74
74
|
discount_factor = 1 / (1 + rate) ** num_of_years
|
|
75
75
|
|
|
76
|
-
return
|
|
76
|
+
return tt.truncate(100 * discount_factor, 4)
|
|
77
77
|
|
|
78
78
|
|
|
79
79
|
def premium(lft_rate: float, selic_over: float) -> float:
|
|
@@ -2,8 +2,8 @@ import pandas as pd
|
|
|
2
2
|
|
|
3
3
|
from pyield import anbima, bday, di
|
|
4
4
|
from pyield import date_converter as dc
|
|
5
|
-
from pyield.bonds import bond_tools as bt
|
|
6
5
|
from pyield.date_converter import DateScalar
|
|
6
|
+
from pyield.tpf import tools as tt
|
|
7
7
|
|
|
8
8
|
FACE_VALUE = 1000
|
|
9
9
|
|
|
@@ -111,12 +111,12 @@ def price(
|
|
|
111
111
|
bdays = bday.count(settlement, maturity)
|
|
112
112
|
|
|
113
113
|
# Calculate the number of periods truncated as per Anbima rule
|
|
114
|
-
num_of_years =
|
|
114
|
+
num_of_years = tt.truncate(bdays / 252, 14)
|
|
115
115
|
|
|
116
116
|
discount_factor = (1 + rate) ** num_of_years
|
|
117
117
|
|
|
118
118
|
# Truncate the price to 6 decimal places as per Anbima rules
|
|
119
|
-
return
|
|
119
|
+
return tt.truncate(FACE_VALUE / discount_factor, 6)
|
|
120
120
|
|
|
121
121
|
|
|
122
122
|
def di_spreads(reference_date: DateScalar) -> pd.DataFrame:
|
|
@@ -151,7 +151,7 @@ def di_spreads(reference_date: DateScalar) -> pd.DataFrame:
|
|
|
151
151
|
12 2030-01-01 14.96
|
|
152
152
|
"""
|
|
153
153
|
# Fetch DI Spreads for the reference date
|
|
154
|
-
df =
|
|
154
|
+
df = tt.pre_spreads(reference_date)
|
|
155
155
|
df.query("BondType == 'LTN'", inplace=True)
|
|
156
156
|
df.sort_values(["MaturityDate"], ignore_index=True, inplace=True)
|
|
157
157
|
return df[["MaturityDate", "DISpread"]]
|
|
@@ -219,7 +219,7 @@ def historical_premium(
|
|
|
219
219
|
ltn_rate = float(ltn_rates.iloc[0])
|
|
220
220
|
|
|
221
221
|
# Retrieve DI rate for the reference date and maturity
|
|
222
|
-
dif = di.DIFutures(
|
|
222
|
+
dif = di.DIFutures(trade_date=reference_date)
|
|
223
223
|
di_rate = dif.rate(expiration=maturity, interpolate=True, extrapolate=False)
|
|
224
224
|
if pd.isnull(di_rate): # Check if the DI rate is NaN
|
|
225
225
|
return float("NaN")
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
import pandas as pd
|
|
3
3
|
|
|
4
|
-
import pyield.bonds.bond_tools as bt
|
|
5
4
|
import pyield.date_converter as dc
|
|
6
5
|
import pyield.interpolator as ip
|
|
6
|
+
import pyield.tpf.tools as bt
|
|
7
7
|
from pyield import anbima, bday
|
|
8
8
|
from pyield.date_converter import DateScalar
|
|
9
9
|
|
|
@@ -6,8 +6,8 @@ import pandas as pd
|
|
|
6
6
|
from pyield import anbima, bday, data_cache, di
|
|
7
7
|
from pyield import date_converter as dc
|
|
8
8
|
from pyield import interpolator as ip
|
|
9
|
-
from pyield.bonds import bond_tools as bt
|
|
10
9
|
from pyield.date_converter import DateScalar
|
|
10
|
+
from pyield.tpf import tools as tt
|
|
11
11
|
|
|
12
12
|
"""
|
|
13
13
|
Constants calculated as per Anbima Rules
|
|
@@ -225,12 +225,12 @@ def price(
|
|
|
225
225
|
cf_df = cash_flows(settlement, maturity)
|
|
226
226
|
cf_values = cf_df["CashFlow"]
|
|
227
227
|
bdays = bday.count(settlement, cf_df["PaymentDate"])
|
|
228
|
-
byears =
|
|
228
|
+
byears = tt.truncate(bdays / 252, 14)
|
|
229
229
|
discount_factors = (1 + rate) ** byears
|
|
230
230
|
# Calculate the present value of each cash flow (DCF) rounded as per Anbima rules
|
|
231
231
|
dcf = (cf_values / discount_factors).round(9)
|
|
232
232
|
# Return the sum of the discounted cash flows truncated as per Anbima rules
|
|
233
|
-
return
|
|
233
|
+
return tt.truncate(dcf.sum(), 6)
|
|
234
234
|
|
|
235
235
|
|
|
236
236
|
def spot_rates( # noqa
|
|
@@ -320,7 +320,7 @@ def spot_rates( # noqa
|
|
|
320
320
|
# Calculate the present value of the coupon payments
|
|
321
321
|
cf_dates = payment_dates(settlement, row["MaturityDate"])[:-1] # noqa
|
|
322
322
|
cf_df = df.query("MaturityDate in @cf_dates").reset_index(drop=True)
|
|
323
|
-
cf_present_value =
|
|
323
|
+
cf_present_value = tt.calculate_present_value(
|
|
324
324
|
cash_flows=cf_df["Coupon"],
|
|
325
325
|
rates=cf_df["SpotRate"],
|
|
326
326
|
periods=cf_df["BDToMat"] / 252,
|
|
@@ -364,7 +364,7 @@ def di_spreads(reference_date: DateScalar) -> pd.DataFrame:
|
|
|
364
364
|
|
|
365
365
|
"""
|
|
366
366
|
# Fetch DI Spreads for the reference date
|
|
367
|
-
df =
|
|
367
|
+
df = tt.pre_spreads(reference_date)
|
|
368
368
|
df = (
|
|
369
369
|
df.query("BondType == 'NTN-F'")
|
|
370
370
|
.sort_values(["MaturityDate"])
|
|
@@ -564,7 +564,7 @@ def premium(
|
|
|
564
564
|
df["DIRate"] = df["BDToMat"].apply(ff_interpolator)
|
|
565
565
|
|
|
566
566
|
# Calculate the present value of the cash flows using the DI rate
|
|
567
|
-
bond_price =
|
|
567
|
+
bond_price = tt.calculate_present_value(
|
|
568
568
|
cash_flows=df["CashFlow"],
|
|
569
569
|
rates=df["DIRate"],
|
|
570
570
|
periods=df["BDToMat"] / 252,
|
|
@@ -607,13 +607,13 @@ def historical_premium(
|
|
|
607
607
|
|
|
608
608
|
dif = di.DIFutures() # Instantiate the DI Futures class
|
|
609
609
|
df["DIRate"] = dif.interpolate_rates(
|
|
610
|
-
|
|
611
|
-
|
|
610
|
+
trade_dates=df["ReferenceDate"],
|
|
611
|
+
expirations=df["PaymentDate"],
|
|
612
612
|
extrapolate=False,
|
|
613
613
|
)
|
|
614
614
|
|
|
615
615
|
# Calculate the present value of the cash flows using the DI rate
|
|
616
|
-
bond_price =
|
|
616
|
+
bond_price = tt.calculate_present_value(
|
|
617
617
|
cash_flows=df["CashFlow"],
|
|
618
618
|
rates=df["DIRate"],
|
|
619
619
|
periods=df["BDToMat"] / 252,
|
|
@@ -77,7 +77,7 @@ def pre_spreads(reference_date: DateScalar) -> pd.DataFrame:
|
|
|
77
77
|
"""
|
|
78
78
|
# Fetch DI rates for the reference date
|
|
79
79
|
converted_date = dc.convert_input_dates(reference_date)
|
|
80
|
-
di = DIFutures(
|
|
80
|
+
di = DIFutures(trade_date=converted_date, month_start=True)
|
|
81
81
|
df_di = di.df
|
|
82
82
|
if "SettlementRate" not in df_di.columns:
|
|
83
83
|
raise ValueError("DI rates data is missing the 'SettlementRate' column.")
|
|
@@ -49,13 +49,6 @@ path = "pyield/__about__.py"
|
|
|
49
49
|
[tool.hatch.build.targets.sdist]
|
|
50
50
|
only-include = ["pyield"]
|
|
51
51
|
|
|
52
|
-
[tool.pdm]
|
|
53
|
-
version = { source = "file", path = "pyield/__about__.py" }
|
|
54
|
-
distribution = true
|
|
55
|
-
|
|
56
|
-
[tool.pdm.build]
|
|
57
|
-
excludes = ["tests", "docs"]
|
|
58
|
-
|
|
59
52
|
[tool.uv]
|
|
60
53
|
package = true
|
|
61
54
|
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.25.6"
|
|
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
|