"""Would the CURRENT maker strategy do better on Poly-US than on Kalshi?

Same strategy, two venues. A three-leg book earns the overround and pays (or is
paid) the venue's maker fee, so the comparison reduces to two numbers:

    net per completed book = (sum of asks - 1.00) - fees        [Kalshi]
                           = (sum of asks - 1.00) + rebate      [Poly-US]

FEE ASYMMETRY -- the thing that makes this worth asking:
  Kalshi  CHARGES the maker 0.0175 * p(1-p) per contract. Measured, not quoted:
          a 1-contract fill at 0.40 cost 0.0042 (mm_maker_live.MAKER_FEE_RATE).
  Poly-US CREDITS the maker 0.0125 * p(1-p) (pus_premium_curve.MAKER_THETA).

On a typical 3-way book that swing is ~0.03 * sum(p(1-p)) ~= 2c, against a book
whose gross margin is only ~2c. So the fee line is the same order as the entire
edge, and the venue choice could matter more than any rule tuning done so far.

HONEST LIMIT: Poly-US publishes no trade tape. `last_px` is a level sampled
every ~20s, so a fill is only inferred from a CHANGE in that level and
consecutive trades at one price are invisible. Poly-US fill/completion numbers
are therefore a FLOOR, and are NOT comparable like-for-like to Kalshi's
tape-derived ones. Overround and fees ARE comparable -- those are quoted state.

Usage:  python research\\venue_compare_maker.py
"""
import csv
import io
import statistics
from collections import defaultdict
from pathlib import Path

KALSHI = Path(r'E:\soccer\research\mm_paper_quotes.csv')
POLYUS = Path(r'E:\soccer\research\mm_polyus_quotes.csv')

KALSHI_FEE = 0.0175      # charged to the maker
POLYUS_REBATE = 0.0125   # paid to the maker


def rows(path, cols):
    """Stream a big CSV, yielding only the columns asked for."""
    with path.open('r', encoding='utf-8', errors='replace', newline='') as fh:
        for r in csv.DictReader(fh):
            yield {c: r.get(c) for c in cols}


def f(v):
    try:
        return float(v)
    except (TypeError, ValueError):
        return None


def book_overrounds(path, key_cols, ask_col, ts_col='ts'):
    """Per (event, snapshot) sum of the three leg asks."""
    snap = defaultdict(dict)
    for r in rows(path, key_cols + [ask_col, ts_col]):
        a = f(r.get(ask_col))
        if a is None or not (0 < a < 1):
            continue
        key = tuple(r.get(c) or '' for c in key_cols)
        side = r.get(key_cols[-1]) or ''
        snap[(key[0], (r.get(ts_col) or '')[:16])][side] = a
    out = []
    for _, legs in snap.items():
        if len(legs) == 3:
            out.append(sum(legs.values()))
    return out


def summarise(name, sums, fee_rate, is_rebate):
    if not sums:
        print(f'{name}: no complete 3-leg snapshots found')
        return
    sums.sort()
    n = len(sums)
    med = sums[n // 2]
    # fee/rebate on a book whose legs sum to `med`: approximate each leg at
    # med/3 for the p(1-p) term, which is what the venue actually charges on.
    p = med / 3.0
    per_book = 3 * fee_rate * p * (1 - p)
    gross = (med - 1.0) * 100
    net = gross + (per_book * 100 if is_rebate else -per_book * 100)
    print(f'{name}')
    print(f'   3-leg snapshots      : {n:,}')
    print(f'   overround at ask     : med {gross:+.2f}c   '
          f'p25 {(sums[n//4]-1)*100:+.2f}c   p75 {(sums[3*n//4]-1)*100:+.2f}c')
    print(f'   pct of books >100c   : {100.0*sum(1 for s in sums if s > 1.0)/n:.1f}%')
    print(f'   maker {"rebate" if is_rebate else "fee":<7}        : '
          f'{"+" if is_rebate else "-"}{per_book*100:.2f}c per book')
    print(f'   NET per completed    : {net:+.2f}c')
    print()
    return net


def main():
    print('=== overround available at the ask, per three-leg book ===')
    print()
    k = book_overrounds(KALSHI, ['event', 'side'], 'k_ask')
    nk = summarise('KALSHI', k, KALSHI_FEE, is_rebate=False)

    p = book_overrounds(POLYUS, ['event_slug', 'side'], 'p_ask')
    np_ = summarise('POLY-US', p, POLYUS_REBATE, is_rebate=True)

    if nk is not None and np_ is not None:
        print(f'DIFFERENCE: Poly-US {np_ - nk:+.2f}c per completed book vs Kalshi')
        print()
        print('Read the fee line before the overround line: the venues differ by')
        print(f'{(KALSHI_FEE + POLYUS_REBATE):.4f} * sum p(1-p) per book regardless of')
        print('what the overround does, because one charges and the other pays.')


if __name__ == '__main__':
    main()
