# ---
# jupyter:
#   jupytext:
#     formats: ipynb,py:percent
#     text_representation:
#       extension: .py
#       format_name: percent
#       format_version: '1.3'
#       jupytext_version: 1.19.1
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# %% [markdown]
# # Portfolio credit analytics

# %%
from __future__ import annotations

import sys
from dataclasses import replace
from decimal import Decimal
from pathlib import Path

root = Path.cwd()
if (root / "src").exists():
    sys.path.insert(0, str(root / "src"))
elif (root.parent / "src").exists():
    sys.path.insert(0, str(root.parent / "src"))

from fuggers_py.bonds.instruments import FixedBond  # noqa: E402
from fuggers_py.bonds.types import CreditRating, Sector, YieldCalculationRules  # noqa: E402
from fuggers_py.core import Currency, Date, Frequency  # noqa: E402
from fuggers_py.portfolio import Classification, Holding, PortfolioBuilder, calculate_credit_quality  # noqa: E402


# %%
reference_date = Date.from_ymd(2024, 1, 2)

def make_holding(label: str, years: int, rating: CreditRating, sector: Sector, coupon: str, price: str) -> Holding:
    bond = FixedBond.new(
        issue_date=reference_date,
        maturity_date=reference_date.add_years(years),
        coupon_rate=Decimal(coupon),
        frequency=Frequency.ANNUAL,
        currency=Currency.USD,
        rules=replace(YieldCalculationRules.us_corporate(), frequency=Frequency.ANNUAL),
    )
    return Holding(
        id=label,
        instrument=bond,
        quantity=Decimal("100"),
        clean_price=Decimal(price),
        classification=Classification(sector=sector, rating=rating, currency=Currency.USD),
        label=label,
    )


portfolio = (
    PortfolioBuilder()
    .with_currency(Currency.USD)
    .add_holding(make_holding("aa_gov", 2, CreditRating.AA, Sector.GOVERNMENT, "0.030", "100.5"))
    .add_holding(make_holding("bbb_corp", 5, CreditRating.BBB, Sector.CORPORATE, "0.050", "101.0"))
    .add_holding(make_holding("bb_ind", 8, CreditRating.BB, Sector.INDUSTRIALS, "0.0625", "98.0"))
    .build()
)


# %% [markdown]
# ## Credit-quality summary

# %%
credit_quality = calculate_credit_quality(portfolio)
{
    "distribution": credit_quality["distribution"],
    "average_rating": credit_quality["average_rating"],
    "investment_grade_weight": credit_quality["investment_grade_weight"],
    "high_yield_weight": credit_quality["high_yield_weight"],
    "migration_risk": credit_quality["migration_risk"],
}
