PYield 0.24.2__tar.gz → 0.25.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.
Files changed (34) hide show
  1. {pyield-0.24.2 → pyield-0.25.1}/PKG-INFO +1 -1
  2. pyield-0.25.1/pyield/__about__.py +1 -0
  3. {pyield-0.24.2 → pyield-0.25.1}/pyield/b3_futures/historical.py +12 -5
  4. {pyield-0.24.2 → pyield-0.25.1}/pyield/b3_futures/intraday.py +19 -9
  5. {pyield-0.24.2 → pyield-0.25.1}/pyield/bonds/bond_tools.py +1 -1
  6. {pyield-0.24.2 → pyield-0.25.1}/pyield/bonds/ntnb.py +1 -1
  7. {pyield-0.24.2 → pyield-0.25.1}/pyield/di.py +54 -19
  8. pyield-0.24.2/pyield/__about__.py +0 -1
  9. {pyield-0.24.2 → pyield-0.25.1}/.gitignore +0 -0
  10. {pyield-0.24.2 → pyield-0.25.1}/LICENSE +0 -0
  11. {pyield-0.24.2 → pyield-0.25.1}/README.md +0 -0
  12. {pyield-0.24.2 → pyield-0.25.1}/pyield/__init__.py +0 -0
  13. {pyield-0.24.2 → pyield-0.25.1}/pyield/anbima.py +0 -0
  14. {pyield-0.24.2 → pyield-0.25.1}/pyield/b3_futures/__init__.py +0 -0
  15. {pyield-0.24.2 → pyield-0.25.1}/pyield/b3_futures/common.py +0 -0
  16. {pyield-0.24.2 → pyield-0.25.1}/pyield/b3_futures/xml.py +0 -0
  17. {pyield-0.24.2 → pyield-0.25.1}/pyield/bday.py +0 -0
  18. {pyield-0.24.2 → pyield-0.25.1}/pyield/bonds/__init__.py +0 -0
  19. {pyield-0.24.2 → pyield-0.25.1}/pyield/bonds/lft.py +0 -0
  20. {pyield-0.24.2 → pyield-0.25.1}/pyield/bonds/ltn.py +0 -0
  21. {pyield-0.24.2 → pyield-0.25.1}/pyield/bonds/ntnf.py +0 -0
  22. {pyield-0.24.2 → pyield-0.25.1}/pyield/conftest.py +0 -0
  23. {pyield-0.24.2 → pyield-0.25.1}/pyield/data_cache.py +0 -0
  24. {pyield-0.24.2 → pyield-0.25.1}/pyield/date_converter.py +0 -0
  25. {pyield-0.24.2 → pyield-0.25.1}/pyield/holidays/__init__.py +0 -0
  26. {pyield-0.24.2 → pyield-0.25.1}/pyield/holidays/br_holidays_new.txt +0 -0
  27. {pyield-0.24.2 → pyield-0.25.1}/pyield/holidays/br_holidays_old.txt +0 -0
  28. {pyield-0.24.2 → pyield-0.25.1}/pyield/holidays/brholidays.py +0 -0
  29. {pyield-0.24.2 → pyield-0.25.1}/pyield/indicators.py +0 -0
  30. {pyield-0.24.2 → pyield-0.25.1}/pyield/interpolator.py +0 -0
  31. {pyield-0.24.2 → pyield-0.25.1}/pyield/projections.py +0 -0
  32. {pyield-0.24.2 → pyield-0.25.1}/pyield/py.typed +0 -0
  33. {pyield-0.24.2 → pyield-0.25.1}/pyield/tools.py +0 -0
  34. {pyield-0.24.2 → pyield-0.25.1}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: PYield
3
- Version: 0.24.2
3
+ Version: 0.25.1
4
4
  Summary: A Python library for analysis of fixed income instruments in Brazil
5
5
  Project-URL: Source, https://github.com/crdcj/PYield
6
6
  Author-email: Carlos Carvalho <cr.cj@outlook.com>
@@ -0,0 +1 @@
1
+ __version__ = "0.25.1"
@@ -94,9 +94,9 @@ def _convert_prices_to_rates(
94
94
  Returns:
95
95
  pd.Series: A pd.Series containing the futures rates.
96
96
  """
97
- if count_convention == 252:
97
+ if count_convention == 252: # noqa
98
98
  rates = (100_000 / prices) ** (252 / days_to_expiration) - 1
99
- elif count_convention == 360:
99
+ elif count_convention == 360: # noqa
100
100
  rates = (100_000 / prices - 1) * (360 / days_to_expiration)
101
101
  else:
102
102
  raise ValueError("Invalid count_convention. Must be 252 or 360.")
@@ -210,7 +210,7 @@ def process_df(
210
210
 
211
211
  df["DaysToExp"] = (df["ExpirationDate"] - trade_date).dt.days
212
212
  # Convert to nullable integer, since it is the default type in the library
213
- df["DaysToExp"] = df["DaysToExp"].astype(pd.Int64Dtype())
213
+ df["DaysToExp"] = df["DaysToExp"].astype("Int64")
214
214
 
215
215
  df["BDaysToExp"] = bday.count(trade_date, df["ExpirationDate"])
216
216
 
@@ -232,19 +232,25 @@ def process_df(
232
232
  # Remove % and round to 5 (3 in %) dec. places in rate columns
233
233
  df[rate_cols] = df[rate_cols].div(100).round(5)
234
234
 
235
- if COUNT_CONVENTIONS[asset_code] == 252:
235
+ if COUNT_CONVENTIONS[asset_code] == 252: # noqa
236
236
  df["SettlementRate"] = _convert_prices_to_rates(
237
237
  prices=df["SettlementPrice"],
238
238
  days_to_expiration=df["BDaysToExp"],
239
239
  count_convention=252,
240
240
  )
241
- elif COUNT_CONVENTIONS[asset_code] == 360:
241
+ elif COUNT_CONVENTIONS[asset_code] == 360: # noqa
242
242
  df["SettlementRate"] = _convert_prices_to_rates(
243
243
  prices=df["SettlementPrice"],
244
244
  days_to_expiration=df["DaysToExp"],
245
245
  count_convention=360,
246
246
  )
247
247
 
248
+ # Calculate DV01 for DI1 contracts
249
+ if asset_code == "DI1":
250
+ byears = df["BDaysToExp"] / 252
251
+ dv01_price = 100_000 / ((1 + df["SettlementRate"] + 0.0001) ** byears)
252
+ df["DV01"] = (df["SettlementPrice"] - dv01_price).astype("Float64")
253
+
248
254
  return df
249
255
 
250
256
 
@@ -262,6 +268,7 @@ def _select_and_reorder_columns(df: pd.DataFrame):
262
268
  "TradeCount",
263
269
  "TradeVolume",
264
270
  "FinancialVolume",
271
+ "DV01",
265
272
  "SettlementPrice",
266
273
  "SettlementRate",
267
274
  "OpenRate",
@@ -9,14 +9,14 @@ def _fetch_b3_df(future_code: str) -> pd.DataFrame:
9
9
  Fetch the latest data for a given future code from B3 derivatives quotation API.
10
10
 
11
11
  Args:
12
- future_code (str): The future code to fetch data for.
12
+ future_code (str): The future code to fetch data for.
13
13
 
14
14
  Returns:
15
- pd.DataFrame: DataFrame containing the normalized and cleaned data from the API.
16
- If no data is available, an empty DataFrame is returned.
15
+ pd.DataFrame: DataFrame containing the normalized and cleaned data from the API.
16
+ If no data is available, an empty DataFrame is returned.
17
17
 
18
18
  Raises:
19
- Exception: An exception is raised if the data fetch operation fails.
19
+ Exception: An exception is raised if the data fetch operation fails.
20
20
  """
21
21
 
22
22
  url = f"https://cotacao.b3.com.br/mds/api/v1/DerivativeQuotation/{future_code}"
@@ -46,10 +46,10 @@ def _rename_columns(df: pd.DataFrame) -> pd.DataFrame:
46
46
  Rename the columns of a DataFrame containing the futures data.
47
47
 
48
48
  Args:
49
- df (pd.DataFrame): A DataFrame containing futures data.
49
+ df (pd.DataFrame): A DataFrame containing futures data.
50
50
 
51
51
  Returns:
52
- pd.DataFrame: DataFrame with the columns renamed.
52
+ pd.DataFrame: DataFrame with the columns renamed.
53
53
  """
54
54
  all_columns = {
55
55
  "symb": "TickerSymbol",
@@ -108,12 +108,20 @@ def _process_df(raw_df: pd.DataFrame) -> pd.DataFrame:
108
108
 
109
109
  df["DaysToExp"] = (df["ExpirationDate"] - df["TradeDate"]).dt.days
110
110
  # Convert to nullable integer, since it is the default type in the library
111
- df["DaysToExp"] = df["DaysToExp"].astype(pd.Int64Dtype())
111
+ df["DaysToExp"] = df["DaysToExp"].astype("Int64")
112
112
 
113
113
  # Remove percentage in all rate columns
114
114
  rate_cols = [col for col in df.columns if "Rate" in col]
115
115
  df[rate_cols] = df[rate_cols].div(100).round(5)
116
116
 
117
+ # Adjust DI1 futures contracts
118
+ if "DI1" in df["TickerSymbol"].iloc[0]:
119
+ byears = df["BDaysToExp"] / 252
120
+ df["CurrentPrice"] = 100_000 / ((1 + df["CurrentRate"]) ** (byears))
121
+ df["CurrentPrice"] = df["CurrentPrice"].round(2).astype("Float64")
122
+ dv01_price = 100_000 / ((1 + df["CurrentRate"] + 0.0001) ** byears)
123
+ df["DV01"] = (df["CurrentPrice"] - dv01_price).astype("Float64")
124
+
117
125
  return df
118
126
 
119
127
 
@@ -122,10 +130,10 @@ def _select_and_reorder_columns(df: pd.DataFrame) -> pd.DataFrame:
122
130
  Select and reorder columns in the DataFrame.
123
131
 
124
132
  Args:
125
- df (pd.DataFrame): A DataFrame containing futures data.
133
+ df (pd.DataFrame): A DataFrame containing futures data.
126
134
 
127
135
  Returns:
128
- pd.DataFrame: DataFrame with the columns selected and reordered.
136
+ pd.DataFrame: DataFrame with the columns selected and reordered.
129
137
  """
130
138
  all_columns = [
131
139
  "TradeDate",
@@ -138,6 +146,7 @@ def _select_and_reorder_columns(df: pd.DataFrame) -> pd.DataFrame:
138
146
  "TradeCount",
139
147
  "TradeVolume",
140
148
  "FinancialVolume",
149
+ "DV01",
141
150
  "PrevSettlementRate",
142
151
  "MinLimitRate",
143
152
  "MaxLimitRate",
@@ -148,6 +157,7 @@ def _select_and_reorder_columns(df: pd.DataFrame) -> pd.DataFrame:
148
157
  "CurrentAskRate",
149
158
  "CurrentBidRate",
150
159
  "CurrentRate",
160
+ "CurrentPrice",
151
161
  ]
152
162
  reordered_columns = [col for col in all_columns if col in df.columns]
153
163
  return df[reordered_columns].copy()
@@ -78,7 +78,7 @@ def pre_spreads(reference_date: DateScalar) -> pd.DataFrame:
78
78
  # Fetch DI rates for the reference date
79
79
  converted_date = dc.convert_input_dates(reference_date)
80
80
  di = DIFutures(trade_dates=converted_date, month_start=True)
81
- df_di = di.data
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.")
84
84
 
@@ -490,7 +490,7 @@ def bei_rates(
490
490
  Get the DI Futures settlement rates for the same reference date to be used as
491
491
  reference for the nominal rates:
492
492
  >>> di = yd.DIFutures("05-09-2024")
493
- >>> df_di = di.data
493
+ >>> df_di = di.df
494
494
 
495
495
  Calculate the BEI rates considering the settlement at the reference date:
496
496
  >>> yd.ntnb.bei_rates(
@@ -17,17 +17,19 @@ class DIFutures:
17
17
  NTN-F bond maturities.
18
18
 
19
19
  Args:
20
- trade_date (DateScalar): The date to retrieve the contract data.
20
+ trade_dates (DateScalar | DateArray | None): The trade date(s) to retrieve the
21
+ DI contract data. If None, the latest available historical trade date is
22
+ used.
21
23
  month_start (bool): If True, adjusts the expiration dates to the start
22
24
  of the month.
23
- prefixed (bool): If True, filters the DI contracts to match only
25
+ pre_filter (bool): If True, filters the DI contracts to match only
24
26
  expirations with existing prefixed TN bond maturities (LTN and NTN-F).
25
27
  all_columns (bool): If True, returns all available columns in the DI dataset.
26
28
 
27
29
  Examples:
28
30
  To create a `DIFutures` instance and retrieve data:
29
- >>> di = yd.DIFutures(trade_dates="16-10-2024", month_start=True)
30
- >>> df = di.data # Retrieve DI contract dataframe for the specified date
31
+ >>> dif = yd.DIFutures(trade_dates="16-10-2024", month_start=True)
32
+ >>> df = dif.df # Retrieve DI contract dataframe for the specified date
31
33
  >>> df.iloc[:5, :5] # Show the first five rows and columns
32
34
  TradeDate ExpirationDate TickerSymbol BDaysToExp OpenContracts
33
35
  0 2024-10-16 2024-11-01 DI1X24 12 1744269
@@ -37,7 +39,7 @@ class DIFutures:
37
39
  4 2024-10-16 2025-03-01 DI1H25 94 344056
38
40
 
39
41
  You can also retrieve forward rates for the DI contracts:
40
- >>> di.forwards.iloc[:5] # Show the first five rows
42
+ >>> dif.forwards.iloc[:5] # Show the first five rows
41
43
  TradeDate ExpirationDate SettlementRate ForwardRate
42
44
  0 2024-10-16 2024-11-01 0.10653 0.10653
43
45
  1 2024-10-16 2024-12-01 0.1091 0.110726
@@ -62,19 +64,42 @@ class DIFutures:
62
64
  self,
63
65
  trade_dates: DateScalar | DateArray | None = None,
64
66
  month_start: bool = False,
65
- prefixed: bool = False,
67
+ pre_filter: bool = False,
66
68
  all_columns: bool = True,
67
69
  ):
68
70
  """
69
- Initialize the DIFutures instance with a specific trade date.
71
+ Initialize the DIFutures instance with the specified parameters.
72
+
73
+ Note:
74
+ The DI contract DataFrame is not loaded during initialization. It will be
75
+ automatically loaded the first time the df() method is accessed.
70
76
  """
77
+ self._df = pd.DataFrame()
78
+ self._dirty = True # Attribute to track if the df needs updating
79
+
71
80
  self.trade_dates = trade_dates
72
81
  self.month_start = month_start
73
- self.prefixed = prefixed
82
+ self.pre_filter = pre_filter
74
83
  self.all_columns = all_columns
75
84
 
76
85
  @property
77
- def data(self) -> pd.DataFrame:
86
+ def df(self) -> pd.DataFrame:
87
+ """
88
+ The DI contracts DataFrame for the instance's trade dates and applied filters.
89
+
90
+ If the internal state is marked as 'dirty', the DataFrame will be (re)loaded
91
+ before returning, ensuring that the returned data reflects the latest attribute
92
+ values.
93
+
94
+ Returns:
95
+ pd.DataFrame: The DI contract data.
96
+ """
97
+ if self._dirty:
98
+ self._df = self._update_df()
99
+ self._dirty = False
100
+ return self._df
101
+
102
+ def _update_df(self) -> pd.DataFrame:
78
103
  """Retrieve DI contract DataFrame for the initialized trade date."""
79
104
  df = (
80
105
  get_di_dataset()
@@ -93,7 +118,7 @@ class DIFutures:
93
118
  if "DaysToExpiration" in df.columns:
94
119
  df.drop(columns=["DaysToExpiration"], inplace=True)
95
120
 
96
- if self._prefixed:
121
+ if self._pre_filter:
97
122
  df_pre = (
98
123
  get_anbima_dataset()
99
124
  .query("BondType in ['LTN', 'NTN-F']")
@@ -106,7 +131,7 @@ class DIFutures:
106
131
  df_pre["MaturityDate"] = bday.offset(df_pre["MaturityDate"], 0)
107
132
  df_pre = df_pre.rename(
108
133
  columns={
109
- "ReferenceDate": "ExpirationDate",
134
+ "ReferenceDate": "TradeDate",
110
135
  "MaturityDate": "ExpirationDate",
111
136
  }
112
137
  )
@@ -125,13 +150,18 @@ class DIFutures:
125
150
  "TickerSymbol",
126
151
  "OpenContracts",
127
152
  "TradeVolume",
153
+ "DV01",
128
154
  "OpenRate",
129
155
  "MinRate",
130
156
  "MaxRate",
131
157
  "CloseRate",
132
158
  "SettlementRate",
159
+ "CurrentRate",
160
+ "SettlementPrice",
161
+ "CurrentPrice",
133
162
  ]
134
- df = df[cols].copy()
163
+ selected_cols = [col for col in cols if col in df.columns]
164
+ df = df[selected_cols].copy()
135
165
 
136
166
  return df.sort_values(by=["TradeDate", "ExpirationDate"]).reset_index(drop=True)
137
167
 
@@ -152,7 +182,7 @@ class DIFutures:
152
182
  - ForwardRate: The forward rate calculated between successive expiration
153
183
  dates.
154
184
  """
155
- df = self.data
185
+ df = self.df
156
186
  if df.empty:
157
187
  return pd.DataFrame()
158
188
 
@@ -278,7 +308,7 @@ class DIFutures:
278
308
  if not interpolate and extrapolate:
279
309
  raise ValueError("Extrapolation is not allowed without interpolation.")
280
310
 
281
- df = self.data
311
+ df = self.df
282
312
 
283
313
  if df.empty:
284
314
  return float("NaN")
@@ -329,6 +359,8 @@ class DIFutures:
329
359
  elif isinstance(trade_dates, pd.Series):
330
360
  self._trade_dates = trade_dates.drop_duplicates().sort_values().to_list()
331
361
 
362
+ self._dirty = True
363
+
332
364
  @property
333
365
  def month_start(self) -> bool:
334
366
  """
@@ -346,9 +378,10 @@ class DIFutures:
346
378
  @month_start.setter
347
379
  def month_start(self, value: bool):
348
380
  self._month_start = value
381
+ self._dirty = True
349
382
 
350
383
  @property
351
- def prefixed(self) -> bool:
384
+ def pre_filter(self) -> bool:
352
385
  """
353
386
  Filters DI Futures to match prefixed TN bond maturities.
354
387
 
@@ -359,11 +392,12 @@ class DIFutures:
359
392
  bool: Whether the contracts are filtered to match prefixed TN bond
360
393
  maturities from the ANBIMA dataset.
361
394
  """
362
- return self._prefixed
395
+ return self._pre_filter
363
396
 
364
- @prefixed.setter
365
- def prefixed(self, value: bool):
366
- self._prefixed = value
397
+ @pre_filter.setter
398
+ def pre_filter(self, value: bool):
399
+ self._pre_filter = value
400
+ self._dirty = True
367
401
 
368
402
  @property
369
403
  def all_columns(self) -> bool:
@@ -372,3 +406,4 @@ class DIFutures:
372
406
  @all_columns.setter
373
407
  def all_columns(self, value: bool):
374
408
  self._all_columns = value
409
+ self._dirty = True
@@ -1 +0,0 @@
1
- __version__ = "0.24.2"
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