# ---
# 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]
# # Engine portfolio examples
#
# This notebook shows:
#
# - a small portfolio built from the three engine scenarios
# - aggregate market value, duration, convexity, and DV01
# - key-rate and sector/rating summaries

# %%
from __future__ import annotations

import sys
from decimal import Decimal
from pathlib import Path

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

# %% [markdown]
# ## Imports

# %%
from fuggers_py.engine import PortfolioAnalyzer  # noqa: E402

from tests._engine_scenarios import (  # noqa: E402
    CALLABLE_ID,
    FIXED_ID,
    FRN_ID,
    PORTFOLIO_ID,
    SETTLEMENT,
    fixed_curves,
    frn_curves,
    portfolio_positions,
    pricing_specs,
    router,
    scenario_a_instrument,
    scenario_b_instrument,
    scenario_c_fixing_source,
    scenario_c_instrument,
    scenario_reference_data,
)

# %% [markdown]
# ## Price the positions

# %%
fixed_spec, floating_spec = pricing_specs()
pricing_router = router()
quote_outputs = {
    FIXED_ID: pricing_router.price(
        scenario_a_instrument(),
        SETTLEMENT,
        instrument_id=FIXED_ID,
        market_price=Decimal("101.25"),
        pricing_spec=fixed_spec,
        curves=fixed_curves(),
    ),
    CALLABLE_ID: pricing_router.price(
        scenario_b_instrument(),
        SETTLEMENT,
        instrument_id=CALLABLE_ID,
        market_price=Decimal("102.50"),
        curves=fixed_curves(),
    ),
    FRN_ID: pricing_router.price(
        scenario_c_instrument(),
        SETTLEMENT,
        instrument_id=FRN_ID,
        market_price=Decimal("100.15"),
        pricing_spec=floating_spec,
        curves=frn_curves(),
        market_data=scenario_c_fixing_source(),
    ),
}

quote_outputs

# %% [markdown]
# ## Aggregate the portfolio analytics

# %%
portfolio_output = PortfolioAnalyzer().analyze(
    PORTFOLIO_ID,
    portfolio_positions(),
    quote_outputs,
    reference_data=scenario_reference_data(),
)

print("Total market value:", portfolio_output.total_market_value)
print("Weighted duration:", portfolio_output.weighted_duration)
print("Weighted convexity:", portfolio_output.weighted_convexity)
print("Aggregate DV01:", portfolio_output.aggregate_dv01)
print("Key-rate summary:", portfolio_output.key_rate_durations)
print("Sector summary:", portfolio_output.sector_breakdown)
print("Rating summary:", portfolio_output.rating_breakdown)
