"""
================================================================================
Strategy **D021** — ``s021``
================================================================================

Theme
-----
**RV compression (5d vs 21d) — short straddle.**

Economic idea
-------------
When ``rv_ratio_5_21 < 0.78``, near-term realized volatility has **collapsed** vs the
month window — often after a vol event. Sell **25 DTE** straddle only if **IV still
exceeds RV21** by a cushion ``iv > rv * 1.12``.

Entry
-----
1. ``rv_ratio_5_21 < 0.78``.
2. ``iv_atm(25) > 1.12 * rv21``.
3. ``VIX > 14`` (avoid selling into the absolute floor).
4. ``n_contracts[i] >= 80``.

Exit
----
Short straddle 25 DTE, hold **5** sessions.
================================================================================
"""

from __future__ import annotations

import math

import pandas as pd

from RenTech.core.options_data_loader import OptionChain
from RenTech.strategy_stack.diverse_theta_strategies_v1.context import ResearchContext

META = {"sid": "D021", "theme": "realized_vol_term", "title": "RV5<<RV21 + VRP cushion short straddle"}

HOLD_SESSIONS = 5
TRADE_KIND = "ss"
TRADE_PARAMS = (25,)


def wants_entry(i: int, row: pd.Series, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    rr = row.get("rv_ratio_5_21")
    if rr is None or pd.isna(rr) or float(rr) >= 0.78:
        return False
    rv = float(row["rv21"]) if pd.notna(row.get("rv21")) else float("nan")
    if not math.isfinite(rv) or rv <= 0:
        return False
    iv = ctx.iv_atm_dte(i, 25)
    if iv is None or iv <= 1.12 * rv:
        return False
    vx = ctx.vix(i)
    if not math.isfinite(vx) or vx <= 14.0:
        return False
    if ctx.chain_contracts(i) < 80:
        return False
    if not ch.contracts:
        return False
    _ = spy
    return True
