File size: 11,093 Bytes
b6d53e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da46dbf
 
 
 
 
 
 
 
 
 
 
b6d53e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da46dbf
 
 
b6d53e2
 
da46dbf
b6d53e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da46dbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6d53e2
da46dbf
 
b6d53e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da46dbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c78a0a
da46dbf
 
b6d53e2
 
 
 
 
 
 
 
 
 
da46dbf
 
b6d53e2
 
 
 
 
 
 
 
 
 
 
 
 
 
da46dbf
 
b6d53e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
from __future__ import annotations

import numpy as np
import pandas as pd


def _calls_for_expiry(options: pd.DataFrame, expiry: pd.Timestamp) -> pd.DataFrame:
    c = options[
        (options["option_type"] == "call")
        & (options["expiry"] == pd.to_datetime(expiry))
    ].copy()
    c = c.sort_values("strike").drop_duplicates(subset=["strike"], keep="last")
    if "openInterest" not in c.columns:
        c["openInterest"] = 0.0
    return c


def _puts_for_expiry(options: pd.DataFrame, expiry: pd.Timestamp) -> pd.DataFrame:
    p = options[
        (options["option_type"] == "put")
        & (options["expiry"] == pd.to_datetime(expiry))
    ].copy()
    p = p.sort_values("strike").drop_duplicates(subset=["strike"], keep="last")
    if "openInterest" not in p.columns:
        p["openInterest"] = 0.0
    return p


def scan_vertical_arbitrage(
    calls_df: pd.DataFrame,
    tol: float = 1e-8,
    min_edge: float = 0.0,
    min_edge_per_width: float = 0.0,
    min_leg_open_interest: int = 0,
) -> pd.DataFrame:
    g = calls_df.sort_values("strike")
    if "openInterest" not in g.columns:
        g = g.copy()
        g["openInterest"] = 0.0
    k = g["strike"].to_numpy(dtype=float)
    c = g["mid"].to_numpy(dtype=float)
    oi = g["openInterest"].fillna(0.0).to_numpy(dtype=float)
    rows: list[dict[str, object]] = []
    for i in range(len(k) - 1):
        edge = c[i + 1] - c[i]
        if edge > max(tol, min_edge):
            width = float(k[i + 1] - k[i])
            edge_pw = float(edge / max(width, 1e-12))
            leg_oi_min = float(min(oi[i], oi[i + 1]))
            if edge_pw < min_edge_per_width:
                continue
            if leg_oi_min < float(min_leg_open_interest):
                continue
            rows.append(
                {
                    "family": "vertical",
                    "k1": float(k[i]),
                    "k2": float(k[i + 1]),
                    "k3": np.nan,
                    "edge": float(edge),
                    "edge_per_width": edge_pw,
                    "leg_oi_min": leg_oi_min,
                    "notes": "Call should not increase with strike.",
                }
            )
    return pd.DataFrame(rows)


def scan_butterfly_arbitrage(
    calls_df: pd.DataFrame,
    tol: float = 1e-8,
    min_edge: float = 0.0,
    min_edge_per_width: float = 0.0,
    min_leg_open_interest: int = 0,
) -> pd.DataFrame:
    g = calls_df.sort_values("strike")
    if "openInterest" not in g.columns:
        g = g.copy()
        g["openInterest"] = 0.0
    k = g["strike"].to_numpy(dtype=float)
    c = g["mid"].to_numpy(dtype=float)
    oi = g["openInterest"].fillna(0.0).to_numpy(dtype=float)
    rows: list[dict[str, object]] = []
    if len(k) < 3:
        return pd.DataFrame(rows)
    slope_left = (c[1:-1] - c[:-2]) / (k[1:-1] - k[:-2])
    slope_right = (c[2:] - c[1:-1]) / (k[2:] - k[1:-1])
    mismatch = slope_left - slope_right
    for i, mm in enumerate(mismatch, start=1):
        if mm > tol:
            width = float(k[i + 1] - k[i - 1])
            edge_pw = float(mm / max(width, 1e-12))
            leg_oi_min = float(min(oi[i - 1], oi[i], oi[i + 1]))
            if mm < min_edge:
                continue
            if edge_pw < min_edge_per_width:
                continue
            if leg_oi_min < float(min_leg_open_interest):
                continue
            rows.append(
                {
                    "family": "butterfly",
                    "k1": float(k[i - 1]),
                    "k2": float(k[i]),
                    "k3": float(k[i + 1]),
                    "edge": float(mm),
                    "edge_per_width": edge_pw,
                    "leg_oi_min": leg_oi_min,
                    "notes": "Call slope decreases across strikes (convexity violation).",
                }
            )
    return pd.DataFrame(rows)


def scan_arbitrage_candidates(
    options: pd.DataFrame,
    expiry: pd.Timestamp,
    tol: float = 1e-8,
    min_edge: float = 0.0,
    min_edge_per_width: float = 0.0,
    min_leg_open_interest: int = 0,
    spot: float | None = None,
    r: float = 0.0,
    t_years: float = 0.25,
) -> pd.DataFrame:
    calls = _calls_for_expiry(options, expiry)
    puts = _puts_for_expiry(options, expiry)
    if calls.empty:
        return pd.DataFrame(
            columns=[
                "expiry",
                "family",
                "k1",
                "k2",
                "k3",
                "edge",
                "edge_per_width",
                "leg_oi_min",
                "notes",
                "confidence",
            ]
        )

    v = scan_vertical_arbitrage(
        calls,
        tol=tol,
        min_edge=min_edge,
        min_edge_per_width=min_edge_per_width,
        min_leg_open_interest=min_leg_open_interest,
    )
    b = scan_butterfly_arbitrage(
        calls,
        tol=tol,
        min_edge=min_edge,
        min_edge_per_width=min_edge_per_width,
        min_leg_open_interest=min_leg_open_interest,
    )

    parity = scan_put_call_parity_arbitrage(
        calls,
        puts,
        spot=spot,
        r=r,
        t_years=t_years,
        tol=tol,
        min_edge=min_edge,
        min_leg_open_interest=min_leg_open_interest,
    )

    calendar = scan_calendar_arbitrage(
        options,
        tol=tol,
        min_edge=min_edge,
        min_leg_open_interest=min_leg_open_interest,
    )

    out = (
        pd.concat([v, b, parity, calendar], ignore_index=True)
        if not v.empty or not b.empty or not parity.empty or not calendar.empty
        else pd.DataFrame()
    )
    if out.empty:
        return pd.DataFrame(
            columns=[
                "expiry",
                "family",
                "k1",
                "k2",
                "k3",
                "edge",
                "edge_per_width",
                "leg_oi_min",
                "notes",
                "confidence",
            ]
        )
    out.insert(0, "expiry", pd.to_datetime(expiry))
    out["confidence"] = "unrated"
    return out.sort_values("edge", ascending=False).reset_index(drop=True)


def scan_put_call_parity_arbitrage(
    calls_df: pd.DataFrame,
    puts_df: pd.DataFrame,
    spot: float | None,
    r: float,
    t_years: float,
    tol: float = 1e-8,
    min_edge: float = 0.0,
    min_leg_open_interest: int = 0,
) -> pd.DataFrame:
    if spot is None:
        return pd.DataFrame()
    c = calls_df[["strike", "mid", "openInterest"]].rename(
        columns={"mid": "call_mid", "openInterest": "call_oi"}
    )
    p = puts_df[["strike", "mid", "openInterest"]].rename(
        columns={"mid": "put_mid", "openInterest": "put_oi"}
    )
    m = c.merge(p, on="strike", how="inner").sort_values("strike")
    if m.empty:
        return pd.DataFrame()
    disc = float(np.exp(-float(r) * float(t_years)))
    rows: list[dict[str, object]] = []
    for _, row in m.iterrows():
        k = float(row["strike"])
        lhs = float(row["call_mid"] - row["put_mid"])
        rhs = float(spot - disc * k)
        resid = lhs - rhs
        edge = abs(resid)
        leg_oi_min = float(min(row["call_oi"], row["put_oi"]))
        if edge <= max(tol, min_edge):
            continue
        if leg_oi_min < float(min_leg_open_interest):
            continue
        rows.append(
            {
                "family": "parity",
                "k1": k,
                "k2": np.nan,
                "k3": np.nan,
                "edge": edge,
                "edge_per_width": edge,
                "leg_oi_min": leg_oi_min,
                "notes": "Put-call parity residual (American/dividend caveat applies).",
            }
        )
    return pd.DataFrame(rows)


def scan_calendar_arbitrage(
    options: pd.DataFrame,
    tol: float = 1e-8,
    min_edge: float = 0.0,
    min_leg_open_interest: int = 0,
) -> pd.DataFrame:
    calls = options[options["option_type"] == "call"].copy()
    if calls.empty:
        return pd.DataFrame()
    if "openInterest" not in calls.columns:
        calls["openInterest"] = 0.0

    rows: list[dict[str, object]] = []
    for strike, grp in calls.groupby("strike"):
        g = grp.sort_values("expiry")
        if len(g) < 2:
            continue
        mids = g["mid"].to_numpy(dtype=float)
        expiries = pd.to_datetime(g["expiry"]).to_numpy()
        ois = g["openInterest"].fillna(0.0).to_numpy(dtype=float)
        for i in range(len(mids) - 1):
            edge = float(mids[i] - mids[i + 1])
            if edge <= max(tol, min_edge):
                continue
            leg_oi_min = float(min(ois[i], ois[i + 1]))
            if leg_oi_min < float(min_leg_open_interest):
                continue
            rows.append(
                {
                    "family": "calendar",
                    "k1": float(strike),
                    "k2": np.nan,
                    "k3": np.nan,
                    "edge": edge,
                    "edge_per_width": edge,
                    "leg_oi_min": leg_oi_min,
                    "notes": "Longer-dated call cheaper than shorter-dated call at same strike.",
                }
            )
    return pd.DataFrame(rows)


def summarize_arbitrage(candidates: pd.DataFrame) -> pd.DataFrame:
    if candidates.empty:
        return pd.DataFrame(
            [
                {
                    "candidate_count": 0,
                    "max_edge": 0.0,
                    "median_edge": 0.0,
                    "vertical_count": 0,
                    "butterfly_count": 0,
                    "parity_count": 0,
                    "calendar_count": 0,
                    "high_conf_count": 0,
                    "medium_conf_count": 0,
                    "low_conf_count": 0,
                }
            ]
        )
    return pd.DataFrame(
        [
            {
                "candidate_count": int(len(candidates)),
                "max_edge": float(candidates["edge"].max()),
                "median_edge": float(candidates["edge"].median()),
                "vertical_count": int((candidates["family"] == "vertical").sum()),
                "butterfly_count": int((candidates["family"] == "butterfly").sum()),
                "parity_count": int((candidates["family"] == "parity").sum()),
                "calendar_count": int((candidates["family"] == "calendar").sum()),
                "high_conf_count": int((candidates["confidence"] == "high").sum()),
                "medium_conf_count": int((candidates["confidence"] == "medium").sum()),
                "low_conf_count": int((candidates["confidence"] == "low").sum()),
            }
        ]
    )


def assign_candidate_confidence(
    candidates: pd.DataFrame,
    mean_violation_rate: float,
    failed_checks: int,
) -> pd.DataFrame:
    if candidates.empty:
        return candidates
    if failed_checks == 0 and mean_violation_rate <= 0.02:
        conf = "high"
    elif failed_checks <= 1 and mean_violation_rate <= 0.08:
        conf = "medium"
    else:
        conf = "low"
    out = candidates.copy()
    out["confidence"] = conf
    return out