# ---
# 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 ETF examples
#
# This notebook shows:
#
# - ETF holdings setup
# - routed instrument pricing
# - ETF iNAV and weighted analytics

# %%
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 EtfPricer  # noqa: E402
from fuggers_py.data import (
    EtfHolding,
    InstrumentId,
)

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

# %% [markdown]
# ## Price the underlying holdings

# %%
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]
# ## Define ETF holdings and compute iNAV

# %%
holdings = [
    EtfHolding(InstrumentId(str(FIXED_ID)), quantity=Decimal("100")),
    EtfHolding(InstrumentId(str(CALLABLE_ID)), quantity=Decimal("80")),
    EtfHolding(InstrumentId(str(FRN_ID)), quantity=Decimal("120")),
]

etf_output = EtfPricer().price(ETF_ID, holdings, quote_outputs, shares_outstanding=Decimal("10000"))

print("Gross market value:", etf_output.gross_market_value)
print("NAV / iNAV:", etf_output.nav, etf_output.inav)
print("Weighted duration:", etf_output.weighted_duration)
print("Weighted convexity:", etf_output.weighted_convexity)
print("Fully priced:", etf_output.fully_priced)
