PYield 0.7.13__tar.gz → 0.8.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.
Files changed (32) hide show
  1. {pyield-0.7.13 → pyield-0.8.0}/PKG-INFO +1 -1
  2. pyield-0.8.0/pyield/__about__.py +1 -0
  3. {pyield-0.7.13 → pyield-0.8.0}/pyield/__init__.py +2 -0
  4. {pyield-0.7.13 → pyield-0.8.0}/pyield/bday.py +4 -3
  5. {pyield-0.7.13 → pyield-0.8.0}/pyield/data_access.py +18 -66
  6. pyield-0.8.0/pyield/date_validator.py +48 -0
  7. {pyield-0.7.13 → pyield-0.8.0}/pyield/futures/intraday.py +16 -10
  8. pyield-0.8.0/pyield/interpolator.py +78 -0
  9. pyield-0.8.0/pyield/ntnb.py +261 -0
  10. {pyield-0.7.13 → pyield-0.8.0}/pyield/tn_bonds.py +2 -2
  11. {pyield-0.7.13 → pyield-0.8.0}/pyproject.toml +9 -5
  12. pyield-0.7.13/pyield/__about__.py +0 -1
  13. {pyield-0.7.13 → pyield-0.8.0}/LICENSE +0 -0
  14. {pyield-0.7.13 → pyield-0.8.0}/README.md +0 -0
  15. {pyield-0.7.13 → pyield-0.8.0}/pyield/futures/__init__.py +0 -0
  16. {pyield-0.7.13 → pyield-0.8.0}/pyield/futures/common.py +0 -0
  17. {pyield-0.7.13 → pyield-0.8.0}/pyield/futures/historical.py +0 -0
  18. {pyield-0.7.13 → pyield-0.8.0}/pyield/futures/xml.py +0 -0
  19. {pyield-0.7.13 → pyield-0.8.0}/pyield/holidays/__init__.py +0 -0
  20. {pyield-0.7.13 → pyield-0.8.0}/pyield/holidays/br_holidays_new.txt +0 -0
  21. {pyield-0.7.13 → pyield-0.8.0}/pyield/holidays/br_holidays_old.txt +0 -0
  22. {pyield-0.7.13 → pyield-0.8.0}/pyield/holidays/core.py +0 -0
  23. {pyield-0.7.13 → pyield-0.8.0}/pyield/indicators.py +0 -0
  24. {pyield-0.7.13 → pyield-0.8.0}/pyield/projections.py +0 -0
  25. {pyield-0.7.13 → pyield-0.8.0}/pyield/py.typed +0 -0
  26. {pyield-0.7.13 → pyield-0.8.0}/pyield/spreads.py +0 -0
  27. {pyield-0.7.13 → pyield-0.8.0}/tests/__init__.py +0 -0
  28. {pyield-0.7.13 → pyield-0.8.0}/tests/data/SPRD231222.zip +0 -0
  29. {pyield-0.7.13 → pyield-0.8.0}/tests/data/SPRD240426.zip +0 -0
  30. {pyield-0.7.13 → pyield-0.8.0}/tests/test_bday.py +0 -0
  31. {pyield-0.7.13 → pyield-0.8.0}/tests/test_futures.py +0 -0
  32. {pyield-0.7.13 → pyield-0.8.0}/tests/test_futures_xml.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: PYield
3
- Version: 0.7.13
3
+ Version: 0.8.0
4
4
  Summary: A Python library for analysis of fixed income instruments in Brazil
5
5
  Keywords: fixed-income, brazil, finance, analysis, bonds
6
6
  Author-Email: Carlos Carvalho <cr.cj@outlook.com>
@@ -0,0 +1 @@
1
+ __version__ = "0.8.0"
@@ -1,3 +1,4 @@
1
+ from . import ntnb
1
2
  from .__about__ import __version__
2
3
  from .bday import count_bdays, generate_bdays, is_bday, offset_bdays
3
4
  from .data_access import (
@@ -17,4 +18,5 @@ __all__ = [
17
18
  "fetch_indicator",
18
19
  "fetch_projection",
19
20
  "calculate_spreads",
21
+ "ntnb",
20
22
  ]
@@ -9,7 +9,6 @@ from .holidays import BrHolidays
9
9
  SingleDateTypes = str | np.datetime64 | pd.Timestamp | datetime
10
10
  SeriesDateTypes = list | tuple | np.ndarray | pd.Series | pd.Index | pd.DatetimeIndex
11
11
 
12
- TO_TIMESTAMP_TYPES = (str, np.datetime64, datetime)
13
12
  TO_SERIES_TYPES = (list, tuple, np.ndarray, pd.Series, pd.Index, pd.DatetimeIndex)
14
13
 
15
14
  # Initialize the BrHolidays class
@@ -33,12 +32,14 @@ def _normalize_input_dates(
33
32
  ) -> pd.Timestamp | pd.Series:
34
33
  if dates is None:
35
34
  return pd.Timestamp.today().normalize()
35
+ elif isinstance(dates, str):
36
+ return pd.to_datetime(dates, dayfirst=True).normalize()
36
37
  elif isinstance(dates, pd.Timestamp):
37
38
  return dates.normalize()
38
- elif isinstance(dates, TO_TIMESTAMP_TYPES):
39
+ elif isinstance(dates, (np.datetime64 | datetime)):
39
40
  return pd.Timestamp(dates).normalize()
40
41
  elif isinstance(dates, TO_SERIES_TYPES):
41
- result = pd.to_datetime(dates)
42
+ result = pd.to_datetime(dates, dayfirst=True)
42
43
  return pd.Series(result).dt.normalize()
43
44
  else:
44
45
  raise ValueError("Invalid date format.")
@@ -1,6 +1,6 @@
1
1
  import pandas as pd
2
2
 
3
- from . import bday
3
+ from . import date_validator as dv
4
4
  from . import futures as ft
5
5
  from . import indicators as it
6
6
  from . import projections as pr
@@ -8,58 +8,6 @@ from . import spreads as sp
8
8
  from . import tn_bonds as tb
9
9
 
10
10
 
11
- def _normalize_date(input_date: str | pd.Timestamp | None = None) -> pd.Timestamp:
12
- """
13
- Normalizes the given date to ensure it is a past business day at midnight. If no
14
- date is provided, it defaults to the last business day.
15
-
16
- Args:
17
- reference_date (str | pd.Timestamp | None): The date to normalize. Can be a
18
- string, pandas Timestamp or None. If None, it defaults to the last business day.
19
-
20
- Returns:
21
- pd.Timestamp: A normalized pandas Timestamp representing a past business day at
22
- midnight.
23
-
24
- Raises:
25
- ValueError: If the input date format is invalid, if the date is in the future,
26
- or if the date is not a business day.
27
-
28
- Notes:
29
- - Normalization means setting the time component of the timestamp to midnight.
30
- - The function checks if the normalized date is a business day and adjusts
31
- accordingly.
32
- - Business day calculations consider local market holidays.
33
-
34
- Examples:
35
- >>> _normalize_date('2023-04-01')
36
- >>> _normalize_date(pd.Timestamp('2023-04-01 15:30'))
37
- >>> _normalize_date()
38
- """
39
- if isinstance(input_date, str):
40
- # Convert string date to Timestamp and normalize to midnight
41
- normalized_date = pd.Timestamp(input_date).normalize()
42
- elif isinstance(input_date, pd.Timestamp):
43
- # Normalize Timestamp to midnight
44
- normalized_date = input_date.normalize()
45
- elif input_date is None:
46
- # If no date is provided, use the last available business day
47
- today = pd.Timestamp.today().normalize()
48
- normalized_date = bday.offset_bdays(dates=today, offset=0, roll="backward")
49
- else:
50
- raise ValueError(f"Date format not recognized: {input_date}")
51
-
52
- error_date = normalized_date.strftime("%d-%m-%Y")
53
- # Validate that the date is not in the future
54
- if normalized_date > pd.Timestamp.today().normalize():
55
- raise ValueError(f"Date {error_date} is in the future")
56
- # Validate that the date is a business day
57
- if not bday.is_bday(normalized_date):
58
- raise ValueError(f"Date {error_date} is not a business day")
59
-
60
- return normalized_date
61
-
62
-
63
11
  def fetch_asset(
64
12
  asset_code: str, reference_date: str | pd.Timestamp | None = None
65
13
  ) -> pd.DataFrame:
@@ -81,7 +29,8 @@ def fetch_asset(
81
29
  - "IND": Ibovespa Futures from B3.
82
30
  - "WIN": Mini Ibovespa Futures from B3.
83
31
  reference_date (str | pd.Timestamp | None): The reference date for which data is
84
- fetched. Defaults to the last business day if None.
32
+ fetched. Defaults to the last business day if None. If the reference date is
33
+ a string, it should be in 'DD-MM-YYYY' format.
85
34
  **kwargs: Additional keyword arguments, specifically:
86
35
  - return_raw (bool): Whether to return raw data without processing. Defaults
87
36
  to False.
@@ -93,13 +42,13 @@ def fetch_asset(
93
42
  ValueError: If the asset code is not recognized or supported.
94
43
 
95
44
  Examples:
96
- >>> fetch_asset('TRB', '2023-04-01')
97
- >>> fetch_asset('DI1', '2023-04-01', return_raw=True)
45
+ >>> fetch_asset('TRB', '31-05-2024')
46
+ >>> fetch_asset('DI1', '31-05-2024')
98
47
  """
99
48
  SUPPORTED_BONDS = ["LTN", "LFT", "NTN-F", "NTN-B"]
100
49
  SUPPORTED_FUTURES = ["DI1", "DDI", "FRC", "DAP", "DOL", "WDO", "IND", "WIN"]
101
50
 
102
- normalized_date = _normalize_date(reference_date)
51
+ normalized_date = dv.normalize_date(reference_date)
103
52
 
104
53
  today = pd.Timestamp.today().normalize()
105
54
  if normalized_date == today:
@@ -109,8 +58,10 @@ def fetch_asset(
109
58
  return tb.fetch_bonds(reference_date=normalized_date)
110
59
 
111
60
  if asset_code.upper() in SUPPORTED_BONDS:
112
- df = tb.fetch_bonds(reference_date=normalized_date)
113
- return df.query(f"BondType == '{asset_code.upper()}'")
61
+ df_bond = tb.fetch_bonds(reference_date=normalized_date)
62
+ df_bond.query(f"BondType == '{asset_code.upper()}'", inplace=True)
63
+ # Return the DataFrame sorted by maturity date
64
+ return df_bond.sort_values("MaturityDate", ignore_index=True)
114
65
 
115
66
  if asset_code.upper() in SUPPORTED_FUTURES:
116
67
  return ft.fetch_historical_df(
@@ -137,7 +88,8 @@ def fetch_indicator(
137
88
  - "VNA_LFT": VNA (Valor Nominal Atualizado) of LFT (Letra Financeira do
138
89
  Tesouro), which reflects updated nominal values for these bonds.
139
90
  - reference_date (str | pd.Timestamp | None): The reference date for which data
140
- is fetched. Defaults to the last business day if None.
91
+ is fetched. Defaults to the last business day if None. If the reference date
92
+ is a string, it should be in 'DD-MM-YYYY' format.
141
93
 
142
94
  Returns:
143
95
  float | None: The value of the specified economic indicator for the reference
@@ -147,14 +99,14 @@ def fetch_indicator(
147
99
  ValueError: If the indicator code is not recognized or supported.
148
100
 
149
101
  Examples:
150
- >>> fetch_indicator('SELIC', '2023-04-01')
102
+ >>> fetch_indicator('SELIC', '31-05-2024')
151
103
  0.1075 # Indicates a SELIC target rate of 10.75% p.a.
152
- >>> fetch_indicator('IPCA', '2023-03-10')
153
- 0.0016 # Indicates an IPCA monthly rate of 0.16% p.m.
154
- >>> fetch_indicator('DI', '2023-04-17')
104
+ >>> fetch_indicator('IPCA', '01-04-2024')
105
+ 0.0038 # Indicates an IPCA monthly rate of 0.38% p.m.
106
+ >>> fetch_indicator('DI', '31-05-2024')
155
107
  0.00040168 # Indicates a DI daily rate of 0.02% p.d.
156
108
  """
157
- normalized_date = _normalize_date(reference_date)
109
+ normalized_date = dv.normalize_date(reference_date)
158
110
 
159
111
  if indicator_code.upper() == "SELIC":
160
112
  return it.fetch_selic_target(reference_date=normalized_date)
@@ -227,7 +179,7 @@ def calculate_spreads(
227
179
  ValueError: If an invalid spread type is provided.
228
180
  """
229
181
  # Normalize the reference date
230
- normalized_date = _normalize_date(reference_date)
182
+ normalized_date = dv.normalize_date(reference_date)
231
183
  if spread_type.upper() == "DI_VS_PRE":
232
184
  return sp.calculate_di_spreads(normalized_date)
233
185
  else:
@@ -0,0 +1,48 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from . import bday
5
+
6
+
7
+ def normalize_date(input_date: str | pd.Timestamp | None = None) -> pd.Timestamp:
8
+ """
9
+ Normalizes the given date to ensure it is a past business day at midnight. If no
10
+ date is provided, it defaults to the last business day.
11
+
12
+ Args:
13
+ reference_date (str | pd.Timestamp | None): The date to normalize. Can be a
14
+ string, pandas Timestamp or None. If None, it defaults to the last business day.
15
+
16
+ Returns:
17
+ pd.Timestamp: A normalized pandas Timestamp.
18
+
19
+ Raises:
20
+ ValueError: If the input date format is invalid.
21
+
22
+ Notes:
23
+ - Normalization means setting the time component of the timestamp to midnight.
24
+ - The function checks if the normalized date is a business day and adjusts
25
+ accordingly.
26
+ - Business day calculations consider local market holidays.
27
+
28
+ Examples:
29
+ >>> normalize_date("31-05-2024")
30
+ >>> normalize_date(pd.Timestamp("2023-04-01 15:30"))
31
+ """
32
+ if isinstance(input_date, str):
33
+ # Convert string date to Timestamp and normalize to midnight
34
+ normalized_date = pd.to_datetime(input_date, dayfirst=True).normalize()
35
+ elif isinstance(input_date, pd.Timestamp):
36
+ # Normalize Timestamp to midnight
37
+ normalized_date = input_date.normalize()
38
+ elif isinstance(input_date, np.datetime64):
39
+ # Convert numpy datetime to Timestamp and normalize to midnight
40
+ normalized_date = pd.Timestamp(input_date).normalize()
41
+ elif input_date is None:
42
+ # If no date is provided, use the last available business day
43
+ today = pd.Timestamp.today().normalize()
44
+ normalized_date = bday.offset_bdays(dates=today, offset=0, roll="backward")
45
+ else:
46
+ raise ValueError(f"Date format not recognized: {input_date}")
47
+
48
+ return normalized_date
@@ -48,6 +48,10 @@ def _fetch_raw_df(future_code: str) -> pd.DataFrame:
48
48
  # Sort the DataFrame by maturity code and reset the index
49
49
  df.sort_values("mtrtyCode", inplace=True, ignore_index=True)
50
50
 
51
+ # Get currante date
52
+ today = pd.Timestamp.now().normalize()
53
+ df["TradeDate"] = today
54
+
51
55
  # Get current date and time
52
56
  now = pd.Timestamp.now().round("s")
53
57
  # Subtract 15 minutes from the current time to account for API delay
@@ -72,21 +76,21 @@ def _rename_columns(df: pd.DataFrame) -> pd.DataFrame:
72
76
  """
73
77
  all_columns = {
74
78
  "symb": "TickerSymbol",
75
- "mtrtyCode": "ExpirationDate",
76
- "opnCtrcts": "OpenContracts",
77
- "tradQty": "TradeCount",
78
- "traddCtrctsQty": "TradeVolume",
79
- "grssAmt": "FinancialVolume",
80
- "prvsDayAdjstmntPric": "PrevSettlementRate",
81
79
  "bottomLmtPric": "MinLimitRate",
80
+ "prvsDayAdjstmntPric": "PrevSettlementRate",
82
81
  "topLmtPric": "MaxLimitRate",
83
82
  "opngPric": "OpenRate",
84
83
  "minPric": "MinRate",
85
- "avrgPric": "AvgRate",
86
84
  "maxPric": "MaxRate",
85
+ "avrgPric": "AvgRate",
86
+ "curPrc": "CurrentRate",
87
+ "grssAmt": "FinancialVolume",
88
+ "mtrtyCode": "ExpirationDate",
89
+ "opnCtrcts": "OpenContracts",
90
+ "tradQty": "TradeCount",
91
+ "traddCtrctsQty": "TradeVolume",
87
92
  "buyOffer.price": "CurrentAskRate",
88
93
  "sellOffer.price": "CurrentBidRate",
89
- "curPrc": "CurrentRate",
90
94
  }
91
95
  # Check which columns are present in the DataFrame before renaming
92
96
  rename_dict = {c: all_columns[c] for c in all_columns if c in df.columns}
@@ -97,9 +101,9 @@ def _rename_columns(df: pd.DataFrame) -> pd.DataFrame:
97
101
  def _process_df(raw_df: pd.DataFrame) -> pd.DataFrame:
98
102
  df = raw_df.copy()
99
103
 
100
- df["BDaysToExp"] = bday.count_bdays(df["TradeTime"], df["ExpirationDate"])
104
+ df["BDaysToExp"] = bday.count_bdays(df["TradeDate"], df["ExpirationDate"])
101
105
 
102
- df["DaysToExp"] = (df["ExpirationDate"] - df["TradeTime"]).dt.days
106
+ df["DaysToExp"] = (df["ExpirationDate"] - df["TradeDate"]).dt.days
103
107
  # Convert to nullable integer, since it is the default type in the library
104
108
  df["DaysToExp"] = df["DaysToExp"].astype(pd.Int64Dtype())
105
109
 
@@ -121,10 +125,12 @@ def _select_and_reorder_columns(df: pd.DataFrame) -> pd.DataFrame:
121
125
  pd.DataFrame: A DataFrame with the columns selected and reordered.
122
126
  """
123
127
  columns = [
128
+ "TradeDate",
124
129
  "TradeTime",
125
130
  "TickerSymbol",
126
131
  "ExpirationDate",
127
132
  "BDaysToExp",
133
+ "DaysToExp",
128
134
  "OpenContracts",
129
135
  "TradeCount",
130
136
  "TradeVolume",
@@ -0,0 +1,78 @@
1
+ import bisect
2
+
3
+
4
+ def interpolate_flat_forward(
5
+ tx_ant: float, du_ant: int, tx_pos: float, du_pos: int, du: int
6
+ ) -> float:
7
+ """
8
+ Realiza a interpolação da taxa de juros usando o método de interpolação flat forward
9
+ considerando uma base de 252 dias úteis.
10
+
11
+ A interpolação é realizada entre dois pares de vértices conhecidos (tx_ant, du_ant)
12
+ e (tx_pos, du_pos), para um terceiro vértice definido pelo número de dias úteis 'du'
13
+ em que 'du_ant < du < du_pos'. Esse terceiro vértice é o ponto no tempo para o qual
14
+ a taxa de juros está sendo calculada.
15
+
16
+ Args:
17
+ - tx_ant (float): Taxa de juros do vértice anterior.
18
+ - du_ant (int): Número de dias úteis do vértice anterior.
19
+ - tx_pos (float): Taxa de juros do vértice posterior.
20
+ - du_pos (int): Número de dias úteis do vértice posterior.
21
+ - du (int): Dias úteis em que se deseja interpolar a taxa de juros.
22
+
23
+ Exemplo de uso:
24
+ taxa_interpolada = interpolate_flat_forward(0.045, 30, 0.05, 60, 45)
25
+
26
+ Retorna:
27
+ float: A taxa de juros interpolada no `du` fornecido.
28
+ """
29
+ a = (1 + tx_ant) ** (du_ant / 252)
30
+ b = (1 + tx_pos) ** (du_pos / 252)
31
+ c = (du - du_ant) / (du_pos - du_ant)
32
+
33
+ return (a * (b / a) ** c) ** (252 / du) - 1
34
+
35
+
36
+ def find_and_interpolate_flat_forward(
37
+ du: int,
38
+ dus: list[int],
39
+ txs: list[float],
40
+ ) -> float:
41
+ """
42
+ Encontra o ponto de interpolação apropriado e retorna a taxa interpolada pelo método
43
+ flat forward desse ponto. Utiliza o módulo `bisect` para busca binária em listas
44
+ ordenadas.
45
+
46
+ Args:
47
+ du (int): Número de dias úteis em que se deseja calcular a taxa de juros flat
48
+ forward. dus (List[int]): Lista com os dias úteis em que as taxas de juros são
49
+ conhecidas. txs (List[float]): Lista com as taxas de juros conhecidas.
50
+
51
+ Notas:
52
+ - Presume-se que `dus` e `txs` estão ordenados e têm o mesmo tamanho.
53
+ - O método utiliza 252 dias úteis por ano na interpolação, que é o padrão do
54
+ mercado brasileiro.
55
+ - Casos especiais são tratados para as situações onde `du` é menor que o
56
+ primeiro DU na lista, maior que o último DU, ou exatamente igual a um DU
57
+ conhecido, evitando a necessidade de interpolação.
58
+
59
+ Exemplo de uso: taxa_interpolada = find_and_interpolate_flat_forward(45, [30, 60,
60
+ 90], [0.045, 0.05, 0.055])
61
+
62
+ Retorna:
63
+ float: A taxa de juros interpolada pelo método flat forward para o número de
64
+ dias úteis fornecido.
65
+ """
66
+ # Special cases
67
+ if du <= dus[0]:
68
+ return txs[0]
69
+ elif du >= dus[-1]:
70
+ return txs[-1]
71
+ # Do not interpolate vertex whose rate is known
72
+ elif du in dus:
73
+ return txs[dus.index(du)]
74
+
75
+ # Find i such that du[i-1] < du < du[i]
76
+ i = bisect.bisect_left(dus, du)
77
+
78
+ return interpolate_flat_forward(txs[i - 1], dus[i - 1], txs[i], dus[i], du)
@@ -0,0 +1,261 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from . import bday
5
+ from . import data_access as da
6
+ from . import date_validator as dv
7
+ from . import interpolator as ip
8
+
9
+ # 6% per year compounded semi-annually and rounded to 8 decimal places
10
+ COUPON = 0.02956301 # round(((0.06 + 1) ** 0.5 - 1), 8)
11
+
12
+
13
+ def anbima_data(reference_date):
14
+ """
15
+ Fetch NTN-B Anbima data for the given reference date.
16
+
17
+ Parameters:
18
+ reference_date (str | pd.Timestamp): The reference date for fetching the data.
19
+
20
+ Returns:
21
+ pd.DataFrame: A DataFrame containing the Anbima data for the given reference date.
22
+ """
23
+ return da.fetch_asset(asset_code="NTN-B", reference_date=reference_date)
24
+
25
+
26
+ def anbima_rates(reference_date):
27
+ """
28
+ Fetch NTN-B Anbima indicative rates for the given reference date.
29
+
30
+ Parameters:
31
+ reference_date (str | pd.Timestamp): The reference date for fetching the data.
32
+
33
+ Returns:
34
+ pd.DataFrame: A DataFrame containing the maturity dates and corresponding rates.
35
+ """
36
+ df = anbima_data(reference_date)
37
+ return df[["MaturityDate", "IndicativeRate"]]
38
+
39
+
40
+ def truncate(value, decimal_places):
41
+ """
42
+ Truncate a float or a Pandas Series to the specified decimal place.
43
+
44
+ Parameters:
45
+ value (float, pandas.Series): The value(s) to be truncated.
46
+ decimal_places (int): The number of decimal places to truncate to.
47
+
48
+ Returns:
49
+ float or pandas.Series: The truncated value(s).
50
+ """
51
+ factor = 10**decimal_places
52
+ return np.trunc(value * factor) / factor
53
+
54
+
55
+ def coupon_dates_map(
56
+ start: str | pd.Timestamp,
57
+ end: str | pd.Timestamp,
58
+ ) -> pd.Series:
59
+ """
60
+ Generates a map of all possible coupon dates between the start and end dates.
61
+ The dates are inclusive.
62
+ Coupon payments are made on the 15th of February, May, August, and November (15-02,
63
+ 15-05, 15-08, and 15-11 of each year).
64
+ """
65
+ # Validate and normalize dates
66
+ start = dv.normalize_date(start)
67
+ end = dv.normalize_date(end)
68
+
69
+ # Initialize the first coupon date based on the reference date
70
+ reference_year = start.year
71
+ first_coupon_date = pd.Timestamp(f"{reference_year}-02-01")
72
+
73
+ # Generate coupon dates
74
+ dates = pd.date_range(start=first_coupon_date, end=end, freq="3MS")
75
+
76
+ # Convert to pandas Series since pd.date_range returns a DatetimeIndex
77
+ dates = pd.Series(dates)
78
+
79
+ # Offset dates by 14 in order to have day 15 of the month
80
+ dates = dates + pd.Timedelta(days=14)
81
+
82
+ # First coupon date must be after the reference date
83
+ return dates[dates >= start].reset_index(drop=True)
84
+
85
+
86
+ def coupon_dates(
87
+ from_date: str | pd.Timestamp,
88
+ maturity_date: str | pd.Timestamp,
89
+ ) -> pd.Series:
90
+ # Validate and normalize dates
91
+ from_date = dv.normalize_date(from_date)
92
+ maturity_date = dv.normalize_date(maturity_date)
93
+
94
+ # Initialize loop variables
95
+ coupon_date = maturity_date
96
+ coupon_dates = []
97
+
98
+ # Iterate backwards from the maturity date to the settlement date
99
+ while coupon_date >= from_date:
100
+ coupon_dates.append(coupon_date)
101
+ # Move the coupon date back 6 months
102
+ coupon_date -= pd.DateOffset(months=6)
103
+
104
+ # Convert the list to a pandas Series
105
+ coupon_dates = pd.Series(coupon_dates)
106
+
107
+ # Sort the coupon dates in ascending order
108
+ coupon_dates = coupon_dates.sort_values(ignore_index=True)
109
+
110
+ # Force a index reset to avoid issues with the index
111
+ return coupon_dates.reset_index(drop=True)
112
+
113
+
114
+ def quotation(
115
+ settlement_date: str | pd.Timestamp,
116
+ maturity_date: str | pd.Timestamp,
117
+ discount_rate: float,
118
+ ) -> float:
119
+ """
120
+ Calculate the NTN-B quotation in base 100 using Anbima rules.
121
+
122
+ Parameters:
123
+ settlement_date (str | pd.Timestamp): The settlement date in 'DD-MM-YYYY' format
124
+ or a pandas Timestamp.
125
+ maturity_date (str | pd.Timestamp): The maturity date in 'DD-MM-YYYY' format or
126
+ a pandas Timestamp.
127
+ discount_rate (float): The discount rate used to calculate the present value of
128
+ the cash flows, which is the yield to maturity (YTM) of the NTN-B.
129
+
130
+ Returns:
131
+ float: The NTN-B quotation truncated to 4 decimal places.
132
+
133
+ References:
134
+ - https://www.anbima.com.br/data/files/A0/02/CC/70/8FEFC8104606BDC8B82BA2A8/Metodologias%20ANBIMA%20de%20Precificacao%20Titulos%20Publicos.pdf
135
+ - The semi-annual coupon is set to 2.956301, which represents a 6% annual
136
+ coupon rate compounded semi-annually and rounded to 6 decimal places as per
137
+ Anbima rules.
138
+
139
+ Examples:
140
+ >>> quotation("31-05-2024", "15-05-2035", 0.061490)
141
+ 99.3651
142
+ >>> quotation("31-05-2024", "15-08-2060", 0.061878)
143
+ 99.5341
144
+ """
145
+ # Semi-annual coupon values are in base 100 and rounded to 6 decimal places
146
+ INTER_PMT = round(100 * COUPON, 6)
147
+ FINAL_PMT = round(100 + INTER_PMT, 6)
148
+
149
+ # Validate and normalize dates
150
+ settlement_date = dv.normalize_date(settlement_date)
151
+ maturity_date = dv.normalize_date(maturity_date)
152
+
153
+ # Create a Series with the coupon dates
154
+ payment_dates = pd.Series(coupon_dates(settlement_date, maturity_date))
155
+
156
+ # Calculate the number of business days between settlement and cash flow dates
157
+ bdays = bday.count_bdays(settlement_date, payment_dates)
158
+
159
+ # Set the cash flow at maturity to 100, otherwise set it to the coupon
160
+ cf = np.where(payment_dates == maturity_date, FINAL_PMT, INTER_PMT)
161
+
162
+ # Calculate the number of periods truncated to 14 decimal places
163
+ n = truncate(bdays / 252, 14)
164
+
165
+ # Calculate the present value of each cash flow (DCF) rounded to 10 decimal places
166
+ dcf = (cf / (1 + discount_rate) ** n).round(10)
167
+
168
+ # Return the quotation (the dcf sum) truncated to 4 decimal places
169
+ return truncate(dcf.sum(), 4)
170
+
171
+
172
+ def spot_rates(
173
+ settlement_date: str | pd.Timestamp,
174
+ maturity_dates: pd.Series,
175
+ ytm_rates: pd.Series,
176
+ ) -> pd.DataFrame:
177
+ """
178
+ Calculates the spot rates for NTN-B bonds based on given settlement date, maturity
179
+ dates and YTM rates.
180
+
181
+ Parameters:
182
+ settlement_date (str | pd.Timestamp): The reference date for settlement.
183
+ maturity_dates (pd.Series): Series of maturity dates for the bonds.
184
+ ytm_rates (pd.Series): Series of Yield to Maturity rates corresponding to the
185
+ maturity dates.
186
+
187
+ Returns:
188
+ pd.DataFrame: DataFrame containing the maturity dates and corresponding spot
189
+ rates.
190
+
191
+ Notes:
192
+ To facilitate code reading, the following naming convention is used:
193
+ - The output DataFrame is named 'df', which is the main DataFrame.
194
+ - Variables that starts with 's_' are Series
195
+ - Variables that starts with 'df_' are DataFrames
196
+
197
+ The calculation of the spot rates for NTN-B bonds considers the following steps:
198
+ - Generate all payment dates for the NTN-B bonds.
199
+ - Interpolate the YTM rates where necessary.
200
+ - Calculate the NTN-B quotation for each maturity date.
201
+ - Calculate the spot rates for each maturity date.
202
+ """
203
+ # COUPON = (1.06) ** 0.5 - 1 # Coupon without rounding
204
+ # Validate and normalize the settlement date
205
+ settlement_date = dv.normalize_date(settlement_date)
206
+
207
+ # Create a temporary DataFrame to sort the input arguments by the number of bdays
208
+ bdays = bday.count_bdays(settlement_date, maturity_dates)
209
+ dft = pd.DataFrame({"BDays": bdays, "YTM": ytm_rates})
210
+
211
+ # Sort the DataFrame by the number of business days
212
+ dft.sort_values(by="BDays", ignore_index=True, inplace=True)
213
+
214
+ # Create lists with the ordered bdays and ytms for interpolation
215
+ ordered_bdays = dft["BDays"].to_list()
216
+ ordered_ytms = dft["YTM"].to_list()
217
+
218
+ # Generate coupon dates and initialize the main DataFrame
219
+ longest_ntnb = maturity_dates.max()
220
+ coupon_dates_all = coupon_dates_map(settlement_date, longest_ntnb)
221
+ df = pd.DataFrame(coupon_dates_all, columns=["MaturityDate"])
222
+
223
+ # Add auxiliary columns for calculations
224
+ df["BDays"] = bday.count_bdays(settlement_date, df["MaturityDate"])
225
+ df["YTM"] = 0.0
226
+ df["SpotRate"] = 0.0
227
+
228
+ # Main loop to calculate spot rates
229
+ for index in df.index:
230
+ maturity_date = df.at[index, "MaturityDate"]
231
+ # Get the coupon dates for the bond without the last one (principal + coupon)
232
+ coupon_dates_wo_last = coupon_dates(settlement_date, maturity_date)[:-1] # noqa
233
+
234
+ # Create a local DataFrame with a subset of the main DataFrame
235
+ dfl = df.query("MaturityDate in @coupon_dates_wo_last").reset_index(drop=True)
236
+
237
+ # Create the Series that will be used to calculate the discounted cash flows
238
+ cfs = pd.Series(COUPON, index=dfl.index)
239
+ spot_rates = dfl["SpotRate"]
240
+ periods = dfl["BDays"] / 252
241
+
242
+ # Calculate the present value of the cash flows (discounted cash flows)
243
+ dcfs = cfs / (1 + spot_rates) ** periods
244
+
245
+ # Interpolate YTM and calculate spot rate
246
+ bd = df.at[index, "BDays"]
247
+ ytm = ip.find_and_interpolate_flat_forward(bd, ordered_bdays, ordered_ytms)
248
+ ntnb_quotation = quotation(settlement_date, maturity_date, ytm) / 100
249
+ spot_rate = ((COUPON + 1) / (ntnb_quotation - dcfs.sum())) ** (252 / bd) - 1
250
+
251
+ # Update DataFrame with calculated values
252
+ df.at[index, "SpotRate"] = spot_rate
253
+ df.at[index, "YTM"] = ytm
254
+
255
+ # Drop the BDays column and return the final DataFrame
256
+ df = (
257
+ df.drop(columns=["BDays"])
258
+ .query("MaturityDate in @maturity_dates")
259
+ .reset_index(drop=True)
260
+ )
261
+ return df
@@ -15,7 +15,7 @@ def _get_anbima_content(reference_date: pd.Timestamp) -> str:
15
15
 
16
16
  # Tries to access the member URL first
17
17
  try:
18
- response = requests.get(member_url)
18
+ response = requests.get(member_url, timeout=5)
19
19
  # Checks if the response was successful (status code 200)
20
20
  response.raise_for_status()
21
21
  return response.text
@@ -25,7 +25,7 @@ def _get_anbima_content(reference_date: pd.Timestamp) -> str:
25
25
 
26
26
  # If the member URL fails, tries to access the non-member URL
27
27
  try:
28
- response = requests.get(non_member_url)
28
+ response = requests.get(non_member_url, timeout=5)
29
29
  response.raise_for_status() # Checks if the second attempt was successful
30
30
  return response.text
31
31
  except requests.exceptions.RequestException:
@@ -32,7 +32,7 @@ dependencies = [
32
32
  "requests>=2.31.0",
33
33
  ]
34
34
  dynamic = []
35
- version = "0.7.13"
35
+ version = "0.8.0"
36
36
 
37
37
  [project.license]
38
38
  file = "LICENSE"
@@ -54,12 +54,16 @@ dev = [
54
54
  "mypy",
55
55
  ]
56
56
 
57
- [tool.ruff.lint]
57
+ [tool.ruff]
58
58
  select = [
59
59
  "E",
60
+ "W",
60
61
  "F",
61
- "UP",
62
62
  "B",
63
- "SIM",
64
- "I",
63
+ "C",
64
+ "Q",
65
+ "S",
65
66
  ]
67
+
68
+ [tool.ruff.format]
69
+ docstring-code-format = true
@@ -1 +0,0 @@
1
- __version__ = "0.7.13"
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