import matplotlib.pyplot as plt
import pandas as pd

from oipd import MarketInputs, ProbCurve, ProbSurface, sources

ticker = "WBD"

expiries = sources.list_expiry_dates(ticker)
expiries

single_expiry = expiries[6]
chain, snapshot = sources.fetch_chain(ticker, expiries=single_expiry)

print(snapshot.underlying_price)
print(single_expiry)

market = MarketInputs(
    valuation_date=snapshot.date,
    underlying_price=snapshot.underlying_price,
    risk_free_rate=0.04,
)

prob = ProbCurve.from_chain(chain, market)

prob.plot()
plt.show()

spot = market.underlying_price
print(spot)


prob_below = prob.prob_below(100)
prob_above = prob.prob_above(150)
prob_between = prob.prob_between(100, 150)

quantiles = {
    "q10": prob.quantile(0.10),
    "q50": prob.quantile(0.50),
    "q90": prob.quantile(0.90),
}

moments = {
    "mean": prob.mean(),
    "variance": prob.variance(),
    "skew": prob.skew(),
    "kurtosis": prob.kurtosis(),
}

{
    "prob_below": prob_below,
    "prob_above": prob_above,
    "prob_between": prob_between,
    **quantiles,
    **moments,
}

ticker = "WBD"

chain_surface, snapshot_surface = sources.fetch_chain(ticker, horizon="12m")

surface_market = MarketInputs(
    valuation_date=snapshot_surface.date,
    risk_free_rate=0.04,
    underlying_price=snapshot_surface.underlying_price,
)

surface = ProbSurface.from_chain(
    chain_surface, surface_market, max_staleness_days=5, failure_policy="skip_warn"
)

# Direct maturity queries on the probability surface
pdf_45d = surface.pdf(surface_market.underlying_price, t=45 / 365.0)
cdf_45d = surface.cdf(
    surface_market.underlying_price,
    t=surface_market.valuation_date + pd.Timedelta(days=45),
)
q50_45d = surface.quantile(0.50, t=45 / 365.0)

print({"pdf_45d": float(pdf_45d), "cdf_45d": float(cdf_45d), "q50_45d": q50_45d})

surface.plot_fan(
    title="Warner Bros Discovery market-implied price forecast over next 12 months"
)
plt.show()
