BONO


NameBONO JSON
Version 1.1.4 PyPI version JSON
download
home_pagehttps://github.com/LuisHCalderon
SummaryLibrería para análisis y cálculos de bonos financieros
upload_time2024-11-24 04:03:43
maintainerNone
docs_urlNone
authorLuis Humberto Calderon Baldeón
requires_python>=3.7
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
### Bond Library
A Python library for performing calculations and analyses related to financial bonds. Ideal for financial analysts, finance students, and developers interested in financial engineering.

#### Summary of Examples:
* Basic bond valuation (coupon and zero-coupon bonds).
* Calculating bond sensitivity (Macaulay duration).
* Yield to Maturity (YTM) calculation.
* Generating cash flows for bonds.
* Portfolio analysis (total value and weighted average duration).
* Yield curve analysis.
* Calculating bond risk measures (Duration and Convexity).
* Simulating interest rate scenarios and their impact on bond cash flows.
* Visualizing bond cash flows and simulated interest rates.
* Comparing multiple bonds to select the best option based on Net Present Value (NPV).


### 1. Bond Valuation
Calculate the price of bonds, including coupon bonds and zero-coupon bonds.

**Example: Valuing a bond**

```python
from bonos.valuacion import precio_bono
```
*#Inputs: Face value (nominal value), coupon rate, discount rate, periods, payment frequency*
```python
bond_price = precio_bono(valor_nominal=1000, tasa_cupon=5, tasa_descuento=3, periodos=5, frecuencia=1)
print(f"The bond price is: {bond_price}")
```

**Example: Valuing a zero-coupon bond**

```python
from bonos.valuacion import precio_bono
```

*#Zero-coupon bond: coupon rate = 0*
```python
zero_coupon_price = precio_bono(valor_nominal=1000, tasa_cupon=0, tasa_descuento=4, periodos=10, frecuencia=1)
print(f"The zero-coupon bond price is: {zero_coupon_price}")
```

### 2. Bond Sensitivity
Calculate the Macaulay Duration, a measure of a bond’s sensitivity to interest rate changes.

**Example: Calculating Macaulay Duration**

```python
from bonos.sensibilidad import duracion_macaulay
```

*#Inputs: Face value, coupon rate, discount rate, periods, payment frequency*
```python
duration = duracion_macaulay(valor_nominal=1000, tasa_cupon=5, tasa_descuento=3, periodos=5, frecuencia=1)
print(f"The Macaulay duration is: {duration}")
```
**Example: Duration of a zero-coupon bond**
```python
from bonos.sensibilidad import duracion_macaulay
```
*#Zero-coupon bond: coupon rate = 0*
```python
zero_coupon_duration = duracion_macaulay(valor_nominal=1000, tasa_cupon=0, tasa_descuento=4, periodos=10, frecuencia=1)
print(f"The duration of the zero-coupon bond is: {zero_coupon_duration}")
```

### 3. Yield to Maturity (YTM)
Calculate the Yield to Maturity (YTM), which represents the bond's expected annual return if held until maturity.

**Example: Calculating YTM**
```python
from bonos.tasas import rendimiento_vencimiento
```
*#Inputs: Bond price, face value, coupon rate, periods, payment frequency*
```python
ytm = rendimiento_vencimiento(precio_bono=950, valor_nominal=1000, tasa_cupon=5, periodos=10, frecuencia=1)
print(f"The yield to maturity (YTM) is: {ytm}%")
```

**Example: YTM with semi-annual payments**
```python
from bonos.tasas import rendimiento_vencimiento
```
*#Semi-annual payments: frequency = 2*
```python
ytm_semi_annual = rendimiento_vencimiento(precio_bono=950, valor_nominal=1000, tasa_cupon=5, periodos=10, frecuencia=2)
print(f"The semi-annual yield to maturity (YTM) is: {ytm_semi_annual}%")
```

### 4. Cash Flow Generation
Generate the cash flows of a bond, including periodic coupon payments and the redemption of the face value.

**Example: Generating cash flows**
```python
from bonos.flujos import generar_flujos
```
*#Inputs: Face value, coupon rate, periods, payment frequency*
```python
cash_flows = generar_flujos(valor_nominal=1000, tasa_cupon=5, periodos=5, frecuencia=2)
print(f"Cash flows: {cash_flows}")
```
**Example: Cash flows for a zero-coupon bond**
```python
from bonos.flujos import generar_flujos
```
*#Zero-coupon bond: coupon rate = 0*
```python
zero_coupon_flows = generar_flujos(valor_nominal=1000, tasa_cupon=0, periodos=10, frecuencia=1)
print(f"Cash flows for zero-coupon bond: {zero_coupon_flows}")
```

### 5. Advanced Example, Bond Portfolio Analysis
Combine the library's features to analyze a portfolio of bonds. For instance, calculate the total portfolio value and its weighted average duration.

**Example: Portfolio Analysis**
```python
from bonos.valuacion import precio_bono
from bonos.sensibilidad import duracion_macaulay
```
*#Define portfolio bonds*
```python
bonds = [
    {"valor_nominal": 1000, "tasa_cupon": 5, "tasa_descuento": 3, "periodos": 5, "frecuencia": 1},
    {"valor_nominal": 2000, "tasa_cupon": 4, "tasa_descuento": 3.5, "periodos": 10, "frecuencia": 2},
    {"valor_nominal": 1500, "tasa_cupon": 6, "tasa_descuento": 4, "periodos": 7, "frecuencia": 1},
]
```
*#Calculate the price and duration for each bond*
```python
portfolio_value = 0
weighted_durations = 0
for bond in bonds:
    # Calculate bond price
    price = precio_bono(
        valor_nominal=bond["valor_nominal"],
        tasa_cupon=bond["tasa_cupon"],
        tasa_descuento=bond["tasa_descuento"],
        periodos=bond["periodos"],
        frecuencia=bond["frecuencia"]
    )
    # Calculate Macaulay duration
    duration = duracion_macaulay(
        valor_nominal=bond["valor_nominal"],
        tasa_cupon=bond["tasa_cupon"],
        tasa_descuento=bond["tasa_descuento"],
        periodos=bond["periodos"],
        frecuencia=bond["frecuencia"]
    )
    # Update portfolio totals
    portfolio_value += price
    weighted_durations += price * duration
```
*#Calculate weighted average duration*
```python
weighted_average_duration = weighted_durations / portfolio_value

print(f"Total portfolio value: {portfolio_value}")
print(f"Weighted average duration: {weighted_average_duration}")
```

### 6. Advanced Example, Bond Yield Curve Analysis
You can use the library to analyze the yield curve of bonds with different maturities, calculating their YTMs and plotting the curve.

**Example: Yield Curve Analysis**
```python
from bonos.tasas import rendimiento_vencimiento
import matplotlib.pyplot as plt
```
*#Define a series of bonds with different maturities and prices*
```python
bonds = [
    {"precio_bono": 980, "valor_nominal": 1000, "tasa_cupon": 3, "periodos": 2, "frecuencia": 1},
    {"precio_bono": 950, "valor_nominal": 1000, "tasa_cupon": 4, "periodos": 5, "frecuencia": 1},
    {"precio_bono": 920, "valor_nominal": 1000, "tasa_cupon": 5, "periodos": 10, "frecuencia": 1},
    {"precio_bono": 890, "valor_nominal": 1000, "tasa_cupon": 6, "periodos": 20, "frecuencia": 1},
]
```
*#Calculate YTM for each bond and store maturities and YTMs*
```python
maturities = []
ytms = []
for bond in bonds:
    ytm = rendimiento_vencimiento(
        precio_bono=bond["precio_bono"],
        valor_nominal=bond["valor_nominal"],
        tasa_cupon=bond["tasa_cupon"],
        periodos=bond["periodos"],
        frecuencia=bond["frecuencia"]
    )
    maturities.append(bond["periodos"])
    ytms.append(ytm)
```
*#Plot the yield curve*
```python
plt.plot(maturities, ytms, marker='o')
plt.title("Bond Yield Curve")
plt.xlabel("Maturity (Years)")
plt.ylabel("Yield to Maturity (YTM)")
plt.grid()
plt.show()
```
### 7. Risk Analysis (Duration and Convexity)
Measure the risk of a bond by calculating its Macaulay Duration and Convexity, which provide insights into the bond's sensitivity to interest rate changes.

**Example: Calculating Duration and Convexity**
```python
from bonos.riesgo import calcular_duracion, calcular_convexidad
```
*#Inputs: Cash flows, discount rate, and corresponding time periods*
*# Define bond cash flows and time periods*
```python
flujos = [100, 100, 1100]  # Cash flows (e.g., annual coupons + face value)
tasas = 0.05              # Discount rate (5%)
plazos = [1, 2, 3]        # Time periods in years
```
*# Calculate Macaulay Duration*
```python
duracion = calcular_duracion(flujos, tasas, plazos)
print(f"The bond's Macaulay Duration is: {duracion}")
```
*# Calculate Convexity*
```python
convexidad = calcular_convexidad(flujos, tasas, plazos)
print(f"The bond's Convexity is: {convexidad}")
```
### 8. Scenario Simulation
Simulate various interest rate scenarios and evaluate their impact on bond cash flows and values. This helps in analyzing the bond's performance under changing market conditions.

**Example: Simulating Interest Rate Scenarios**
```python
from bonos.simulacion import simular_tasas_inflacion, simular_flujos_bono
import numpy as np
```
*#Inputs: Base interest rate, standard deviation, number of scenarios*
*# Simulate 1000 interest rate scenarios around a base rate of 5% with 1% volatility*
```python
tasas_simuladas = simular_tasas_inflacion(base_tasa=0.05, desviacion=0.01, num_escenarios=1000)
print(f"Simulated interest rates: {tasas_simuladas[:10]}")  # Display first 10 scenarios
```
*# Simulate cash flows under each interest rate scenario*
```python
flujos = [100, 100, 1100]  # Bond cash flows
plazos = [1, 2, 3]         # Corresponding time periods
escenarios_flujos = simular_flujos_bono(flujos, tasas_simuladas, plazos)
```
*# Example: Print present value of cash flows for the first scenario*
```python
print(f"Present value of cash flows (Scenario 1): {escenarios_flujos[0]}")
```
### 9. Visualization
Generate visualizations to better understand bond cash flows, interest rate scenarios, and other analyses.

**Example 1: Visualizing Bond Cash Flows**
```python
from bonos.visualizacion import graficar_flujos
```
*#Inputs: Cash flows and time periods*
```python
flujos = [100, 100, 1100]
plazos = [1, 2, 3]

graficar_flujos(flujos, plazos)
# This produces a bar chart showing cash flows against their corresponding maturities.
```
**Example 2: Visualizing Simulated Interest Rates**
```python
from bonos.visualizacion import graficar_tasas_simuladas
```
*#Inputs: Array of simulated interest rates*
```python
tasas_simuladas = [0.04, 0.05, 0.06, 0.07, 0.04]
graficar_tasas_simuladas(tasas_simuladas)
#This produces a histogram of the simulated interest rates.
```
### 10. Optimization and Bond Comparison
Compare multiple bonds to select the one that best fits your investment strategy. For instance, you can select the bond with the highest Net Present Value (NPV).

**Example: Comparing Bonds**
```python
from bonos.optimizacion import comparar_bonos
```
*#Inputs: List of bonds with their cash flows and discount rates*

*# Define multiple bonds*
```python
bonds = [
    {"flujos": [100, 100, 1100], "plazos": [1, 2, 3]},  # Bond 1
    {"flujos": [50, 50, 1050], "plazos": [1, 2, 3]},   # Bond 2
    {"flujos": [200, 200, 1200], "plazos": [1, 2, 3]}  # Bond 3
]
```

*# Compare bonds and select the best one based*
```python
tasa_descuento = 0.05  # 5% discount rate
mejor_bono = comparar_bonos(bonds, tasa_descuento)
```

*# Output the best bond*
```python
print(f"The best bond is: {mejor_bono['bono']}")
print(f"Net Present Value (NPV): {mejor_bono['vpn']}")
#In this example, the bond with the highest Net Present Value (NPV) is selected.
```

### Full Example Workflow:
Combine these functionalities to conduct a comprehensive bond analysis:

```python
from bonos.riesgo import calcular_duracion, calcular_convexidad
from bonos.simulacion import simular_tasas_inflacion, simular_flujos_bono
from bonos.visualizacion import graficar_flujos
from bonos.optimizacion import comparar_bonos

# Step 1: Define bond details
flujos = [100, 100, 1100]
plazos = [1, 2, 3]
tasa_descuento = 0.05

# Step 2: Calculate risk measures (duration and convexity)
duracion = calcular_duracion(flujos, tasa_descuento, plazos)
convexidad = calcular_convexidad(flujos, tasa_descuento, plazos)

print(f"Duration: {duracion}")
print(f"Convexity: {convexidad}")

# Step 3: Simulate interest rate scenarios
tasas_simuladas = simular_tasas_inflacion(base_tasa=0.05, desviacion=0.01, num_escenarios=1000)

# Step 4: Simulate present values of cash flows under each scenario
escenarios_flujos = simular_flujos_bono(flujos, tasas_simuladas, plazos)

# Step 5: Visualize bond cash flows
graficar_flujos(flujos, plazos)

# Step 6: Compare bonds (if there are multiple bonds)
bonds = [
    {"flujos": [100, 100, 1100], "plazos": [1, 2, 3]},
    {"flujos": [50, 50, 1050], "plazos": [1, 2, 3]},
    {"flujos": [200, 200, 1200], "plazos": [1, 2, 3]}
]
mejor_bono = comparar_bonos(bonds, tasa_descuento)

print(f"The best bond is: {mejor_bono['bono']}")
print(f"Net Present Value (NPV): {mejor_bono['vpn']}")
```

#### License
This project is licensed under the MIT License.<p>
```python
Luis Humberto Calderon B.
UNIVERSIDAD NACIONAL DE INGENIERIA
Lima-Peru, 2024
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/LuisHCalderon",
    "name": "BONO",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": null,
    "author": "Luis Humberto Calderon Balde\u00f3n",
    "author_email": "luis.calderon.b@uni.pe",
    "download_url": "https://files.pythonhosted.org/packages/dd/fe/efc5a307230df7dbe3d42090475e95d70fd18123e066353cf58113da975a/bono-1.1.4.tar.gz",
    "platform": null,
    "description": "\r\n### Bond Library\r\nA Python library for performing calculations and analyses related to financial bonds. Ideal for financial analysts, finance students, and developers interested in financial engineering.\r\n\r\n#### Summary of Examples:\r\n* Basic bond valuation (coupon and zero-coupon bonds).\r\n* Calculating bond sensitivity (Macaulay duration).\r\n* Yield to Maturity (YTM) calculation.\r\n* Generating cash flows for bonds.\r\n* Portfolio analysis (total value and weighted average duration).\r\n* Yield curve analysis.\r\n* Calculating bond risk measures (Duration and Convexity).\r\n* Simulating interest rate scenarios and their impact on bond cash flows.\r\n* Visualizing bond cash flows and simulated interest rates.\r\n* Comparing multiple bonds to select the best option based on Net Present Value (NPV).\r\n\r\n\r\n### 1. Bond Valuation\r\nCalculate the price of bonds, including coupon bonds and zero-coupon bonds.\r\n\r\n**Example: Valuing a bond**\r\n\r\n```python\r\nfrom bonos.valuacion import precio_bono\r\n```\r\n*#Inputs: Face value (nominal value), coupon rate, discount rate, periods, payment frequency*\r\n```python\r\nbond_price = precio_bono(valor_nominal=1000, tasa_cupon=5, tasa_descuento=3, periodos=5, frecuencia=1)\r\nprint(f\"The bond price is: {bond_price}\")\r\n```\r\n\r\n**Example: Valuing a zero-coupon bond**\r\n\r\n```python\r\nfrom bonos.valuacion import precio_bono\r\n```\r\n\r\n*#Zero-coupon bond: coupon rate = 0*\r\n```python\r\nzero_coupon_price = precio_bono(valor_nominal=1000, tasa_cupon=0, tasa_descuento=4, periodos=10, frecuencia=1)\r\nprint(f\"The zero-coupon bond price is: {zero_coupon_price}\")\r\n```\r\n\r\n### 2. Bond Sensitivity\r\nCalculate the Macaulay Duration, a measure of a bond\u00e2\u20ac\u2122s sensitivity to interest rate changes.\r\n\r\n**Example: Calculating Macaulay Duration**\r\n\r\n```python\r\nfrom bonos.sensibilidad import duracion_macaulay\r\n```\r\n\r\n*#Inputs: Face value, coupon rate, discount rate, periods, payment frequency*\r\n```python\r\nduration = duracion_macaulay(valor_nominal=1000, tasa_cupon=5, tasa_descuento=3, periodos=5, frecuencia=1)\r\nprint(f\"The Macaulay duration is: {duration}\")\r\n```\r\n**Example: Duration of a zero-coupon bond**\r\n```python\r\nfrom bonos.sensibilidad import duracion_macaulay\r\n```\r\n*#Zero-coupon bond: coupon rate = 0*\r\n```python\r\nzero_coupon_duration = duracion_macaulay(valor_nominal=1000, tasa_cupon=0, tasa_descuento=4, periodos=10, frecuencia=1)\r\nprint(f\"The duration of the zero-coupon bond is: {zero_coupon_duration}\")\r\n```\r\n\r\n### 3. Yield to Maturity (YTM)\r\nCalculate the Yield to Maturity (YTM), which represents the bond's expected annual return if held until maturity.\r\n\r\n**Example: Calculating YTM**\r\n```python\r\nfrom bonos.tasas import rendimiento_vencimiento\r\n```\r\n*#Inputs: Bond price, face value, coupon rate, periods, payment frequency*\r\n```python\r\nytm = rendimiento_vencimiento(precio_bono=950, valor_nominal=1000, tasa_cupon=5, periodos=10, frecuencia=1)\r\nprint(f\"The yield to maturity (YTM) is: {ytm}%\")\r\n```\r\n\r\n**Example: YTM with semi-annual payments**\r\n```python\r\nfrom bonos.tasas import rendimiento_vencimiento\r\n```\r\n*#Semi-annual payments: frequency = 2*\r\n```python\r\nytm_semi_annual = rendimiento_vencimiento(precio_bono=950, valor_nominal=1000, tasa_cupon=5, periodos=10, frecuencia=2)\r\nprint(f\"The semi-annual yield to maturity (YTM) is: {ytm_semi_annual}%\")\r\n```\r\n\r\n### 4. Cash Flow Generation\r\nGenerate the cash flows of a bond, including periodic coupon payments and the redemption of the face value.\r\n\r\n**Example: Generating cash flows**\r\n```python\r\nfrom bonos.flujos import generar_flujos\r\n```\r\n*#Inputs: Face value, coupon rate, periods, payment frequency*\r\n```python\r\ncash_flows = generar_flujos(valor_nominal=1000, tasa_cupon=5, periodos=5, frecuencia=2)\r\nprint(f\"Cash flows: {cash_flows}\")\r\n```\r\n**Example: Cash flows for a zero-coupon bond**\r\n```python\r\nfrom bonos.flujos import generar_flujos\r\n```\r\n*#Zero-coupon bond: coupon rate = 0*\r\n```python\r\nzero_coupon_flows = generar_flujos(valor_nominal=1000, tasa_cupon=0, periodos=10, frecuencia=1)\r\nprint(f\"Cash flows for zero-coupon bond: {zero_coupon_flows}\")\r\n```\r\n\r\n### 5. Advanced Example, Bond Portfolio Analysis\r\nCombine the library's features to analyze a portfolio of bonds. For instance, calculate the total portfolio value and its weighted average duration.\r\n\r\n**Example: Portfolio Analysis**\r\n```python\r\nfrom bonos.valuacion import precio_bono\r\nfrom bonos.sensibilidad import duracion_macaulay\r\n```\r\n*#Define portfolio bonds*\r\n```python\r\nbonds = [\r\n    {\"valor_nominal\": 1000, \"tasa_cupon\": 5, \"tasa_descuento\": 3, \"periodos\": 5, \"frecuencia\": 1},\r\n    {\"valor_nominal\": 2000, \"tasa_cupon\": 4, \"tasa_descuento\": 3.5, \"periodos\": 10, \"frecuencia\": 2},\r\n    {\"valor_nominal\": 1500, \"tasa_cupon\": 6, \"tasa_descuento\": 4, \"periodos\": 7, \"frecuencia\": 1},\r\n]\r\n```\r\n*#Calculate the price and duration for each bond*\r\n```python\r\nportfolio_value = 0\r\nweighted_durations = 0\r\nfor bond in bonds:\r\n    # Calculate bond price\r\n    price = precio_bono(\r\n        valor_nominal=bond[\"valor_nominal\"],\r\n        tasa_cupon=bond[\"tasa_cupon\"],\r\n        tasa_descuento=bond[\"tasa_descuento\"],\r\n        periodos=bond[\"periodos\"],\r\n        frecuencia=bond[\"frecuencia\"]\r\n    )\r\n    # Calculate Macaulay duration\r\n    duration = duracion_macaulay(\r\n        valor_nominal=bond[\"valor_nominal\"],\r\n        tasa_cupon=bond[\"tasa_cupon\"],\r\n        tasa_descuento=bond[\"tasa_descuento\"],\r\n        periodos=bond[\"periodos\"],\r\n        frecuencia=bond[\"frecuencia\"]\r\n    )\r\n    # Update portfolio totals\r\n    portfolio_value += price\r\n    weighted_durations += price * duration\r\n```\r\n*#Calculate weighted average duration*\r\n```python\r\nweighted_average_duration = weighted_durations / portfolio_value\r\n\r\nprint(f\"Total portfolio value: {portfolio_value}\")\r\nprint(f\"Weighted average duration: {weighted_average_duration}\")\r\n```\r\n\r\n### 6. Advanced Example, Bond Yield Curve Analysis\r\nYou can use the library to analyze the yield curve of bonds with different maturities, calculating their YTMs and plotting the curve.\r\n\r\n**Example: Yield Curve Analysis**\r\n```python\r\nfrom bonos.tasas import rendimiento_vencimiento\r\nimport matplotlib.pyplot as plt\r\n```\r\n*#Define a series of bonds with different maturities and prices*\r\n```python\r\nbonds = [\r\n    {\"precio_bono\": 980, \"valor_nominal\": 1000, \"tasa_cupon\": 3, \"periodos\": 2, \"frecuencia\": 1},\r\n    {\"precio_bono\": 950, \"valor_nominal\": 1000, \"tasa_cupon\": 4, \"periodos\": 5, \"frecuencia\": 1},\r\n    {\"precio_bono\": 920, \"valor_nominal\": 1000, \"tasa_cupon\": 5, \"periodos\": 10, \"frecuencia\": 1},\r\n    {\"precio_bono\": 890, \"valor_nominal\": 1000, \"tasa_cupon\": 6, \"periodos\": 20, \"frecuencia\": 1},\r\n]\r\n```\r\n*#Calculate YTM for each bond and store maturities and YTMs*\r\n```python\r\nmaturities = []\r\nytms = []\r\nfor bond in bonds:\r\n    ytm = rendimiento_vencimiento(\r\n        precio_bono=bond[\"precio_bono\"],\r\n        valor_nominal=bond[\"valor_nominal\"],\r\n        tasa_cupon=bond[\"tasa_cupon\"],\r\n        periodos=bond[\"periodos\"],\r\n        frecuencia=bond[\"frecuencia\"]\r\n    )\r\n    maturities.append(bond[\"periodos\"])\r\n    ytms.append(ytm)\r\n```\r\n*#Plot the yield curve*\r\n```python\r\nplt.plot(maturities, ytms, marker='o')\r\nplt.title(\"Bond Yield Curve\")\r\nplt.xlabel(\"Maturity (Years)\")\r\nplt.ylabel(\"Yield to Maturity (YTM)\")\r\nplt.grid()\r\nplt.show()\r\n```\r\n### 7. Risk Analysis (Duration and Convexity)\r\nMeasure the risk of a bond by calculating its Macaulay Duration and Convexity, which provide insights into the bond's sensitivity to interest rate changes.\r\n\r\n**Example: Calculating Duration and Convexity**\r\n```python\r\nfrom bonos.riesgo import calcular_duracion, calcular_convexidad\r\n```\r\n*#Inputs: Cash flows, discount rate, and corresponding time periods*\r\n*# Define bond cash flows and time periods*\r\n```python\r\nflujos = [100, 100, 1100]  # Cash flows (e.g., annual coupons + face value)\r\ntasas = 0.05              # Discount rate (5%)\r\nplazos = [1, 2, 3]        # Time periods in years\r\n```\r\n*# Calculate Macaulay Duration*\r\n```python\r\nduracion = calcular_duracion(flujos, tasas, plazos)\r\nprint(f\"The bond's Macaulay Duration is: {duracion}\")\r\n```\r\n*# Calculate Convexity*\r\n```python\r\nconvexidad = calcular_convexidad(flujos, tasas, plazos)\r\nprint(f\"The bond's Convexity is: {convexidad}\")\r\n```\r\n### 8. Scenario Simulation\r\nSimulate various interest rate scenarios and evaluate their impact on bond cash flows and values. This helps in analyzing the bond's performance under changing market conditions.\r\n\r\n**Example: Simulating Interest Rate Scenarios**\r\n```python\r\nfrom bonos.simulacion import simular_tasas_inflacion, simular_flujos_bono\r\nimport numpy as np\r\n```\r\n*#Inputs: Base interest rate, standard deviation, number of scenarios*\r\n*# Simulate 1000 interest rate scenarios around a base rate of 5% with 1% volatility*\r\n```python\r\ntasas_simuladas = simular_tasas_inflacion(base_tasa=0.05, desviacion=0.01, num_escenarios=1000)\r\nprint(f\"Simulated interest rates: {tasas_simuladas[:10]}\")  # Display first 10 scenarios\r\n```\r\n*# Simulate cash flows under each interest rate scenario*\r\n```python\r\nflujos = [100, 100, 1100]  # Bond cash flows\r\nplazos = [1, 2, 3]         # Corresponding time periods\r\nescenarios_flujos = simular_flujos_bono(flujos, tasas_simuladas, plazos)\r\n```\r\n*# Example: Print present value of cash flows for the first scenario*\r\n```python\r\nprint(f\"Present value of cash flows (Scenario 1): {escenarios_flujos[0]}\")\r\n```\r\n### 9. Visualization\r\nGenerate visualizations to better understand bond cash flows, interest rate scenarios, and other analyses.\r\n\r\n**Example 1: Visualizing Bond Cash Flows**\r\n```python\r\nfrom bonos.visualizacion import graficar_flujos\r\n```\r\n*#Inputs: Cash flows and time periods*\r\n```python\r\nflujos = [100, 100, 1100]\r\nplazos = [1, 2, 3]\r\n\r\ngraficar_flujos(flujos, plazos)\r\n# This produces a bar chart showing cash flows against their corresponding maturities.\r\n```\r\n**Example 2: Visualizing Simulated Interest Rates**\r\n```python\r\nfrom bonos.visualizacion import graficar_tasas_simuladas\r\n```\r\n*#Inputs: Array of simulated interest rates*\r\n```python\r\ntasas_simuladas = [0.04, 0.05, 0.06, 0.07, 0.04]\r\ngraficar_tasas_simuladas(tasas_simuladas)\r\n#This produces a histogram of the simulated interest rates.\r\n```\r\n### 10. Optimization and Bond Comparison\r\nCompare multiple bonds to select the one that best fits your investment strategy. For instance, you can select the bond with the highest Net Present Value (NPV).\r\n\r\n**Example: Comparing Bonds**\r\n```python\r\nfrom bonos.optimizacion import comparar_bonos\r\n```\r\n*#Inputs: List of bonds with their cash flows and discount rates*\r\n\r\n*# Define multiple bonds*\r\n```python\r\nbonds = [\r\n    {\"flujos\": [100, 100, 1100], \"plazos\": [1, 2, 3]},  # Bond 1\r\n    {\"flujos\": [50, 50, 1050], \"plazos\": [1, 2, 3]},   # Bond 2\r\n    {\"flujos\": [200, 200, 1200], \"plazos\": [1, 2, 3]}  # Bond 3\r\n]\r\n```\r\n\r\n*# Compare bonds and select the best one based*\r\n```python\r\ntasa_descuento = 0.05  # 5% discount rate\r\nmejor_bono = comparar_bonos(bonds, tasa_descuento)\r\n```\r\n\r\n*# Output the best bond*\r\n```python\r\nprint(f\"The best bond is: {mejor_bono['bono']}\")\r\nprint(f\"Net Present Value (NPV): {mejor_bono['vpn']}\")\r\n#In this example, the bond with the highest Net Present Value (NPV) is selected.\r\n```\r\n\r\n### Full Example Workflow:\r\nCombine these functionalities to conduct a comprehensive bond analysis:\r\n\r\n```python\r\nfrom bonos.riesgo import calcular_duracion, calcular_convexidad\r\nfrom bonos.simulacion import simular_tasas_inflacion, simular_flujos_bono\r\nfrom bonos.visualizacion import graficar_flujos\r\nfrom bonos.optimizacion import comparar_bonos\r\n\r\n# Step 1: Define bond details\r\nflujos = [100, 100, 1100]\r\nplazos = [1, 2, 3]\r\ntasa_descuento = 0.05\r\n\r\n# Step 2: Calculate risk measures (duration and convexity)\r\nduracion = calcular_duracion(flujos, tasa_descuento, plazos)\r\nconvexidad = calcular_convexidad(flujos, tasa_descuento, plazos)\r\n\r\nprint(f\"Duration: {duracion}\")\r\nprint(f\"Convexity: {convexidad}\")\r\n\r\n# Step 3: Simulate interest rate scenarios\r\ntasas_simuladas = simular_tasas_inflacion(base_tasa=0.05, desviacion=0.01, num_escenarios=1000)\r\n\r\n# Step 4: Simulate present values of cash flows under each scenario\r\nescenarios_flujos = simular_flujos_bono(flujos, tasas_simuladas, plazos)\r\n\r\n# Step 5: Visualize bond cash flows\r\ngraficar_flujos(flujos, plazos)\r\n\r\n# Step 6: Compare bonds (if there are multiple bonds)\r\nbonds = [\r\n    {\"flujos\": [100, 100, 1100], \"plazos\": [1, 2, 3]},\r\n    {\"flujos\": [50, 50, 1050], \"plazos\": [1, 2, 3]},\r\n    {\"flujos\": [200, 200, 1200], \"plazos\": [1, 2, 3]}\r\n]\r\nmejor_bono = comparar_bonos(bonds, tasa_descuento)\r\n\r\nprint(f\"The best bond is: {mejor_bono['bono']}\")\r\nprint(f\"Net Present Value (NPV): {mejor_bono['vpn']}\")\r\n```\r\n\r\n#### License\r\nThis project is licensed under the MIT License.<p>\r\n```python\r\nLuis Humberto Calderon B.\r\nUNIVERSIDAD NACIONAL DE INGENIERIA\r\nLima-Peru, 2024\r\n```\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Librer\u00eda para an\u00e1lisis y c\u00e1lculos de bonos financieros",
    "version": "1.1.4",
    "project_urls": {
        "Homepage": "https://github.com/LuisHCalderon"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f88a14574ebdd2afcc4090c8baed6e7fb5a1542e8fca5ff3ab3cb0bc6e3e7029",
                "md5": "6cbd6c10cf554af64d1568b80c539a1a",
                "sha256": "d691d8d06520d3f1c56c29205bd071538ca795d744ad1e633ebeb41e682b7f2a"
            },
            "downloads": -1,
            "filename": "BONO-1.1.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6cbd6c10cf554af64d1568b80c539a1a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 12565,
            "upload_time": "2024-11-24T04:03:41",
            "upload_time_iso_8601": "2024-11-24T04:03:41.197483Z",
            "url": "https://files.pythonhosted.org/packages/f8/8a/14574ebdd2afcc4090c8baed6e7fb5a1542e8fca5ff3ab3cb0bc6e3e7029/BONO-1.1.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ddfeefc5a307230df7dbe3d42090475e95d70fd18123e066353cf58113da975a",
                "md5": "e2971793aa1964f2e022bdde2a97f9f5",
                "sha256": "4b0d48a4a8b2761c7050218aa31070d40dfad07f7560a19cbec3a9bbe5a71cc9"
            },
            "downloads": -1,
            "filename": "bono-1.1.4.tar.gz",
            "has_sig": false,
            "md5_digest": "e2971793aa1964f2e022bdde2a97f9f5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 12175,
            "upload_time": "2024-11-24T04:03:43",
            "upload_time_iso_8601": "2024-11-24T04:03:43.147289Z",
            "url": "https://files.pythonhosted.org/packages/dd/fe/efc5a307230df7dbe3d42090475e95d70fd18123e066353cf58113da975a/bono-1.1.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-24 04:03:43",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "bono"
}
        
Elapsed time: 0.40688s