PYield 0.33.2__tar.gz → 0.34.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 (51) hide show
  1. {pyield-0.33.2 → pyield-0.34.0}/PKG-INFO +1 -1
  2. pyield-0.34.0/pyield/__about__.py +1 -0
  3. {pyield-0.33.2 → pyield-0.34.0}/pyield/bc/__init__.py +4 -2
  4. pyield-0.34.0/pyield/bc/trades_intraday.py +219 -0
  5. pyield-0.33.2/pyield/bc/trade.py → pyield-0.34.0/pyield/bc/trades_monthly.py +19 -18
  6. {pyield-0.33.2 → pyield-0.34.0}/pyield/fwd.py +30 -13
  7. {pyield-0.33.2 → pyield-0.34.0}/pyield/interpolator.py +61 -20
  8. pyield-0.33.2/pyield/__about__.py +0 -1
  9. {pyield-0.33.2 → pyield-0.34.0}/.gitignore +0 -0
  10. {pyield-0.33.2 → pyield-0.34.0}/LICENSE +0 -0
  11. {pyield-0.33.2 → pyield-0.34.0}/README.md +0 -0
  12. {pyield-0.33.2 → pyield-0.34.0}/pyield/__init__.py +0 -0
  13. {pyield-0.33.2 → pyield-0.34.0}/pyield/anbima/__init__.py +0 -0
  14. {pyield-0.33.2 → pyield-0.34.0}/pyield/anbima/ettj.py +0 -0
  15. {pyield-0.33.2 → pyield-0.34.0}/pyield/anbima/ima.py +0 -0
  16. {pyield-0.33.2 → pyield-0.34.0}/pyield/anbima/imaq.py +0 -0
  17. {pyield-0.33.2 → pyield-0.34.0}/pyield/anbima/ipca.py +0 -0
  18. {pyield-0.33.2 → pyield-0.34.0}/pyield/anbima/tpf.py +0 -0
  19. {pyield-0.33.2 → pyield-0.34.0}/pyield/b3/__init__.py +0 -0
  20. {pyield-0.33.2 → pyield-0.34.0}/pyield/b3/di_over.py +0 -0
  21. {pyield-0.33.2 → pyield-0.34.0}/pyield/b3/dif.py +0 -0
  22. {pyield-0.33.2 → pyield-0.34.0}/pyield/b3/futures/__init__.py +0 -0
  23. {pyield-0.33.2 → pyield-0.34.0}/pyield/b3/futures/common.py +0 -0
  24. {pyield-0.33.2 → pyield-0.34.0}/pyield/b3/futures/historical.py +0 -0
  25. {pyield-0.33.2 → pyield-0.34.0}/pyield/b3/futures/intraday.py +0 -0
  26. {pyield-0.33.2 → pyield-0.34.0}/pyield/b3/futures/xml.py +0 -0
  27. {pyield-0.33.2 → pyield-0.34.0}/pyield/bc/auction.py +0 -0
  28. {pyield-0.33.2 → pyield-0.34.0}/pyield/bc/bcdata.py +0 -0
  29. {pyield-0.33.2 → pyield-0.34.0}/pyield/bc/ptax.py +0 -0
  30. {pyield-0.33.2 → pyield-0.34.0}/pyield/bc/repo.py +0 -0
  31. {pyield-0.33.2 → pyield-0.34.0}/pyield/bc/vna.py +0 -0
  32. {pyield-0.33.2 → pyield-0.34.0}/pyield/bday.py +0 -0
  33. {pyield-0.33.2 → pyield-0.34.0}/pyield/conftest.py +0 -0
  34. {pyield-0.33.2 → pyield-0.34.0}/pyield/data_cache.py +0 -0
  35. {pyield-0.33.2 → pyield-0.34.0}/pyield/date_converter.py +0 -0
  36. {pyield-0.33.2 → pyield-0.34.0}/pyield/holidays/__init__.py +0 -0
  37. {pyield-0.33.2 → pyield-0.34.0}/pyield/holidays/br_holidays_new.txt +0 -0
  38. {pyield-0.33.2 → pyield-0.34.0}/pyield/holidays/br_holidays_old.txt +0 -0
  39. {pyield-0.33.2 → pyield-0.34.0}/pyield/holidays/brholidays.py +0 -0
  40. {pyield-0.33.2 → pyield-0.34.0}/pyield/ibge/__init__.py +0 -0
  41. {pyield-0.33.2 → pyield-0.34.0}/pyield/ibge/ipca.py +0 -0
  42. {pyield-0.33.2 → pyield-0.34.0}/pyield/py.typed +0 -0
  43. {pyield-0.33.2 → pyield-0.34.0}/pyield/retry.py +0 -0
  44. {pyield-0.33.2 → pyield-0.34.0}/pyield/tpf/__init__.py +0 -0
  45. {pyield-0.33.2 → pyield-0.34.0}/pyield/tpf/lft.py +0 -0
  46. {pyield-0.33.2 → pyield-0.34.0}/pyield/tpf/ltn.py +0 -0
  47. {pyield-0.33.2 → pyield-0.34.0}/pyield/tpf/ntnb.py +0 -0
  48. {pyield-0.33.2 → pyield-0.34.0}/pyield/tpf/ntnc.py +0 -0
  49. {pyield-0.33.2 → pyield-0.34.0}/pyield/tpf/ntnf.py +0 -0
  50. {pyield-0.33.2 → pyield-0.34.0}/pyield/tpf/tools.py +0 -0
  51. {pyield-0.33.2 → pyield-0.34.0}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PYield
3
- Version: 0.33.2
3
+ Version: 0.34.0
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.34.0"
@@ -9,7 +9,8 @@ from pyield.bc.bcdata import (
9
9
  )
10
10
  from pyield.bc.ptax import ptax_series
11
11
  from pyield.bc.repo import repos
12
- from pyield.bc.trade import tpf_trades
12
+ from pyield.bc.trades_intraday import fpd_intraday_trades
13
+ from pyield.bc.trades_monthly import fpd_monthly_trades
13
14
  from pyield.bc.vna import vna_lft
14
15
 
15
16
  __all__ = [
@@ -18,7 +19,8 @@ __all__ = [
18
19
  "di_over_series",
19
20
  "ptax_series",
20
21
  "repos",
21
- "tpf_trades",
22
+ "fpd_monthly_trades",
23
+ "fpd_intraday_trades",
22
24
  "selic_over",
23
25
  "selic_over_series",
24
26
  "selic_target",
@@ -0,0 +1,219 @@
1
+ import datetime as dt
2
+ import io
3
+ import logging
4
+ from pathlib import Path
5
+ from zoneinfo import ZoneInfo
6
+
7
+ import pandas as pd
8
+ import requests
9
+
10
+ from pyield import bday
11
+
12
+ BZ_TIMEZONE = ZoneInfo("America/Sao_Paulo")
13
+ REALTIME_START_TIME = dt.time(9, 0, 0)
14
+ REALTIME_END_TIME = dt.time(22, 0, 0)
15
+
16
+ logger = logging.getLogger(__name__)
17
+ test_file = Path(__file__).parent.parent.parent / "tests/data/negocios-registrados.csv"
18
+
19
+
20
+ def _fetch_csv_from_url() -> str:
21
+ FILE_URL = "https://www3.bcb.gov.br/novoselic/NegociosRegistradosDownload"
22
+ r = requests.get(FILE_URL, timeout=30) # API usually takes 10s to respond
23
+ r.raise_for_status()
24
+ r.encoding = "iso-8859-15"
25
+ return r.text
26
+
27
+
28
+ def _clean_csv(text: str) -> str:
29
+ """Clean the CSV text data by removing unnecessary rows."""
30
+ rows = text.splitlines()
31
+ valid_rows = [row for row in rows if row.startswith("1;")]
32
+ return "\n".join(valid_rows)
33
+
34
+
35
+ def _convert_csv_to_df(text: str) -> pd.DataFrame:
36
+ return pd.read_csv(
37
+ io.StringIO(text),
38
+ sep=";",
39
+ decimal=",",
40
+ thousands=".",
41
+ dtype_backend="numpy_nullable",
42
+ header=None,
43
+ na_values="-",
44
+ )
45
+
46
+
47
+ def _process_df(df: pd.DataFrame) -> pd.DataFrame:
48
+ col_names_by_index = {
49
+ 0: "RowType", # column indicating row type (filtered with "1")
50
+ 1: "SelicCode", # código título
51
+ 2: "MaturityDate", # data vencimento
52
+ 3: "BondType", # sigla
53
+ 4: "LastPrice", # pu último (mercado à vista)
54
+ 5: "LastRate", # tx último (mercado à vista)
55
+ 6: "MinPrice", # pu mínimo (mercado à vista)
56
+ 7: "MinRate", # tx mínimo (mercado à vista)
57
+ 8: "AvgPrice", # pu médio (mercado à vista)
58
+ 9: "AvgRate", # tx médio (mercado à vista)
59
+ 10: "MaxPrice", # pu máximo (mercado à vista)
60
+ 11: "MaxRate", # tx máximo (mercado à vista)
61
+ 12: "Trades", # totais liquidados operações (mercado à vista)
62
+ 13: "BrokeredTrades", # corretagem liquidados operações (merc, à vista)
63
+ 14: "Quantity", # títulos (mercado à vista)
64
+ 15: "BrokeredQuantity", # corretagem títulos (mercado à vista)
65
+ 16: "Volume", # financeiro (mercado à vista)
66
+ 17: "ForwardLastPrice", # pu último (mercado a termo)
67
+ 18: "ForwardLastRate", # tx último (mercado a termo)
68
+ 19: "ForwardMinPrice", # pu mínimo (mercado a termo)
69
+ 20: "ForwardMinRate", # tx mínimo (mercado a termo)
70
+ 21: "ForwardAvgPrice", # pu médio (mercado a termo)
71
+ 22: "ForwardAvgRate", # tx médio (mercado a termo)
72
+ 23: "ForwardMaxPrice", # pu máximo (mercado a termo)
73
+ 24: "ForwardMaxRate", # tx máximo (mercado a termo)
74
+ 25: "ForwardTrades", # totais contratados operações (mercado a termo)
75
+ 26: "ForwardBrokeredTrades", # corretagem contratados operações (merc. a termo)
76
+ 27: "ForwardQuantity", # títulos (mercado a termo)
77
+ 28: "ForwardBrokeredQuantity", # corretagem titulos (mercado a termo)
78
+ 29: "ForwardVolume", # financeiro (mercado a termo)
79
+ }
80
+ df = df.rename(columns=col_names_by_index)
81
+
82
+ df["BondType"] = df["BondType"].str.strip()
83
+ df["MaturityDate"] = pd.to_datetime(df["MaturityDate"], format="%d-%m-%Y")
84
+ today = dt.datetime.now(BZ_TIMEZONE).date()
85
+ df["SettlementDate"] = pd.Timestamp(today)
86
+
87
+ # Remove percentage from rate columns
88
+ rate_cols = [col for col in df.columns if "Rate" in col]
89
+ for col in rate_cols:
90
+ df[col] = (df[col] / 100).round(6)
91
+
92
+ return df
93
+
94
+
95
+ def _reorder_columns(df: pd.DataFrame) -> pd.DataFrame:
96
+ reorder_columns = [
97
+ # "RowType",
98
+ "SettlementDate",
99
+ "BondType",
100
+ "SelicCode",
101
+ "MaturityDate",
102
+ "MinPrice",
103
+ "AvgPrice",
104
+ "MaxPrice",
105
+ "LastPrice",
106
+ "MinRate",
107
+ "AvgRate",
108
+ "MaxRate",
109
+ "LastRate",
110
+ "Trades",
111
+ "Quantity",
112
+ "Volume",
113
+ "BrokeredTrades",
114
+ "BrokeredQuantity",
115
+ "ForwardMinPrice",
116
+ "ForwardAvgPrice",
117
+ "ForwardLastPrice",
118
+ "ForwardMaxPrice",
119
+ "ForwardLastRate",
120
+ "ForwardMinRate",
121
+ "ForwardAvgRate",
122
+ "ForwardMaxRate",
123
+ "ForwardTrades",
124
+ "ForwardQuantity",
125
+ "ForwardVolume",
126
+ "ForwardBrokeredTrades",
127
+ "ForwardBrokeredQuantity",
128
+ ]
129
+
130
+ column_order = [col for col in reorder_columns if col in df.columns]
131
+ return df[column_order].copy()
132
+
133
+
134
+ def is_selic_open() -> bool:
135
+ """Verifica se o mercado está aberto no momento."""
136
+ now = dt.datetime.now(BZ_TIMEZONE)
137
+ today = now.date()
138
+ time = now.time()
139
+ is_last_bday = bday.is_business_day(today)
140
+ is_trading_time = REALTIME_START_TIME <= time <= REALTIME_END_TIME
141
+
142
+ return is_last_bday and is_trading_time
143
+
144
+
145
+ def fpd_intraday_trades() -> pd.DataFrame:
146
+ """Fetches real-time secondary trading data for domestic Federal Public Debt (FPD)
147
+ from the Central Bank of Brazil (BCB).
148
+
149
+ This function checks if the SELIC market is currently open based on Brazil/Sao_Paulo
150
+ timezone business days and trading hours (defined by REALTIME_START_TIME and
151
+ REALTIME_END_TIME). If the market is closed, or if no data is available from the
152
+ source, or if an error occurs during fetching or processing, an empty DataFrame
153
+ is returned. Otherwise, it retrieves, cleans, and processes the intraday trade
154
+ data provided by BCB for Brazilian government bonds.
155
+
156
+ Returns:
157
+ pd.DataFrame: A DataFrame containing the latest intraday trades for FPD
158
+ securities. Returns an empty DataFrame if the market is closed, no data
159
+ is found, or an error occurs. The DataFrame includes the following columns:
160
+
161
+ * `SettlementDate`: The reference date for the spot market
162
+ trading activity reported in this dataset (the current
163
+ business day). Forward trades listed have future settlement dates
164
+ not specified here.
165
+ * `BondType`: Abbreviation/ticker for the bond type (e.g., LFT,
166
+ LTN, NTN-B).
167
+ * `SelicCode`: The unique SELIC code identifying the specific bond issue.
168
+ * `MaturityDate`: The maturity date of the bond.
169
+
170
+ **Spot Market Data:**
171
+ * `MinPrice`: Minimum traded price.
172
+ * `AvgPrice`: Average traded price.
173
+ * `MaxPrice`: Maximum traded price.
174
+ * `LastPrice`: Last traded price.
175
+ * `MinRate`: Minimum traded yield/rate (as a decimal, e.g., 0.11 for 11%).
176
+ * `AvgRate`: Average traded yield/rate (as a decimal).
177
+ * `MaxRate`: Maximum traded yield/rate (as a decimal).
178
+ * `LastRate`: Last traded yield/rate (as a decimal).
179
+ * `Trades`: Total number of trades settled.
180
+ * `Quantity`: Total number of bonds traded (quantity).
181
+ * `Volume`: Total financial volume traded (in BRL).
182
+ * `BrokeredTrades`: Number of brokered trades settled.
183
+ * `BrokeredQuantity`: Quantity of bonds traded via brokers.
184
+
185
+ **Forward Market Data:**
186
+ * `ForwardMinPrice`: Minimum traded price.
187
+ * `ForwardAvgPrice`: Average traded price.
188
+ * `ForwardMaxPrice`: Maximum traded price.
189
+ * `ForwardLastPrice`: Last traded price.
190
+ * `ForwardMinRate`: Minimum traded yield/rate (decimal).
191
+ * `ForwardAvgRate`: Average traded yield/rate (decimal).
192
+ * `ForwardMaxRate`: Maximum traded yield/rate (decimal).
193
+ * `ForwardLastRate`: Last traded yield/rate (decimal).
194
+ * `ForwardTrades`: Total number of trades contracted.
195
+ * `ForwardQuantity`: Total number of bonds traded (quantity).
196
+ * `ForwardVolume`: Total financial volume traded (in BRL).
197
+ * `ForwardBrokeredTrades`: Number of brokered trades contracted.
198
+ * `ForwardBrokeredQuantity`: Quantity of bonds traded via brokers.
199
+ """
200
+ if not is_selic_open():
201
+ logger.info("Market is closed. Returning empty DataFrame.")
202
+ return pd.DataFrame()
203
+
204
+ try:
205
+ raw_text = _fetch_csv_from_url()
206
+ # raw_text = test_file.read_text(encoding="iso-8859-15")
207
+ cleaned_text = _clean_csv(raw_text)
208
+ if not cleaned_text:
209
+ logger.warning("No data found in the FPD intraday trades.")
210
+ return pd.DataFrame()
211
+ df = _convert_csv_to_df(cleaned_text)
212
+ df = _process_df(df)
213
+ df = _reorder_columns(df)
214
+ volume = df["Volume"].sum() / 10**9
215
+ logger.info(f"Fetched {volume:,.1f} billion BRL in FPD intraday trades.")
216
+ return df
217
+ except Exception:
218
+ logger.exception("Error fetching data from BCB. Returning empty DataFrame.")
219
+ return pd.DataFrame()
@@ -15,10 +15,10 @@ COLUMN_MAPPING = {
15
15
  "CODIGO": "SelicCode",
16
16
  "CODIGO ISIN": "ISIN",
17
17
  "EMISSAO": "IssueDate",
18
- "VENCIMENTO": "Maturity",
19
- "NUM DE OPER": "TradeCount",
20
- "QUANT NEGOCIADA": "TradeQuantity",
21
- "VALOR NEGOCIADO": "TradeValue",
18
+ "VENCIMENTO": "MaturityDate",
19
+ "NUM DE OPER": "Trades",
20
+ "QUANT NEGOCIADA": "Quantity",
21
+ "VALOR NEGOCIADO": "Volume",
22
22
  "PU MIN": "MinPrice",
23
23
  "PU MED": "AvgPrice",
24
24
  "PU MAX": "MaxPrice",
@@ -27,8 +27,8 @@ COLUMN_MAPPING = {
27
27
  "TAXA MIN": "MinRate",
28
28
  "TAXA MED": "AvgRate",
29
29
  "TAXA MAX": "MaxRate",
30
- "NUM OPER COM CORRETAGEM": "BrokerageTradeCount",
31
- "QUANT NEG COM CORRETAGEM": "BrokerageTradeQuantity",
30
+ "NUM OPER COM CORRETAGEM": "BrokerageTrades",
31
+ "QUANT NEG COM CORRETAGEM": "BrokerageQuantity",
32
32
  }
33
33
 
34
34
 
@@ -63,9 +63,11 @@ def _fetch_data_from_url(file_url: str) -> pd.DataFrame:
63
63
  return df
64
64
 
65
65
 
66
- def tpf_trades(target_date: DateScalar, all_operations: bool = True) -> pd.DataFrame:
67
- """Fetches monthly secondary trading data for the 'títulos públicos federais' (TPF)
68
- registered in the Brazilian Central Bank (BCB) system.
66
+ def fpd_monthly_trades(
67
+ target_date: DateScalar, all_operations: bool = True
68
+ ) -> pd.DataFrame:
69
+ """Fetches monthly secondary trading data for the domestic 'Federal Public Debt'
70
+ (FPD) registered in the Brazilian Central Bank (BCB) Selic system.
69
71
 
70
72
  Downloads the monthly bond trading data from the Brazilian Central Bank (BCB)
71
73
  website for the month corresponding to the provided date. The data is downloaded
@@ -90,30 +92,29 @@ def tpf_trades(target_date: DateScalar, all_operations: bool = True) -> pd.DataF
90
92
  - SelicCode: Unique code in the SELIC system
91
93
  - ISIN: International Securities Identification Number
92
94
  - IssueDate: Date when the security was issued
93
- - Maturity: Security's maturity date
94
- - TradeCount: Number of trades executed
95
- - TradeQuantity: Quantity traded
96
- - TradeValue: Total value traded
95
+ - MaturityDate: Security's maturity date
96
+ - Trades: Number of trades executed
97
+ - Quantity: Quantity traded
98
+ - Volume: Total value traded
97
99
  - AvgPrice: Average price
98
100
  - AvgRate: Average rate
99
101
  And additional trading metrics like min/max prices and rates.
100
102
 
101
103
  Examples:
102
104
  >>> from pyield import bc
103
- >>> df = bc.tpf_trades("07-01-2025") # Returns all trades for January 2025
105
+ >>> df = bc.fpd_monthly_trades("07-01-2025") # Returns all trades for Jan/2025
104
106
 
105
107
  Notes:
106
108
  Transactions are considered off-group when the transferring counterparty's
107
109
  conglomerate is different from the receiving counterparty's conglomerate,
108
110
  or when at least one of the counterparties does not belong to a conglomerate.
109
111
  In the case of funds, the conglomerate considered is that of the administrator.
110
-
111
112
  """
112
113
  filename = _build_filename(target_date, all_operations)
113
- logger.info(f"Fetching TPF trades for {target_date} from BCB")
114
+ logger.info(f"Fetching FPD trades for {target_date} from BCB")
114
115
  url = f"{BASE_URL}/{filename}"
115
116
  df = _fetch_data_from_url(url)
116
117
  df = df.rename(columns=COLUMN_MAPPING)
117
- # TradeValue are empty in the original BCB file, so we calculate it
118
- df["TradeValue"] = (df["TradeQuantity"] * df["AvgPrice"]).round(2)
118
+ # Volume are empty in the original BCB file, so we calculate it
119
+ df["Volume"] = (df["Quantity"] * df["AvgPrice"]).round(2)
119
120
  return df
@@ -69,8 +69,19 @@ def forwards(
69
69
  2 0.090284
70
70
  dtype: Float64
71
71
 
72
+ >>> # Exemplo com agrupamento (a última está isolada em outro grupo)
73
+ >>> groupby_dates = pd.Series([1, 1, 2])
74
+ >>> yd.forwards(bdays, rates, groupby_dates)
75
+ 0 0.05
76
+ 1 0.070095
77
+ 2 0.07
78
+ dtype: Float64
79
+
72
80
  Note:
73
- A função retorna uma série com o mesmo índice que `bdays` e `rates`.
81
+ - A função ordena os dados de entrada primeiro por `groupby_dates`,
82
+ se for fornecido, e depois por `bdays` para garantir a ordem cronológica
83
+ correta no cálculo das taxas a termo.
84
+ - Os resultados são retornados na mesma ordem dos dados de entrada.
74
85
  """ # noqa: E501
75
86
  bdays = bdays.astype("Int64")
76
87
  rates = rates.astype("Float64")
@@ -79,9 +90,12 @@ def forwards(
79
90
  if not bdays.index.equals(rates.index):
80
91
  raise ValueError("The indexes of bdays and rates must be the same.")
81
92
 
93
+ # Store original index
94
+ original_index = bdays.index
95
+
82
96
  # Create a DataFrame to work with the given series
83
- df = pd.DataFrame({"duk": bdays, "rk": rates})
84
- df["tk"] = df["duk"] / 252
97
+ df = pd.DataFrame({"du_k": bdays, "rate_k": rates})
98
+ df["time_k"] = df["du_k"] / 252
85
99
 
86
100
  if isinstance(groupby_dates, pd.Series):
87
101
  if not groupby_dates.index.equals(bdays.index):
@@ -91,27 +105,30 @@ def forwards(
91
105
  df["groupby_date"] = 0 # Dummy value to group the DataFrame
92
106
 
93
107
  # Sort by the groupby_dates and t2 columns to ensure proper chronological order
94
- df.sort_values(by=["groupby_date", "tk"], inplace=True)
108
+ df = df.sort_values(by=["groupby_date", "time_k"])
95
109
 
96
110
  # Calculate the next zero rate and business day for each group
97
- df["rj"] = df.groupby("groupby_date")["rk"].shift(1)
98
- df["tj"] = df.groupby("groupby_date")["tk"].shift(1)
111
+ df["rate_j"] = df.groupby("groupby_date")["rate_k"].shift(1)
112
+ df["time_j"] = df.groupby("groupby_date")["time_k"].shift(1)
99
113
 
100
114
  # Calculate the formula components
101
115
  # fₖ = fⱼ→ₖ = ((1 + rₖ)^tₖ / (1 + rⱼ)^tⱼ) ^ (1/(tₖ - tⱼ)) - 1
102
- factor_rk = (1 + df["rk"]) ** df["tk"] # (1 + rₖ)^tₖ
103
- factor_rj = (1 + df["rj"]) ** df["tj"] # (1 + rⱼ)^tⱼ
104
- time_factor = 1 / (df["tk"] - df["tj"]) # 1/(tₖ - tⱼ)
105
- df["fwd"] = (factor_rk / factor_rj) ** time_factor - 1
116
+ factor_k = (1 + df["rate_k"]) ** df["time_k"] # (1 + rₖ)^tₖ
117
+ factor_j = (1 + df["rate_j"]) ** df["time_j"] # (1 + rⱼ)^tⱼ
118
+ factor_t = 1 / (df["time_k"] - df["time_j"]) # 1/(tₖ - tⱼ)
119
+ df["fwd"] = (factor_k / factor_j) ** factor_t - 1
106
120
 
107
121
  # Identifify the first index of each group of dates
108
122
  first_indices = df.groupby("groupby_date").head(1).index
109
123
  # Set the first forward rate of each group to the zero rate
110
- df.loc[first_indices, "fwd"] = df.loc[first_indices, "rk"]
124
+ df.loc[first_indices, "fwd"] = df.loc[first_indices, "rate_k"]
125
+
126
+ # Reindex the result to match the original input order
127
+ result_fwd = df["fwd"].reindex(original_index)
111
128
 
112
129
  # Return the forward rates as a Series with no name
113
- df["fwd"].name = None
114
- return df["fwd"]
130
+ result_fwd.name = None
131
+ return result_fwd
115
132
 
116
133
 
117
134
  def forward(
@@ -32,13 +32,13 @@ class Interpolator:
32
32
  >>> known_rates = [0.045, 0.05, 0.055]
33
33
 
34
34
  Linear interpolation example:
35
- >>> lin_interp = Interpolator("linear", known_bdays, known_rates)
36
- >>> lin_interp(45)
35
+ >>> linear = Interpolator("linear", known_bdays, known_rates)
36
+ >>> linear(45)
37
37
  0.0475
38
38
 
39
39
  Flat forward interpolation example:
40
- >>> ffo_interp = Interpolator("flat_forward", known_bdays, known_rates)
41
- >>> ffo_interp(45)
40
+ >>> fforward = Interpolator("flat_forward", known_bdays, known_rates)
41
+ >>> fforward(45)
42
42
  0.04833068080970859
43
43
  """
44
44
 
@@ -61,18 +61,60 @@ class Interpolator:
61
61
  self._known_rates = tuple(df["rate"])
62
62
  self._extrapolate = bool(extrapolate)
63
63
 
64
- def _flat_forward(self, bday: int, i: int) -> float:
65
- """Performs the interest rate interpolation using the flat forward method."""
66
- prev_rate = self._known_rates[i - 1]
67
- prev_bday = self._known_bdays[i - 1]
68
- next_rate = self._known_rates[i]
69
- next_bday = self._known_bdays[i]
64
+ def flat_forward(self, bday: int, k: int) -> float:
65
+ r"""
66
+ Performs the interest rate interpolation using the flat forward method.
67
+
68
+ This method calculates the interpolated interest rate for a given
69
+ number of business days (`bday`) using the flat forward methodology,
70
+ based on two known points: the current point (`k`) and the previous point (`j`).
71
+
72
+ Assuming interest rates are in decimal form, the interpolated rate
73
+ is calculated. Time is measured in years based on a 252-business-day year.
74
+
75
+ The interpolated rate is given by the formula:
76
+
77
+ $$
78
+ \left(f_j*\left(\frac{f_k}{f_j}\right)^{f_t}\right)^{\frac{1}{time}}-1
79
+ $$
80
+
81
+ Where the factors used in the formula are defined as:
82
+
83
+ * `fⱼ = (1 + rateⱼ)^timeⱼ` is the compounding factor at point `j`.
84
+ * `fₖ = (1 + rateₖ)^timeₖ` is the compounding factor at point `k`.
85
+ * `fₜ = (time - timeⱼ)/(timeₖ - timeⱼ)` is the time factor.
86
+
87
+ And the variables are defined as:
88
+
89
+ * `time = bday/252` is the time in years for the interpolated point. `bday` is
90
+ the number of business days for the interpolated point (input to this method).
91
+ * `k` is the index of the current known point.
92
+ * `timeₖ = bdayₖ/252` is the time in years of point `k`.
93
+ * `rateₖ` is the interest rate (decimal) at point `k`.
94
+ * `j` is the index of the previous known point (`k - 1`).
95
+ * `timeⱼ = bdayⱼ/252` is the time in years of point `j`.
96
+ * `rateⱼ` is the interest rate (decimal) at point `j`.
97
+
98
+ Args:
99
+ bday (int): Number of bus. days for which the rate is to be interpolated.
100
+ k (int): The index in the known_bdays and known_rates arrays such that
101
+ known_bdays[k-1] < bday < known_bdays[k]. This `k` corresponds
102
+ to the index of the next known point after `bday`.
103
+
104
+ Returns:
105
+ float: The interpolated interest rate in decimal form.
106
+ """
107
+ rate_j = self._known_rates[k - 1]
108
+ time_j = self._known_bdays[k - 1] / 252
109
+ rate_k = self._known_rates[k]
110
+ time_k = self._known_bdays[k] / 252
111
+ time = bday / 252
70
112
 
71
113
  # Perform flat forward interpolation
72
- a = (1 + prev_rate) ** (prev_bday / 252)
73
- b = (1 + next_rate) ** (next_bday / 252)
74
- c = (bday - prev_bday) / (next_bday - prev_bday)
75
- return (a * (b / a) ** c) ** (252 / bday) - 1
114
+ f_j = (1 + rate_j) ** time_j
115
+ f_k = (1 + rate_k) ** time_k
116
+ f_t = (time - time_j) / (time_k - time_j)
117
+ return (f_j * (f_k / f_j) ** f_t) ** (1 / time) - 1
76
118
 
77
119
  def interpolate(self, bday: int) -> float:
78
120
  """
@@ -104,15 +146,15 @@ class Interpolator:
104
146
  if method == "linear":
105
147
  return float(np.interp(bday, known_bdays, known_rates))
106
148
 
107
- # Find i such that known_bdays[i-1] < bday < known_bdays[i]
108
- idx = bisect.bisect_left(known_bdays, bday)
149
+ # Find k such that known_bdays[k-1] < bday < known_bdays[k]
150
+ k = bisect.bisect_left(known_bdays, bday)
109
151
 
110
152
  # Check if the interpolation point is known
111
- if idx < len(known_bdays) and known_bdays[idx] == bday:
112
- return float(known_rates[idx])
153
+ if k < len(known_bdays) and known_bdays[k] == bday:
154
+ return float(known_rates[k])
113
155
 
114
156
  # Perform flat forward interpolation
115
- return float(self._flat_forward(bday, idx))
157
+ return float(self.flat_forward(bday, k))
116
158
 
117
159
  def __call__(self, bday: int) -> float:
118
160
  """
@@ -130,7 +172,6 @@ class Interpolator:
130
172
 
131
173
  def __repr__(self) -> str:
132
174
  """Textual representation, used in terminal or scripts."""
133
-
134
175
  return repr(self._df)
135
176
 
136
177
  def __len__(self) -> int:
@@ -1 +0,0 @@
1
- __version__ = "0.33.02"
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