Skip to main content

A Python library for analysis of fixed income instruments in Brazil

Project description

PyPI version Made with Python License

PYield: Brazilian Fixed Income Toolkit

PYield is a Python library designed for the analysis of Brazilian fixed income instruments. Leveraging the power of popular Python libraries like Polars, Pandas, Numpy and Requests, PYield simplifies the process of obtaining and processing data from key sources such as ANBIMA, BCB, IBGE and B3.

Documentation: https://crdcj.github.io/PYield/

Key Features

  • Data Collection: Automated fetching of data from ANBIMA and B3.
  • Data Processing: Efficient processing and normalization of fixed income data.
  • Analysis Tools: Built-in functions for common analysis tasks in fixed income markets.
  • Easy Integration: Seamless integration with pandas data analysis workflows.
  • Type Hints: Full support for static type checking, enhancing development experience and code quality.

Installation

You can install PYield using pip:

pip install pyield

Custom Types

DateScalar

DateScalar and DateArray are a type alias used across PYield to represent different types of date inputs. It includes several common date formats, allowing for flexible date handling within the library.

The accepted formats in DateScalar are:

  • datetime.date
  • datetime.datetime
  • str (in the format DD-MM-YYYY as used in Brazil)
  • np.datetime64
  • pd.Timestamp

DateArray

The accepted formats in DateArray are:

  • pd.DatetimeIndex
  • np.ndarray
  • list[DateScalar]
  • tuple[DateScalar, ...]
  • pd.Series (Pandas Series)
  • pl.Series (Polars Series)

Referencing DateScalar and DateArray in function arguments simplifies the code by allowing any of these date formats to be used interchangeably.

Important Note on Date Formats

When using date strings in PYield functions, please ensure that the date format is day-first (e.g., "31-05-2024"). This format was chosen to be consistent with the Brazilian date convention.

For production code, it is recommended to parse date strings with pandas.to_datetime using an explicit format to avoid ambiguity and ensure consistency. For example:

import pandas as pd
# Converting a date string to a pandas Timestamp with a specific format
date = pd.to_datetime("2024/31/05", format="%Y/%d/%m")
date = pd.to_datetime("05-31-2024", format="%m-%d-%Y")

How to use PYield

Brazilian Treasury Bonds Tools

>>> from pyield import ntnb, ntnf, ltn

# Get ANBIMA data for a given date
>>> ltn.data("23-08-2024")
┌───────────────┬──────────┬───────────┬───────────────┬───┬──────────┬──────────┬────────────────┬─────────┐
 ReferenceDate  BondType  SelicCode  IssueBaseDate    BidRate   AskRate   IndicativeRate  DIRate  
 ---            ---       ---        ---               ---       ---       ---             ---     
 date           str       i64        date              f64       f64       f64             f64     
╞═══════════════╪══════════╪═══════════╪═══════════════╪═══╪══════════╪══════════╪════════════════╪═════════╡
 2024-08-23     LTN       100000     2022-07-08       0.10459   0.104252  0.104416        0.10472 
 2024-08-23     LTN       100000     2018-02-01       0.107366  0.107016  0.107171        0.10823 
 2024-08-23     LTN       100000     2023-01-06       0.110992  0.110746  0.110866        0.11179 
 2024-08-23     LTN       100000     2022-01-07       0.11315   0.112947  0.113032        0.11365 
                                                                                          
 2024-08-23     LTN       100000     2023-07-07       0.115452  0.115247  0.115335        0.11498 
 2024-08-23     LTN       100000     2024-01-05       0.115758  0.115633  0.115694        0.11508 
 2024-08-23     LTN       100000     2024-07-05       0.11647   0.116341  0.116417        0.11554 
 2024-08-23     LTN       100000     2024-01-05       0.117504  0.11737   0.117436        0.11594 
└───────────────┴──────────┴───────────┴───────────────┴───┴──────────┴──────────┴────────────────┴─────────┘

# Calculate the quotation of a NTN-B bond as per ANBIMA's rules
>>> ntnb.quotation("31-05-2024", "15-05-2035", 0.061490)
99.3651
>>> ntnb.quotation("31-05-2024", "15-08-2060", 0.061878)
99.5341

# Calculate the DI Spread of NTN-F and LTN bonds in a given date
>>> ntnf.di_spreads("23-08-2024")
    MaturityDate  DISpread
0   2025-01-01     -5.38
1   2027-01-01      4.39
2   2029-01-01      7.37
3   2031-01-01     12.58
4   2033-01-01      7.67
5   2035-01-01     12.76

Business Days Tools (Brazilian holidays are automatically considered)

>>> from pyield import bday
# Count the number of business days between two dates
# Start date is included, end date is excluded
>>> bday.count(start='29-12-2023', end='02-01-2024')
1

# Get the next business day after a given date (offset=1)
>>> bday.offset(dates="29-12-2023", offset=1)
datetime.date(2024, 1, 2)

# Get the next business day if it is not a business day (offset=0)
>>> bday.offset(dates="30-12-2023", offset=0)
datetime.date(2024, 1, 2)

# Since 29-12-2023 is a business day, it returns the same date (offset=0)
>>> bday.offset(dates="29-12-2023", offset=0)
datetime.date(2023, 12, 29)

# Generate a pandas series with the business days between two dates
>>> bday.generate(start='29-12-2023', end='03-01-2024')
0   2023-12-29
1   2024-01-02
2   2024-01-03

Futures Data

>>> import pyield as yd

# Fetch historical DI Futures data from B3
>>> yd.futures(contract_code="DI1", date='08-03-2024')
TradeDate  TickerSymbol ExpirationDate BDaysToExp ... LastRate LastAskRate LastBidRate SettlementRate
2024-03-08       DI1J24     2024-04-01         15 ...   10.952      10.952      10.956         10.956
2024-03-08       DI1K24     2024-05-02         37 ...   10.776      10.774      10.780         10.777
2024-03-08       DI1M24     2024-06-03         58 ...   10.604      10.602      10.604         10.608
       ...          ...            ...        ... ...      ...         ...         ...            ...
2024-03-08       DI1F37     2037-01-02       3213 ...     <NA>        <NA>        <NA>         10.859
2024-03-08       DI1F38     2038-01-04       3462 ...     <NA>        <NA>        <NA>         10.859
2024-03-08       DI1F39     2039-01-03       3713 ...     <NA>        <NA>        <NA>         10.85

# Fetch current DI Futures data from B3 (15 minutes delay)
>>> yd.futures(contract_code="DI1", date="21-03-2024")  # when the date used is the current date and market is open
LastUpdatee      TickerSymbol ExpirationDate BDaysToExp ... MaxRate LastAskRate LastBidRate LastRate
2024-04-21 13:37:39       DI1K24     2024-05-02          7 ... 0.10660     0.10652     0.10660  0.10660
2024-04-21 13:37:39       DI1M24     2024-06-03         28 ... 0.10518     0.10510     0.10516  0.10518
2024-04-21 13:37:39       DI1N24     2024-07-01         48 ... 0.10480     0.10456     0.10462  0.10460
                ...          ...            ...        ... ...     ...         ...         ...      ...
2024-04-21 13:37:39       DI1F37     2037-01-02       3183 ...    <NA>        <NA>     0.11600     <NA>
2024-04-21 13:37:39       DI1F38     2038-01-04       3432 ...    <NA>        <NA>     0.11600     <NA>
2024-04-21 13:37:39       DI1F39     2039-01-03       3683 ...    <NA>        <NA>        <NA>     <NA>

Indicators Data

>>> from pyield import bc

# Fetch the SELIC target rates from the Central Bank of Brazil
>>> bc.selic_over_series("26-01-2025", "30-01-2025")  # No data on 26-01-2025 (sunday)
        Date   Value
0 2025-01-27  0.1215
1 2025-01-28  0.1215
2 2025-01-29  0.1215
3 2025-01-30  0.1315

# Fetch the SELIC target rate for a specific date
>>> bc.selic_over("27-01-2025")
        Date   Value
0.1215  # 12.15%

Projections Data

>>> from pyield import ipca
# Fetch current month projection for IPCA from IBGE API
>>> current_ipca = ipca.projected_rate()
>>> print(current_ipca)
IndicatorProjection(
    last_updated=Timestamp('2024-04-19 18:55:00'),    
    reference_period='set/24',
    projected_value=0.0035  # 0.35%
)
>>> ipca.projected_value
0.0035  # 0.35%

Interpolation Tools

Interpolate interest rates for specific business days using the Interpolator class.

>>> from pyield import Interpolator
# Initialize the Interpolator with known business days and interest rates.
>>> known_bdays = [30, 60, 90]
>>> known_rates = [0.045, 0.05, 0.055]
>>> linear_interpolator = Interpolator("linear", known_bdays, known_rates)
>>> linear_interpolator(45)  # Interpolate the interest rate for a given number of business days.
0.0475

# Use the flat forward method for interpolation.
>>> ff_interpolator = Interpolator("flat_forward", known_bdays, known_rates)
>>> ff_interpolator(45)
0.04833068080970859

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyield-0.39.8.tar.gz (96.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyield-0.39.8-py3-none-any.whl (130.6 kB view details)

Uploaded Python 3

File details

Details for the file pyield-0.39.8.tar.gz.

File metadata

  • Download URL: pyield-0.39.8.tar.gz
  • Upload date:
  • Size: 96.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.1

File hashes

Hashes for pyield-0.39.8.tar.gz
Algorithm Hash digest
SHA256 d329948c6ba6f3273fd8bfa96a6a30338ae1e83a5762a62879e0019e245f30a3
MD5 36f347185fb527b580e71b5fee891844
BLAKE2b-256 26a51bd7a6f703d4f3d2e46469337c52ccfc07bb5964691f80c42e1908ee0cab

See more details on using hashes here.

File details

Details for the file pyield-0.39.8-py3-none-any.whl.

File metadata

  • Download URL: pyield-0.39.8-py3-none-any.whl
  • Upload date:
  • Size: 130.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.1

File hashes

Hashes for pyield-0.39.8-py3-none-any.whl
Algorithm Hash digest
SHA256 75afe7a8aae7b288f17bd9ef2d774d39f4cb7e8c7c978d71f8e7fba7cff8fe78
MD5 0eda1b3bb8e4eed4e8dedff1d3f29a14
BLAKE2b-256 5a062cd53f20e90691a75ea8c402b88b7d6147028596a2edcb3c61b667f03eb6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page