PYield 0.40.6__tar.gz → 0.41.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.40.6 → pyield-0.41.0}/.gitignore +0 -1
- {pyield-0.40.6 → pyield-0.41.0}/PKG-INFO +17 -21
- {pyield-0.40.6 → pyield-0.41.0}/README.md +16 -20
- pyield-0.41.0/pyield/__about__.py +1 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/__init__.py +3 -1
- {pyield-0.40.6 → pyield-0.41.0}/pyield/b3/di1.py +8 -6
- {pyield-0.40.6 → pyield-0.41.0}/pyield/interpolator.py +54 -10
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/auctions.py +29 -28
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/lft.py +24 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/ntnb.py +39 -26
- pyield-0.41.0/pyield/tn/ntnb1.py +345 -0
- pyield-0.41.0/pyield/tn/ntnbprinc.py +80 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/ntnf.py +9 -13
- pyield-0.40.6/pyield/__about__.py +0 -1
- {pyield-0.40.6 → pyield-0.41.0}/LICENSE +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/anbima/__init__.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/anbima/difusao.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/anbima/ettj_intraday.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/anbima/ettj_last.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/anbima/ima.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/anbima/imaq.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/anbima/tpf.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/b3/__init__.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/b3/di_over.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/b3/futures/__init__.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/b3/futures/common.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/b3/futures/historical.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/b3/futures/intraday.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/b3/futures/xml.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bc/__init__.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bc/auction.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bc/ptax_api.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bc/rates.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bc/repo.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bc/trades_intraday.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bc/trades_monthly.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bc/vna.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bday/__init__.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bday/core.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bday/holidays/__init__.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bday/holidays/br_holidays_new.txt +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bday/holidays/br_holidays_old.txt +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/bday/holidays/brholidays.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/config.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/conftest.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/converters.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/data_cache.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/fwd.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/ipca/__init__.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/ipca/historical.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/ipca/projected.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/py.typed +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/retry.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/__init__.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/benchmark.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/ltn.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/ntnc.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/pre.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/tn/tools.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyield/types.py +0 -0
- {pyield-0.40.6 → pyield-0.41.0}/pyproject.toml +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: PYield
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.41.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>
|
|
@@ -46,7 +46,21 @@ Description-Content-Type: text/markdown
|
|
|
46
46
|
|
|
47
47
|
# PYield: Brazilian Fixed Income Toolkit
|
|
48
48
|
|
|
49
|
-
PYield is a Python library designed for the analysis of Brazilian fixed income instruments. Leveraging the power of
|
|
49
|
+
PYield is a Python library designed for the analysis of Brazilian fixed income instruments. Leveraging the power of Polars and Requests, PYield simplifies the process of obtaining and processing data from key sources such as ANBIMA, BCB, IBGE and B3.
|
|
50
|
+
|
|
51
|
+
## Examples & Quickstart
|
|
52
|
+
|
|
53
|
+
A quickstart notebook is available in the examples/ directory and can be opened directly in Google Colab:
|
|
54
|
+
|
|
55
|
+
[](https://colab.research.google.com/github/crdcj/PYield/blob/main/examples/pyield_quickstart.ipynb)
|
|
56
|
+
|
|
57
|
+
It demonstrates:
|
|
58
|
+
|
|
59
|
+
- Package installation.
|
|
60
|
+
- Basic use of the business day calendar (bday.count, bday.offset).
|
|
61
|
+
- DI futures query (futures).
|
|
62
|
+
|
|
63
|
+
More examples may be added later (treasury bonds, curve interpolation, inflation). Contributions are welcome.
|
|
50
64
|
|
|
51
65
|
---
|
|
52
66
|
### ✅ Polars migration from version 0.40.0 onwards:
|
|
@@ -74,10 +88,9 @@ Visit the [full documentation for PYield](https://crdcj.github.io/PYield/).
|
|
|
74
88
|
|
|
75
89
|
## Overview & Navigation
|
|
76
90
|
|
|
77
|
-
PYield is split into focused namespaces. Each function and class has a rich docstring (the online site is generated from them via MkDocs). The quickest learning path is
|
|
91
|
+
PYield is split into focused namespaces. Each function and class has a rich docstring (the online site is generated from them via MkDocs). The quickest learning path is accessing the documentation and following the function/class examples verbatim.
|
|
78
92
|
|
|
79
93
|
### Top-Level Namespace (Cheat Sheet)
|
|
80
|
-
Symbols exported directly by `pyield.__all__` (available via `from pyield import ...`). Prefer these first:
|
|
81
94
|
|
|
82
95
|
| Symbol | Kind | Purpose |
|
|
83
96
|
|--------|------|---------|
|
|
@@ -98,14 +111,6 @@ Symbols exported directly by `pyield.__all__` (available via `from pyield import
|
|
|
98
111
|
| `pre` | module | Zero-coupon (pré-fixado) helpers. |
|
|
99
112
|
| `ipca` | module | Inflation historical & projections. |
|
|
100
113
|
|
|
101
|
-
|
|
102
|
-
### Learning Path
|
|
103
|
-
1. Install: `pip install pyield`.
|
|
104
|
-
2. Choose a domain: e.g. bonds (`from pyield import ntnb`).
|
|
105
|
-
3. Inspect: `dir(ntnb)` then `help(ntnb.quotation)`.
|
|
106
|
-
4. Reproduce the docstring example verbatim.
|
|
107
|
-
5. Chain outputs (Polars DataFrames / Series) into your pipeline; convert to pandas only if unavoidable.
|
|
108
|
-
|
|
109
114
|
### Minimal Quick Start
|
|
110
115
|
```python
|
|
111
116
|
from pyield import bday, ntnb, bc
|
|
@@ -122,15 +127,6 @@ selic = bc.selic_over("31-05-2024")
|
|
|
122
127
|
print(business_days, q, selic)
|
|
123
128
|
```
|
|
124
129
|
|
|
125
|
-
### Docstrings = Source of Truth
|
|
126
|
-
If any README description conflicts with behavior, prefer the docstring. It documents:
|
|
127
|
-
* Parameters & types
|
|
128
|
-
* Edge cases / null semantics
|
|
129
|
-
* References (e.g. ANBIMA methodology PDFs)
|
|
130
|
-
* Examples guaranteed to run (CI checks)
|
|
131
|
-
|
|
132
|
-
See also: [Custom Types & Data Handling](#custom-types--data-handling) for input normalization rules.
|
|
133
|
-
|
|
134
130
|
## Installation
|
|
135
131
|
|
|
136
132
|
You can install PYield using pip:
|
|
@@ -4,7 +4,21 @@
|
|
|
4
4
|
|
|
5
5
|
# PYield: Brazilian Fixed Income Toolkit
|
|
6
6
|
|
|
7
|
-
PYield is a Python library designed for the analysis of Brazilian fixed income instruments. Leveraging the power of
|
|
7
|
+
PYield is a Python library designed for the analysis of Brazilian fixed income instruments. Leveraging the power of Polars and Requests, PYield simplifies the process of obtaining and processing data from key sources such as ANBIMA, BCB, IBGE and B3.
|
|
8
|
+
|
|
9
|
+
## Examples & Quickstart
|
|
10
|
+
|
|
11
|
+
A quickstart notebook is available in the examples/ directory and can be opened directly in Google Colab:
|
|
12
|
+
|
|
13
|
+
[](https://colab.research.google.com/github/crdcj/PYield/blob/main/examples/pyield_quickstart.ipynb)
|
|
14
|
+
|
|
15
|
+
It demonstrates:
|
|
16
|
+
|
|
17
|
+
- Package installation.
|
|
18
|
+
- Basic use of the business day calendar (bday.count, bday.offset).
|
|
19
|
+
- DI futures query (futures).
|
|
20
|
+
|
|
21
|
+
More examples may be added later (treasury bonds, curve interpolation, inflation). Contributions are welcome.
|
|
8
22
|
|
|
9
23
|
---
|
|
10
24
|
### ✅ Polars migration from version 0.40.0 onwards:
|
|
@@ -32,10 +46,9 @@ Visit the [full documentation for PYield](https://crdcj.github.io/PYield/).
|
|
|
32
46
|
|
|
33
47
|
## Overview & Navigation
|
|
34
48
|
|
|
35
|
-
PYield is split into focused namespaces. Each function and class has a rich docstring (the online site is generated from them via MkDocs). The quickest learning path is
|
|
49
|
+
PYield is split into focused namespaces. Each function and class has a rich docstring (the online site is generated from them via MkDocs). The quickest learning path is accessing the documentation and following the function/class examples verbatim.
|
|
36
50
|
|
|
37
51
|
### Top-Level Namespace (Cheat Sheet)
|
|
38
|
-
Symbols exported directly by `pyield.__all__` (available via `from pyield import ...`). Prefer these first:
|
|
39
52
|
|
|
40
53
|
| Symbol | Kind | Purpose |
|
|
41
54
|
|--------|------|---------|
|
|
@@ -56,14 +69,6 @@ Symbols exported directly by `pyield.__all__` (available via `from pyield import
|
|
|
56
69
|
| `pre` | module | Zero-coupon (pré-fixado) helpers. |
|
|
57
70
|
| `ipca` | module | Inflation historical & projections. |
|
|
58
71
|
|
|
59
|
-
|
|
60
|
-
### Learning Path
|
|
61
|
-
1. Install: `pip install pyield`.
|
|
62
|
-
2. Choose a domain: e.g. bonds (`from pyield import ntnb`).
|
|
63
|
-
3. Inspect: `dir(ntnb)` then `help(ntnb.quotation)`.
|
|
64
|
-
4. Reproduce the docstring example verbatim.
|
|
65
|
-
5. Chain outputs (Polars DataFrames / Series) into your pipeline; convert to pandas only if unavoidable.
|
|
66
|
-
|
|
67
72
|
### Minimal Quick Start
|
|
68
73
|
```python
|
|
69
74
|
from pyield import bday, ntnb, bc
|
|
@@ -80,15 +85,6 @@ selic = bc.selic_over("31-05-2024")
|
|
|
80
85
|
print(business_days, q, selic)
|
|
81
86
|
```
|
|
82
87
|
|
|
83
|
-
### Docstrings = Source of Truth
|
|
84
|
-
If any README description conflicts with behavior, prefer the docstring. It documents:
|
|
85
|
-
* Parameters & types
|
|
86
|
-
* Edge cases / null semantics
|
|
87
|
-
* References (e.g. ANBIMA methodology PDFs)
|
|
88
|
-
* Examples guaranteed to run (CI checks)
|
|
89
|
-
|
|
90
|
-
See also: [Custom Types & Data Handling](#custom-types--data-handling) for input normalization rules.
|
|
91
|
-
|
|
92
88
|
## Installation
|
|
93
89
|
|
|
94
90
|
You can install PYield using pip:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.41.0"
|
|
@@ -5,7 +5,7 @@ from pyield.__about__ import __version__
|
|
|
5
5
|
from pyield.b3 import di1, futures
|
|
6
6
|
from pyield.fwd import forward, forwards
|
|
7
7
|
from pyield.interpolator import Interpolator
|
|
8
|
-
from pyield.tn import lft, ltn, ntnb, ntnc, ntnf, pre
|
|
8
|
+
from pyield.tn import lft, ltn, ntnb, ntnb1, ntnbprinc, ntnc, ntnf, pre
|
|
9
9
|
|
|
10
10
|
__all__ = [
|
|
11
11
|
"__version__",
|
|
@@ -23,6 +23,8 @@ __all__ = [
|
|
|
23
23
|
"lft",
|
|
24
24
|
"ltn",
|
|
25
25
|
"ntnb",
|
|
26
|
+
"ntnbprinc",
|
|
27
|
+
"ntnb1",
|
|
26
28
|
"ntnc",
|
|
27
29
|
"ntnf",
|
|
28
30
|
"pre",
|
|
@@ -132,8 +132,8 @@ def data(
|
|
|
132
132
|
.filter(pl.col("BondType").is_in(["LTN", "NTN-F"]))
|
|
133
133
|
.unique(subset=["ReferenceDate", "MaturityDate"])
|
|
134
134
|
.select(
|
|
135
|
-
pl.col("ReferenceDate")
|
|
136
|
-
pl.col("MaturityDate")
|
|
135
|
+
TradeDate=pl.col("ReferenceDate"),
|
|
136
|
+
ExpirationDate=pl.col("MaturityDate"),
|
|
137
137
|
)
|
|
138
138
|
)
|
|
139
139
|
|
|
@@ -253,7 +253,7 @@ def interpolate_rates(
|
|
|
253
253
|
0.13881
|
|
254
254
|
]
|
|
255
255
|
|
|
256
|
-
>>> # With extrapolation set to False, the second rate will be
|
|
256
|
+
>>> # With extrapolation set to False, the second rate will be null
|
|
257
257
|
>>> # Note: 0.13576348733268917 is shown as 0.135763
|
|
258
258
|
>>> di1.interpolate_rates(
|
|
259
259
|
... dates="25-04-2025",
|
|
@@ -264,7 +264,7 @@ def interpolate_rates(
|
|
|
264
264
|
Series: 'FlatFwdRate' [f64]
|
|
265
265
|
[
|
|
266
266
|
0.135763
|
|
267
|
-
|
|
267
|
+
null
|
|
268
268
|
]
|
|
269
269
|
|
|
270
270
|
Raises:
|
|
@@ -288,6 +288,8 @@ def interpolate_rates(
|
|
|
288
288
|
return pl.Series(dtype=pl.Float64)
|
|
289
289
|
|
|
290
290
|
s_bdays = bday.count(dfi["TradeDate"], dfi["ExpirationDate"])
|
|
291
|
+
|
|
292
|
+
# Inicializa FlatFwdRate como None
|
|
291
293
|
dfi = dfi.with_columns(BDaysToExp=s_bdays, FlatFwdRate=None)
|
|
292
294
|
|
|
293
295
|
# Load DI rates dataset filtered by the provided reference dates
|
|
@@ -321,8 +323,8 @@ def interpolate_rates(
|
|
|
321
323
|
.alias("FlatFwdRate")
|
|
322
324
|
)
|
|
323
325
|
|
|
324
|
-
# Return the
|
|
325
|
-
return dfi.get_column("FlatFwdRate")
|
|
326
|
+
# Return the interpolated rates with nulls where interpolation was not possible
|
|
327
|
+
return dfi.get_column("FlatFwdRate").fill_nan(None)
|
|
326
328
|
|
|
327
329
|
|
|
328
330
|
def interpolate_rate(
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import bisect
|
|
2
|
-
from typing import Literal
|
|
2
|
+
from typing import Literal, overload
|
|
3
3
|
|
|
4
4
|
import polars as pl
|
|
5
5
|
|
|
@@ -32,21 +32,39 @@ class Interpolator:
|
|
|
32
32
|
>>> known_bdays = [30, 60, 90]
|
|
33
33
|
>>> known_rates = [0.045, 0.05, 0.055]
|
|
34
34
|
|
|
35
|
-
Linear interpolation
|
|
35
|
+
Linear interpolation:
|
|
36
36
|
>>> linear = Interpolator("linear", known_bdays, known_rates)
|
|
37
37
|
>>> linear(45)
|
|
38
38
|
0.0475
|
|
39
39
|
|
|
40
|
-
Flat forward interpolation
|
|
40
|
+
Flat forward interpolation:
|
|
41
41
|
>>> fforward = Interpolator("flat_forward", known_bdays, known_rates)
|
|
42
42
|
>>> fforward(45)
|
|
43
43
|
0.04833068080970859
|
|
44
44
|
|
|
45
|
+
Array interpolation (polars shows 6 decimal places by default):
|
|
46
|
+
>>> fforward([15, 45, 75, 100])
|
|
47
|
+
shape: (4,)
|
|
48
|
+
Series: 'interpolated_rate' [f64]
|
|
49
|
+
[
|
|
50
|
+
0.045
|
|
51
|
+
0.048331
|
|
52
|
+
0.052997
|
|
53
|
+
null
|
|
54
|
+
]
|
|
55
|
+
|
|
45
56
|
>>> print(fforward(100)) # Extrapolation disabled by default
|
|
46
57
|
nan
|
|
47
58
|
|
|
48
|
-
>>> print(fforward(-10))
|
|
59
|
+
>>> print(fforward(-10)) # Invalid input returns NaN
|
|
49
60
|
nan
|
|
61
|
+
|
|
62
|
+
If extrapolation is enabled, the last known rate is used:
|
|
63
|
+
>>> fforward_extrap = Interpolator(
|
|
64
|
+
... "flat_forward", known_bdays, known_rates, extrapolate=True
|
|
65
|
+
... )
|
|
66
|
+
>>> print(fforward_extrap(100))
|
|
67
|
+
0.055
|
|
50
68
|
"""
|
|
51
69
|
|
|
52
70
|
def __init__(
|
|
@@ -152,18 +170,44 @@ class Interpolator:
|
|
|
152
170
|
f_t = (time - time_j) / (time_k - time_j)
|
|
153
171
|
return (f_j * (f_k / f_j) ** f_t) ** (1 / time) - 1
|
|
154
172
|
|
|
155
|
-
|
|
173
|
+
@overload
|
|
174
|
+
def interpolate(self, bdays: int) -> float: ...
|
|
175
|
+
@overload
|
|
176
|
+
def interpolate(self, bdays: ArrayLike) -> pl.Series: ...
|
|
177
|
+
|
|
178
|
+
def interpolate(self, bdays: int | ArrayLike) -> float | pl.Series:
|
|
179
|
+
"""
|
|
180
|
+
Interpolates rates for given business day(s).
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
bdays: int or ArrayLike - Business day(s) for interpolation
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
float or pl.Series - Interpolated rate(s)
|
|
187
|
+
"""
|
|
188
|
+
if hasattr(bdays, "__len__"):
|
|
189
|
+
bday_series = pl.Series(
|
|
190
|
+
name="interpolated_rate", values=bdays, dtype=pl.Int64
|
|
191
|
+
)
|
|
192
|
+
result = bday_series.map_elements(
|
|
193
|
+
self._interpolated_rate, return_dtype=pl.Float64
|
|
194
|
+
)
|
|
195
|
+
return result.fill_nan(None)
|
|
196
|
+
else:
|
|
197
|
+
return self._interpolated_rate(bdays)
|
|
198
|
+
|
|
199
|
+
def _interpolated_rate(self, bday: int) -> float:
|
|
156
200
|
"""
|
|
157
201
|
Finds the appropriate interpolation point and returns the interest rate
|
|
158
202
|
interpolated by the specified method from that point.
|
|
159
203
|
|
|
160
204
|
Args:
|
|
161
|
-
bday (int): Number of business days for which the interest rate
|
|
162
|
-
|
|
205
|
+
bday (int): Number of business days for which the interest rate
|
|
206
|
+
is to be calculated.
|
|
163
207
|
|
|
164
208
|
Returns:
|
|
165
|
-
float: The interest rate interpolated by the specified method
|
|
166
|
-
the given number of business days. If the input is out of range and
|
|
209
|
+
float: The interest rate interpolated by the specified method
|
|
210
|
+
for the given number of business days. If the input is out of range and
|
|
167
211
|
extrapolation is disabled, returns float("nan").
|
|
168
212
|
"""
|
|
169
213
|
# Validate input
|
|
@@ -197,7 +241,7 @@ class Interpolator:
|
|
|
197
241
|
|
|
198
242
|
raise ValueError(f"Interpolation method '{method}' not recognized.")
|
|
199
243
|
|
|
200
|
-
def __call__(self, bday: int) -> float:
|
|
244
|
+
def __call__(self, bday: int | ArrayLike) -> float | pl.Series:
|
|
201
245
|
"""
|
|
202
246
|
Allows the instance to be called as a function to perform interpolation.
|
|
203
247
|
|
|
@@ -132,30 +132,32 @@ def _transform_raw_data(raw_data: list[dict]) -> pl.DataFrame:
|
|
|
132
132
|
# Conversão de datas
|
|
133
133
|
cs.starts_with("data_").str.strptime(pl.Date, "%d/%m/%Y"),
|
|
134
134
|
# Cálculos de totais
|
|
135
|
-
|
|
136
|
-
"
|
|
135
|
+
quantidade_ofertada_total=(
|
|
136
|
+
pl.sum_horizontal("quantidade_ofertada_1v", "quantidade_ofertada_2v")
|
|
137
137
|
),
|
|
138
|
-
|
|
139
|
-
"
|
|
138
|
+
quantidade_aceita_total=(
|
|
139
|
+
pl.sum_horizontal("quantidade_aceita_1v", "quantidade_aceita_2v")
|
|
140
140
|
),
|
|
141
|
-
|
|
142
|
-
"
|
|
141
|
+
financeiro_aceito_total=(
|
|
142
|
+
pl.sum_horizontal("financeiro_aceito_1v", "financeiro_aceito_2v")
|
|
143
143
|
),
|
|
144
144
|
# Cálculo do financeiro ofertado
|
|
145
|
-
pl.when(
|
|
145
|
+
financeiro_ofertado_1v=pl.when(
|
|
146
|
+
pl.col("quantidade_ofertada_1v") == pl.col("quantidade_aceita_1v")
|
|
147
|
+
)
|
|
146
148
|
.then(pl.col("financeiro_aceito_1v"))
|
|
147
|
-
.otherwise(
|
|
148
|
-
.
|
|
149
|
-
|
|
149
|
+
.otherwise(pl.col("quantidade_ofertada_1v") * pl.col("pu_medio")),
|
|
150
|
+
financeiro_ofertado_2v=pl.when(
|
|
151
|
+
pl.col("quantidade_ofertada_2v") == pl.col("quantidade_aceita_2v")
|
|
152
|
+
)
|
|
150
153
|
.then(pl.col("financeiro_aceito_2v"))
|
|
151
|
-
.otherwise(
|
|
152
|
-
.alias("financeiro_ofertado_2v"),
|
|
154
|
+
.otherwise(pl.col("quantidade_ofertada_2v") * pl.col("pu_medio")),
|
|
153
155
|
# Cálculo das taxas de colocação
|
|
154
|
-
(
|
|
155
|
-
"
|
|
156
|
+
colocacao_1v=(
|
|
157
|
+
pl.col("quantidade_aceita_1v") / pl.col("quantidade_ofertada_1v")
|
|
156
158
|
),
|
|
157
|
-
(
|
|
158
|
-
"
|
|
159
|
+
colocacao_2v=(
|
|
160
|
+
pl.col("quantidade_aceita_2v") / pl.col("quantidade_ofertada_2v")
|
|
159
161
|
),
|
|
160
162
|
# Deixar um marcador de que o pu_medio não é original
|
|
161
163
|
tipo_pu_medio=pl.when(pl.col("pu_medio") == 0)
|
|
@@ -164,22 +166,21 @@ def _transform_raw_data(raw_data: list[dict]) -> pl.DataFrame:
|
|
|
164
166
|
)
|
|
165
167
|
.with_columns(
|
|
166
168
|
# Cálculo do financeiro ofertado
|
|
167
|
-
|
|
168
|
-
"
|
|
169
|
+
financeiro_ofertado_total=(
|
|
170
|
+
pl.sum_horizontal("financeiro_ofertado_1v", "financeiro_ofertado_2v")
|
|
169
171
|
),
|
|
170
|
-
(
|
|
172
|
+
colocacao_total=(
|
|
171
173
|
pl.col("quantidade_aceita_total") / pl.col("quantidade_ofertada_total")
|
|
172
|
-
)
|
|
174
|
+
),
|
|
173
175
|
# Algumas vezes o prazo não vem na API, então calculamos
|
|
174
|
-
(
|
|
175
|
-
|
|
176
|
-
.
|
|
176
|
+
dias_corridos=(
|
|
177
|
+
pl.col("data_vencimento") - pl.col("data_liquidacao_1v")
|
|
178
|
+
).dt.total_days(),
|
|
177
179
|
# Algumas vezes o PU médio vem zero da API, então recalculamos
|
|
178
|
-
pl.when(pl.col("pu_medio") == 0)
|
|
180
|
+
pu_medio=pl.when(pl.col("pu_medio") == 0)
|
|
179
181
|
.then((pl.col("financeiro_aceito_1v") / pl.col("quantidade_aceita_1v")))
|
|
180
182
|
.otherwise(pl.col("pu_medio"))
|
|
181
|
-
.round(6)
|
|
182
|
-
.alias("pu_medio"),
|
|
183
|
+
.round(6),
|
|
183
184
|
)
|
|
184
185
|
.with_columns(
|
|
185
186
|
# Arredondamentos e transformações que criam/alteram colunas sem condicional
|
|
@@ -205,7 +206,7 @@ def _transform_raw_data(raw_data: list[dict]) -> pl.DataFrame:
|
|
|
205
206
|
# Cálculo de dias úteis (requer acesso a colunas já convertidas)
|
|
206
207
|
dias_uteis = bday.count(df["data_liquidacao_1v"], df["data_vencimento"])
|
|
207
208
|
df = df.with_columns(dias_uteis.alias("dias_uteis"))
|
|
208
|
-
return df.sort(
|
|
209
|
+
return df.sort("data_1v", "titulo", "data_vencimento")
|
|
209
210
|
|
|
210
211
|
|
|
211
212
|
def _add_duration(df: pl.DataFrame) -> pl.DataFrame:
|
|
@@ -300,7 +301,7 @@ def _add_dv01_usd(df: pl.DataFrame) -> pl.DataFrame:
|
|
|
300
301
|
"""
|
|
301
302
|
Adiciona o DV01 em USD usando um join_asof para encontrar a PTAX mais recente.
|
|
302
303
|
"""
|
|
303
|
-
auction_date = df
|
|
304
|
+
auction_date = df["data_1v"].first()
|
|
304
305
|
# Busca o DataFrame da PTAX
|
|
305
306
|
df_ptax = _fetch_ptax_data(auction_date=auction_date)
|
|
306
307
|
if df_ptax.is_empty():
|
|
@@ -146,3 +146,27 @@ def premium(lft_rate: float, di_rate: float) -> float:
|
|
|
146
146
|
ltt_factor = (lft_rate + 1) ** (1 / 252)
|
|
147
147
|
di_factor = (di_rate + 1) ** (1 / 252)
|
|
148
148
|
return (ltt_factor * di_factor - 1) / (di_factor - 1)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def price(
|
|
152
|
+
vna: float,
|
|
153
|
+
quotation: float,
|
|
154
|
+
) -> float:
|
|
155
|
+
"""
|
|
156
|
+
Calculate the LFT price using Brazilian Treasury rules.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
vna (float): The nominal value of the LFT bond.
|
|
160
|
+
quotation (float): The LFT quotation in base 100.
|
|
161
|
+
Returns:
|
|
162
|
+
float: The LFT price truncated to 6 decimal places.
|
|
163
|
+
|
|
164
|
+
References:
|
|
165
|
+
- SEI Proccess 17944.005214/2024-09
|
|
166
|
+
|
|
167
|
+
Examples:
|
|
168
|
+
>>> from pyield import lft
|
|
169
|
+
>>> lft.price(15785.324502, 99.9291)
|
|
170
|
+
15774.132706
|
|
171
|
+
"""
|
|
172
|
+
return tools.truncate(vna * quotation / 100, 6)
|
|
@@ -376,18 +376,23 @@ def _create_bootstrap_dataframe(
|
|
|
376
376
|
# Generate coupon dates up to the longest maturity date
|
|
377
377
|
all_coupon_dates = _generate_all_coupon_dates(settlement, maturities.max())
|
|
378
378
|
bdays_to_mat = bday.count(settlement, all_coupon_dates)
|
|
379
|
+
ytm_rates = flat_fwd.interpolate(bdays_to_mat)
|
|
379
380
|
|
|
380
381
|
df = (
|
|
381
|
-
pl.DataFrame(
|
|
382
|
+
pl.DataFrame(
|
|
383
|
+
{
|
|
384
|
+
"MaturityDate": all_coupon_dates,
|
|
385
|
+
"BDToMat": bdays_to_mat,
|
|
386
|
+
"BYears": bdays_to_mat / 252,
|
|
387
|
+
"YTM": ytm_rates,
|
|
388
|
+
}
|
|
389
|
+
)
|
|
382
390
|
.with_columns(
|
|
383
|
-
|
|
384
|
-
YTM=pl.col("BDToMat").map_elements(flat_fwd, return_dtype=pl.Float64),
|
|
385
|
-
Coupon=COUPON_PMT,
|
|
391
|
+
Coupon=pl.lit(COUPON_PMT),
|
|
386
392
|
SpotRate=pl.lit(None, dtype=pl.Float64),
|
|
387
393
|
)
|
|
388
394
|
.sort("MaturityDate")
|
|
389
395
|
)
|
|
390
|
-
|
|
391
396
|
return df
|
|
392
397
|
|
|
393
398
|
|
|
@@ -599,20 +604,17 @@ def bei_rates(
|
|
|
599
604
|
settlement = cv.convert_dates(settlement)
|
|
600
605
|
ntnb_maturities = cv.convert_dates(ntnb_maturities)
|
|
601
606
|
|
|
602
|
-
|
|
607
|
+
ff_interpolator = ip.Interpolator(
|
|
603
608
|
method="flat_forward",
|
|
604
609
|
known_bdays=bday.count(settlement, nominal_maturities),
|
|
605
610
|
known_rates=nominal_rates,
|
|
606
611
|
extrapolate=True,
|
|
607
612
|
)
|
|
608
|
-
|
|
613
|
+
df_spot = spot_rates(settlement, ntnb_maturities, ntnb_rates)
|
|
609
614
|
df = (
|
|
610
|
-
|
|
611
|
-
.rename({"SpotRate": "RIR"})
|
|
615
|
+
df_spot.rename({"SpotRate": "RIR"})
|
|
612
616
|
.with_columns(
|
|
613
|
-
NIR=
|
|
614
|
-
nir_interpolator, return_dtype=pl.Float64
|
|
615
|
-
)
|
|
617
|
+
NIR=ff_interpolator(df_spot["BDToMat"]),
|
|
616
618
|
)
|
|
617
619
|
.with_columns(
|
|
618
620
|
BEI=((pl.col("NIR") + 1) / (pl.col("RIR") + 1)) - 1,
|
|
@@ -629,20 +631,31 @@ def duration(
|
|
|
629
631
|
rate: float,
|
|
630
632
|
) -> float:
|
|
631
633
|
"""
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
634
|
+
Calculate the Macaulay duration of the NTN-B bond in business years.
|
|
635
|
+
|
|
636
|
+
Formula:
|
|
637
|
+
Sum( t * CFₜ / (1 + y)ᵗ )
|
|
638
|
+
MacD = ---------------------------------
|
|
639
|
+
Current Bond Price
|
|
640
|
+
|
|
641
|
+
Where:
|
|
642
|
+
t = time in years until payment
|
|
643
|
+
CFₜ = cash flow at time t
|
|
644
|
+
y = yield to maturity (periodic)
|
|
645
|
+
Price = Sum( CFₜ / (1 + y)ᵗ )
|
|
646
|
+
|
|
647
|
+
Args:
|
|
648
|
+
settlement (DateLike): The settlement date of the operation.
|
|
649
|
+
maturity (DateLike): The maturity date of the NTN-B bond.
|
|
650
|
+
rate (float): The discount rate used to calculate the duration.
|
|
651
|
+
|
|
652
|
+
Returns:
|
|
653
|
+
float: The Macaulay duration of the NTN-B bond in business years.
|
|
654
|
+
|
|
655
|
+
Examples:
|
|
656
|
+
>>> from pyield import ntnb
|
|
657
|
+
>>> ntnb.duration("23-08-2024", "15-08-2060", 0.061005)
|
|
658
|
+
15.08305431313046
|
|
646
659
|
"""
|
|
647
660
|
df = cash_flows(settlement, maturity)
|
|
648
661
|
if df.is_empty():
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import polars as pl
|
|
5
|
+
|
|
6
|
+
import pyield.converters as cv
|
|
7
|
+
import pyield.tn.tools as bt
|
|
8
|
+
from pyield import bday
|
|
9
|
+
from pyield.types import DateLike, has_nullable_args
|
|
10
|
+
|
|
11
|
+
"""
|
|
12
|
+
Global parameters for NTN-B1 bonds calculations.
|
|
13
|
+
These parameters are used to define the cash flows and payment structure of the bonds,
|
|
14
|
+
according to Commercial Name.
|
|
15
|
+
The parameters are initialized based on the commercial name of the NTN-B1 bond.
|
|
16
|
+
|
|
17
|
+
"""
|
|
18
|
+
AMORTIZATION_PAYMENT = 0
|
|
19
|
+
FINAL_AMORTIZATION_PAYMENT = 0
|
|
20
|
+
NUMBER_OF_AMORTIZATIONS = 0
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class CommercialName(Enum):
|
|
24
|
+
"""
|
|
25
|
+
Commercial Name Enum used to identify the kind of used NTN-B1 in the scope of the
|
|
26
|
+
calculation (Renda+ or Educa+).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
RENDA_MAIS = "Renda+"
|
|
30
|
+
EDUCA_MAIS = "Educa+"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Mapeamento estático do número de meses
|
|
34
|
+
# Isso é uma constante real (não muda durante a execução)
|
|
35
|
+
PARAMS_MAP = {
|
|
36
|
+
CommercialName.RENDA_MAIS: 240,
|
|
37
|
+
CommercialName.EDUCA_MAIS: 60,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _get_bond_parameters(commercial_name: CommercialName) -> tuple[float, float, int]:
|
|
42
|
+
"""
|
|
43
|
+
Returns amortization parameters based on commercial name.
|
|
44
|
+
Returns: (amortization_payment, final_amortization_payment, number_of_amortizations)
|
|
45
|
+
"""
|
|
46
|
+
try:
|
|
47
|
+
n_amortizations = PARAMS_MAP[commercial_name]
|
|
48
|
+
except KeyError:
|
|
49
|
+
raise ValueError(f"Invalid commercial name: {commercial_name}")
|
|
50
|
+
|
|
51
|
+
amortization_payment = 1 / n_amortizations
|
|
52
|
+
final_amortization_payment = 1 - (amortization_payment * (n_amortizations - 1))
|
|
53
|
+
|
|
54
|
+
return amortization_payment, final_amortization_payment, n_amortizations
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def payment_dates(
|
|
58
|
+
settlement: DateLike, maturity: DateLike, commercial_name: CommercialName
|
|
59
|
+
) -> pl.Series:
|
|
60
|
+
"""
|
|
61
|
+
Generate all remaining amortization dates between a given date and the maturity
|
|
62
|
+
date.
|
|
63
|
+
The dates are inclusive. Payments are made from January 15th of the year of
|
|
64
|
+
conversion to December 15 of maturity year.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
settlement (DateLike): The settlement date (exclusive) to start generating
|
|
68
|
+
the amortization dates.
|
|
69
|
+
maturity (DateLike): The maturity date.
|
|
70
|
+
commercial_name (CommercialName): The commercial name of the NTN-B1 bond
|
|
71
|
+
(Renda+ or Educa+).
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
pl.Series: Series of coupon dates within the specified range.
|
|
75
|
+
|
|
76
|
+
Examples:
|
|
77
|
+
>>> from pyield import ntnb1
|
|
78
|
+
>>> r_mais = ntnb1.CommercialName.RENDA_MAIS
|
|
79
|
+
>>> ntnb1.payment_dates("10-05-2024", "15-12-2050", r_mais)
|
|
80
|
+
shape: (240,)
|
|
81
|
+
Series: 'payment_dates' [date]
|
|
82
|
+
[
|
|
83
|
+
2031-01-15
|
|
84
|
+
2031-02-15
|
|
85
|
+
2031-03-15
|
|
86
|
+
2031-04-15
|
|
87
|
+
2031-05-15
|
|
88
|
+
…
|
|
89
|
+
2050-08-15
|
|
90
|
+
2050-09-15
|
|
91
|
+
2050-10-15
|
|
92
|
+
2050-11-15
|
|
93
|
+
2050-12-15
|
|
94
|
+
]
|
|
95
|
+
"""
|
|
96
|
+
if has_nullable_args(settlement, maturity, commercial_name):
|
|
97
|
+
return pl.Series("payment_dates", dtype=pl.Date)
|
|
98
|
+
|
|
99
|
+
# Validate and normalize dates
|
|
100
|
+
settlement = cv.convert_dates(settlement)
|
|
101
|
+
maturity = cv.convert_dates(maturity)
|
|
102
|
+
|
|
103
|
+
if maturity <= settlement:
|
|
104
|
+
raise ValueError("Maturity date must be after the settlement date.")
|
|
105
|
+
|
|
106
|
+
maturity = maturity.replace(day=15)
|
|
107
|
+
|
|
108
|
+
# Get bond parameters
|
|
109
|
+
_, _, n_amortizations = _get_bond_parameters(commercial_name)
|
|
110
|
+
|
|
111
|
+
amtz_dates = [maturity - pd.DateOffset(months=i) for i in range(n_amortizations)]
|
|
112
|
+
|
|
113
|
+
if len(amtz_dates) == 0:
|
|
114
|
+
raise ValueError("No amortization dates found after settlement date.")
|
|
115
|
+
|
|
116
|
+
s_pmt_dates = pl.Series(name="payment_dates", values=amtz_dates).cast(pl.Date)
|
|
117
|
+
|
|
118
|
+
return s_pmt_dates.filter(s_pmt_dates > settlement).sort()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def cash_flows(
|
|
122
|
+
settlement: DateLike, maturity: DateLike, commercial_name: CommercialName
|
|
123
|
+
) -> pl.DataFrame:
|
|
124
|
+
"""
|
|
125
|
+
Generate the cash flows for NTN-B1 bonds between the settlement and maturity dates.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
settlement (DateScalar): The settlement date (exclusive) to start generating
|
|
129
|
+
the cash flows.
|
|
130
|
+
maturity (DateScalar): The maturity date of the bond.
|
|
131
|
+
commercial_name (CommercialName): The commercial name of the NTN-B1 bond
|
|
132
|
+
(Renda+ or Educa+).
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
pd.DataFrame: DataFrame with columns "PaymentDate" and "CashFlow".
|
|
136
|
+
|
|
137
|
+
Returned columns:
|
|
138
|
+
- PaymentDate: The payment date of the cash flow
|
|
139
|
+
- CashFlow: Cash flow value for the bond
|
|
140
|
+
|
|
141
|
+
Examples:
|
|
142
|
+
>>> from pyield import ntnb1
|
|
143
|
+
>>> r_mais = ntnb1.CommercialName.RENDA_MAIS
|
|
144
|
+
>>> ntnb1.cash_flows("10-05-2024", "15-12-2060", r_mais)
|
|
145
|
+
shape: (240, 2)
|
|
146
|
+
┌─────────────┬──────────┐
|
|
147
|
+
│ PaymentDate ┆ CashFlow │
|
|
148
|
+
│ --- ┆ --- │
|
|
149
|
+
│ date ┆ f64 │
|
|
150
|
+
╞═════════════╪══════════╡
|
|
151
|
+
│ 2041-01-15 ┆ 0.004167 │
|
|
152
|
+
│ 2041-02-15 ┆ 0.004167 │
|
|
153
|
+
│ 2041-03-15 ┆ 0.004167 │
|
|
154
|
+
│ 2041-04-15 ┆ 0.004167 │
|
|
155
|
+
│ 2041-05-15 ┆ 0.004167 │
|
|
156
|
+
│ … ┆ … │
|
|
157
|
+
│ 2060-08-15 ┆ 0.004167 │
|
|
158
|
+
│ 2060-09-15 ┆ 0.004167 │
|
|
159
|
+
│ 2060-10-15 ┆ 0.004167 │
|
|
160
|
+
│ 2060-11-15 ┆ 0.004167 │
|
|
161
|
+
│ 2060-12-15 ┆ 0.004167 │
|
|
162
|
+
└─────────────┴──────────┘
|
|
163
|
+
|
|
164
|
+
"""
|
|
165
|
+
if has_nullable_args(settlement, maturity, commercial_name):
|
|
166
|
+
return pl.DataFrame({"PaymentDate": [], "CashFlow": []})
|
|
167
|
+
|
|
168
|
+
# Validate and normalize dates
|
|
169
|
+
settlement = cv.convert_dates(settlement)
|
|
170
|
+
maturity = cv.convert_dates(maturity)
|
|
171
|
+
|
|
172
|
+
# Get the coupon dates between the settlement and maturity dates
|
|
173
|
+
p_dates = payment_dates(settlement, maturity, commercial_name)
|
|
174
|
+
df = pl.DataFrame({"PaymentDate": p_dates})
|
|
175
|
+
|
|
176
|
+
# Get bond parameters
|
|
177
|
+
amort_payment, final_amort_payment, _ = _get_bond_parameters(commercial_name)
|
|
178
|
+
|
|
179
|
+
# Set the cash flow at maturity to FINAL_PMT and the others to COUPON_PMT
|
|
180
|
+
df = df.with_columns(
|
|
181
|
+
pl.when(pl.col("PaymentDate") == maturity)
|
|
182
|
+
.then(final_amort_payment)
|
|
183
|
+
.otherwise(amort_payment)
|
|
184
|
+
.alias("CashFlow")
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# Return a dataframe with the payment dates and cash flows
|
|
188
|
+
return df
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def quotation(
|
|
192
|
+
settlement: DateLike,
|
|
193
|
+
maturity: DateLike,
|
|
194
|
+
rate: float,
|
|
195
|
+
commercial_name: CommercialName,
|
|
196
|
+
) -> float:
|
|
197
|
+
"""
|
|
198
|
+
Calculate the NTN-B quotation in base 100 using Anbima rules.
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
settlement (DateScalar): The settlement date of the operation.
|
|
202
|
+
maturity (DateScalar): The maturity date of the NTN-B bond.
|
|
203
|
+
rate (float): The discount rate used to calculate the present value of
|
|
204
|
+
the cash flows, which is the yield to maturity (YTM) of the NTN-B.
|
|
205
|
+
commercial_name (CommercialName): The commercial name of the NTN-B1 bond
|
|
206
|
+
(Renda+ or Educa+).
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
float: The NTN-B quotation truncated to 6 decimal places.
|
|
210
|
+
|
|
211
|
+
References:
|
|
212
|
+
- https://www.anbima.com.br/data/files/A0/02/CC/70/8FEFC8104606BDC8B82BA2A8/Metodologias%20ANBIMA%20de%20Precificacao%20Titulos%20Publicos.pdf
|
|
213
|
+
|
|
214
|
+
Examples:
|
|
215
|
+
>>> from pyield import ntnb1
|
|
216
|
+
>>> r_mais = ntnb1.CommercialName.RENDA_MAIS
|
|
217
|
+
>>> ntnb1.quotation("18-06-2025", "15-12-2084", 0.07010, r_mais)
|
|
218
|
+
0.038332
|
|
219
|
+
"""
|
|
220
|
+
cf_df = cash_flows(settlement, maturity, commercial_name)
|
|
221
|
+
cf_dates = cf_df["PaymentDate"]
|
|
222
|
+
cf_values = cf_df["CashFlow"]
|
|
223
|
+
|
|
224
|
+
# Calculate the number of business days between settlement and cash flow dates
|
|
225
|
+
b_days = bday.count(settlement, cf_dates)
|
|
226
|
+
|
|
227
|
+
# Calculate the number of periods truncated as per Anbima rules
|
|
228
|
+
num_of_years = bt.truncate(b_days / 252, 14)
|
|
229
|
+
|
|
230
|
+
discount_factor = (1 + rate) ** num_of_years
|
|
231
|
+
|
|
232
|
+
# Calculate the present value of each cash flow (DCF) rounded as per Anbima rules
|
|
233
|
+
cf_present_value = (cf_values / discount_factor).round(10)
|
|
234
|
+
|
|
235
|
+
# Return the quotation (the dcf sum) truncated as per Anbima rules
|
|
236
|
+
return bt.truncate(cf_present_value.sum(), 6)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def price(
|
|
240
|
+
vna: float,
|
|
241
|
+
quotation: float,
|
|
242
|
+
) -> float:
|
|
243
|
+
"""
|
|
244
|
+
Calculate the NTN-B1 price using Brazilian Treasury rules.
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
vna (float): The nominal value of the NTN-B bond.
|
|
248
|
+
quotation (float): The NTN-B quotation in base 100.
|
|
249
|
+
|
|
250
|
+
Returns:
|
|
251
|
+
float: The NTN-B1 price truncated to 6 decimal places.
|
|
252
|
+
|
|
253
|
+
References:
|
|
254
|
+
- SEI Proccess 17944.005214/2024-09
|
|
255
|
+
|
|
256
|
+
Examples:
|
|
257
|
+
>>> from pyield import ntnb1
|
|
258
|
+
>>> ntnb1.price(4299.160173, 99.3651 / 100)
|
|
259
|
+
4271.864805
|
|
260
|
+
>>> ntnb1.price(4315.498383, 100.6409 / 100)
|
|
261
|
+
4343.156412
|
|
262
|
+
"""
|
|
263
|
+
if has_nullable_args(vna, quotation):
|
|
264
|
+
return float("nan")
|
|
265
|
+
return bt.truncate(vna * quotation, 6)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def duration(
|
|
269
|
+
settlement: DateLike,
|
|
270
|
+
maturity: DateLike,
|
|
271
|
+
rate: float,
|
|
272
|
+
commercial_name: CommercialName,
|
|
273
|
+
) -> float:
|
|
274
|
+
"""
|
|
275
|
+
Calculate the Macaulay duration of the NTN-B bond in business years.
|
|
276
|
+
|
|
277
|
+
Args:
|
|
278
|
+
settlement (DateScalar): The settlement date of the operation.
|
|
279
|
+
maturity (DateScalar): The maturity date of the NTN-B bond.
|
|
280
|
+
rate (float): The discount rate used to calculate the duration.
|
|
281
|
+
commercial_name (CommercialName): The commercial name of the NTN-B1 bond
|
|
282
|
+
(Renda+ or Educa+).
|
|
283
|
+
|
|
284
|
+
Returns:
|
|
285
|
+
float: The Macaulay duration of the NTN-B bond in business years.
|
|
286
|
+
|
|
287
|
+
Examples:
|
|
288
|
+
>>> from pyield import ntnb1
|
|
289
|
+
>>> r_mais = ntnb1.CommercialName.RENDA_MAIS
|
|
290
|
+
>>> ntnb1.duration("23-06-2025", "15-12-2084", 0.0686, r_mais)
|
|
291
|
+
47.10493458167134
|
|
292
|
+
"""
|
|
293
|
+
# Return NaN if any input is nullable
|
|
294
|
+
if has_nullable_args(settlement, maturity, rate, commercial_name):
|
|
295
|
+
return float("nan")
|
|
296
|
+
|
|
297
|
+
df = cash_flows(settlement, maturity, commercial_name)
|
|
298
|
+
s_byears = bday.count(settlement, df["PaymentDate"]) / 252
|
|
299
|
+
s_dcf = df["CashFlow"] / (1 + rate) ** s_byears
|
|
300
|
+
duration = (s_dcf * s_byears).sum() / s_dcf.sum()
|
|
301
|
+
|
|
302
|
+
# Truncate duration to 14 decimal places for result reproducibility
|
|
303
|
+
return bt.truncate(duration, 14)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def dv01(
|
|
307
|
+
settlement: DateLike,
|
|
308
|
+
maturity: DateLike,
|
|
309
|
+
rate: float,
|
|
310
|
+
vna: float,
|
|
311
|
+
commercial_name: CommercialName = CommercialName.RENDA_MAIS,
|
|
312
|
+
) -> float:
|
|
313
|
+
"""
|
|
314
|
+
Calculate the DV01 (Dollar Value of 01) for an NTN-B1 in R$.
|
|
315
|
+
|
|
316
|
+
Represents the price change in R$ for a 1 basis point (0.01%) increase in yield.
|
|
317
|
+
|
|
318
|
+
Args:
|
|
319
|
+
settlement (DateScalar): The settlement date in 'DD-MM-YYYY' format
|
|
320
|
+
or a pandas Timestamp.
|
|
321
|
+
maturity (DateScalar): The maturity date in 'DD-MM-YYYY' format or
|
|
322
|
+
a pandas Timestamp.
|
|
323
|
+
rate (float): The discount rate used to calculate the present value of
|
|
324
|
+
the cash flows, which is the yield to maturity (YTM) of the NTN-B.
|
|
325
|
+
vna (float): The nominal value of the NTN-B bond.
|
|
326
|
+
commercial_name (CommercialName): The commercial name of the NTN-B1 bond
|
|
327
|
+
|
|
328
|
+
Returns:
|
|
329
|
+
float: The DV01 value, representing the price change for a 1 basis point
|
|
330
|
+
increase in yield.
|
|
331
|
+
|
|
332
|
+
Examples:
|
|
333
|
+
>>> from pyield import ntnb1
|
|
334
|
+
>>> r_mais = ntnb1.CommercialName.RENDA_MAIS
|
|
335
|
+
>>> ntnb1.dv01("23-06-2025", "15-12-2084", 0.0686, 4299.160173, r_mais)
|
|
336
|
+
0.7738490000000127
|
|
337
|
+
"""
|
|
338
|
+
if has_nullable_args(settlement, maturity, rate, vna, commercial_name):
|
|
339
|
+
return float("nan")
|
|
340
|
+
|
|
341
|
+
quotation1 = quotation(settlement, maturity, rate, commercial_name)
|
|
342
|
+
quotation2 = quotation(settlement, maturity, rate + 0.0001, commercial_name)
|
|
343
|
+
price1 = price(vna, quotation1)
|
|
344
|
+
price2 = price(vna, quotation2)
|
|
345
|
+
return price1 - price2
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
from pyield import bday
|
|
2
|
+
from pyield.tn import tools
|
|
3
|
+
from pyield.types import DateLike, has_nullable_args
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def price(
|
|
7
|
+
settlement: DateLike,
|
|
8
|
+
maturity: DateLike,
|
|
9
|
+
rate: float,
|
|
10
|
+
face_value: float,
|
|
11
|
+
) -> float:
|
|
12
|
+
"""
|
|
13
|
+
Calculate the NTN-B PRINCIPAL price using Anbima rules.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
settlement (DateScalar): The settlement date in 'DD-MM-YYYY' format
|
|
17
|
+
or a pandas Timestamp.
|
|
18
|
+
maturity (DateScalar): The maturity date in 'DD-MM-YYYY' format or
|
|
19
|
+
a pandas Timestamp.
|
|
20
|
+
rate (float): The discount rate used to calculate the present value of
|
|
21
|
+
the cash flows, which is the yield to maturity (YTM) of the NTN-F.
|
|
22
|
+
face_value (float): The face value of the bond (VNA).
|
|
23
|
+
Returns:
|
|
24
|
+
float: The NTN-B PRINCIPAL price using Anbima rules.
|
|
25
|
+
|
|
26
|
+
References:
|
|
27
|
+
- https://www.anbima.com.br/data/files/A0/02/CC/70/8FEFC8104606BDC8B82BA2A8/Metodologias%20ANBIMA%20de%20Precificacao%20Titulos%20Publicos.pdf
|
|
28
|
+
|
|
29
|
+
Examples:
|
|
30
|
+
>>> from pyield import ntnbprinc
|
|
31
|
+
>>> ntnbprinc.price("02-12-2025", "15-05-2029", 0.0777, 4567.033825)
|
|
32
|
+
3537.763157
|
|
33
|
+
"""
|
|
34
|
+
if has_nullable_args(settlement, maturity, rate, face_value):
|
|
35
|
+
return float("nan")
|
|
36
|
+
|
|
37
|
+
# Calculate the number of business days between settlement and cash flow dates
|
|
38
|
+
bdays = bday.count(settlement, maturity)
|
|
39
|
+
|
|
40
|
+
# Calculate the number of periods truncated as per Anbima rule
|
|
41
|
+
num_of_years = tools.truncate(bdays / 252, 14)
|
|
42
|
+
|
|
43
|
+
discount_factor = (1 + rate) ** num_of_years
|
|
44
|
+
|
|
45
|
+
# Truncate the price to 6 decimal places as per Anbima rules
|
|
46
|
+
return tools.truncate(face_value / discount_factor, 6)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def dv01(
|
|
50
|
+
settlement: DateLike,
|
|
51
|
+
maturity: DateLike,
|
|
52
|
+
rate: float,
|
|
53
|
+
face_value: float,
|
|
54
|
+
) -> float:
|
|
55
|
+
"""
|
|
56
|
+
Calculate the DV01 (Dollar Value of 01) for an LTN in R$.
|
|
57
|
+
|
|
58
|
+
Represents the price change in R$ for a 1 basis point (0.01%) increase in yield.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
settlement (DateScalar): The settlement date in 'DD-MM-YYYY' format
|
|
62
|
+
or a pandas Timestamp.
|
|
63
|
+
maturity (DateScalar): The maturity date in 'DD-MM-YYYY' format or
|
|
64
|
+
a pandas Timestamp.
|
|
65
|
+
rate (float): The discount rate used to calculate the present value of
|
|
66
|
+
the cash flows, which is the yield to maturity (YTM) of the LTN.
|
|
67
|
+
face_value (float): The face value of the bond (VNA).
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
float: The DV01 value, representing the price change for a 1 basis point
|
|
71
|
+
increase in yield.
|
|
72
|
+
|
|
73
|
+
Examples:
|
|
74
|
+
>>> from pyield import ntnbprinc as bp
|
|
75
|
+
>>> bp.dv01("02-12-2025", "15-05-2029", 0.0777, 4567.033825)
|
|
76
|
+
1.1200559999997495
|
|
77
|
+
"""
|
|
78
|
+
price1 = price(settlement, maturity, rate, face_value)
|
|
79
|
+
price2 = price(settlement, maturity, rate + 0.0001, face_value)
|
|
80
|
+
return price1 - price2
|
|
@@ -340,17 +340,16 @@ def spot_rates( # noqa
|
|
|
340
340
|
|
|
341
341
|
# 4. Construir DataFrame inicial
|
|
342
342
|
bdays_to_mat = bday.count(settlement, all_coupon_dates)
|
|
343
|
+
ytm_rates = ntnf_rate_interpolator(bdays_to_mat)
|
|
343
344
|
df = pl.DataFrame(
|
|
344
345
|
{
|
|
345
346
|
"MaturityDate": all_coupon_dates,
|
|
346
347
|
"BDToMat": bdays_to_mat,
|
|
348
|
+
"BYears": bdays_to_mat / 252,
|
|
349
|
+
"YTM": ytm_rates,
|
|
347
350
|
}
|
|
348
351
|
).with_columns(
|
|
349
|
-
|
|
350
|
-
Coupon=COUPON_PMT,
|
|
351
|
-
YTM=pl.col("BDToMat").map_elements(
|
|
352
|
-
ntnf_rate_interpolator, return_dtype=pl.Float64
|
|
353
|
-
),
|
|
352
|
+
Coupon=pl.lit(COUPON_PMT),
|
|
354
353
|
)
|
|
355
354
|
|
|
356
355
|
# 5. Loop de bootstrap (iterativo por dependência sequencial)
|
|
@@ -601,9 +600,10 @@ def premium( # noqa
|
|
|
601
600
|
)
|
|
602
601
|
|
|
603
602
|
bdays_to_payments = bday.count(settlement, df_cf["PaymentDate"])
|
|
604
|
-
df = df_cf.with_columns(
|
|
605
|
-
|
|
606
|
-
|
|
603
|
+
df = df_cf.with_columns(
|
|
604
|
+
BDToMat=bdays_to_payments,
|
|
605
|
+
BYears=bdays_to_payments / 252,
|
|
606
|
+
DIRate=ff_interpolator(bdays_to_payments),
|
|
607
607
|
)
|
|
608
608
|
|
|
609
609
|
bond_price = tools.calculate_present_value(
|
|
@@ -711,11 +711,7 @@ def di_net_spread( # noqa
|
|
|
711
711
|
|
|
712
712
|
df = df.with_columns(
|
|
713
713
|
BDaysToPayment=bdays_to_payment,
|
|
714
|
-
|
|
715
|
-
DIRateInterp=pl.col("BDaysToPayment").map_elements(
|
|
716
|
-
function=ff_interpolator,
|
|
717
|
-
return_dtype=pl.Float64,
|
|
718
|
-
),
|
|
714
|
+
DIRateInterp=ff_interpolator(bdays_to_payment),
|
|
719
715
|
)
|
|
720
716
|
|
|
721
717
|
# Extração dos dados para o cálculo numérico
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.40.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
|
|
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
|