Download options_scanner/rolling.py from Reckless88/options-scanner: direct link, hf CLI and curl.
- Browser
- Download file 6.68 kB
-
https://huggingface.co/datasets/Reckless88/options-scanner/resolve/main/options_scanner/rolling.py
- Command line
-
hf download hf://datasets/Reckless88/options-scanner/options_scanner/rolling.py
-
curl -L -o rolling.py https://huggingface.co/datasets/Reckless88/options-scanner/resolve/main/options_scanner/rolling.py
6.68 kB
| """Position management and rolling mechanics. | |
| RollManager.check() takes an open position plus today's chain and returns | |
| recommended actions with a concrete proposal (close / take-profit / stop / | |
| roll out / roll down / roll out-and-down / roll out-and-up). | |
| """ | |
| from dataclasses import dataclass, field | |
| from .pricing import bs_delta | |
| class Position: | |
| symbol: str | |
| structure: str # e.g. "Bull Put Spread (credit)" | |
| legs: list # [(kind, strike, expiry, side, qty)] | |
| entry_credit: float = 0.0 # >0 credit, <0 debit, per share | |
| entry_date: str = "" | |
| qty_sets: int = 1 | |
| class RollAction: | |
| action: str # close_profit | close_stop | roll_out | roll_down | roll_out_and_down | roll_out_and_up | hold | |
| reason: str | |
| proposed_legs: list = field(default_factory=list) # replacement legs if rolling | |
| urgency: str = "normal" # normal | high | |
| def _position_value(position, chain, horizon_expiry=None): | |
| """Mark-to-market per share using current chain quotes (mid), back legs | |
| valued at front expiry via BS when they outlive the horizon.""" | |
| from .pricing import bs_price | |
| from datetime import date, datetime, timezone | |
| value = 0.0 | |
| for kind, strike, expiry, side, qty in position.legs: | |
| q = chain.get(strike, expiry, kind) | |
| if q and q.mid > 0: | |
| price = q.mid | |
| else: | |
| dte = (date.fromisoformat(expiry) - datetime.now(timezone.utc).date()).days | |
| price = bs_price(chain.spot, strike, max(dte, 0.5) / 365.0, 0.30, kind) | |
| value += side * qty * price | |
| return value | |
| def _short_deltas(position, chain): | |
| """Current |delta| of each short leg.""" | |
| out = [] | |
| for kind, strike, expiry, side, qty in position.legs: | |
| if side < 0: | |
| q = chain.get(strike, expiry, kind) | |
| d = abs(q.delta) if q and q.delta else 0.0 | |
| if not d: | |
| from .pricing import bs_delta as _bd | |
| from datetime import date, datetime, timezone | |
| dte = (date.fromisoformat(expiry) - datetime.now(timezone.utc).date()).days | |
| d = abs(_bd(chain.spot, strike, max(dte, 0.5) / 365.0, 0.30, kind)) | |
| out.append((kind, strike, expiry, d)) | |
| return out | |
| def _dte(expiry): | |
| from datetime import date, datetime, timezone | |
| return (date.fromisoformat(expiry) - datetime.now(timezone.utc).date()).days | |
| def check(position, chain, rules): | |
| """rules: profit_target_pct, stop_loss_mult, roll_dte, tested_delta.""" | |
| actions = [] | |
| value = _position_value(position, chain) | |
| # realized/unrealized P&L per share relative to entry | |
| pnl = (position.entry_credit - value) if position.entry_credit >= 0 else (value - position.entry_credit) | |
| is_credit = position.entry_credit >= 0 | |
| dte = min(_dte(e) for _, _, e, _, _ in position.legs) | |
| # 1. Take profit: credit -> X% of credit captured; debit -> X% of max gain proxy | |
| if is_credit and pnl >= rules["profit_target_pct"] * position.entry_credit: | |
| actions.append(RollAction("close_profit", | |
| f"captured {pnl / position.entry_credit:.0%} of entry credit " | |
| f"(${pnl * 100:.2f}/set)", urgency="normal")) | |
| if not is_credit and position.entry_credit < 0 and value > 0 and \ | |
| (value - position.entry_credit) / (-position.entry_credit) >= rules["profit_target_pct"]: | |
| actions.append(RollAction("close_profit", | |
| f"debit spread up {pnl / -position.entry_credit:.0%} of entry debit")) | |
| # 2. Stop loss | |
| if is_credit and value >= position.entry_credit * rules["stop_loss_mult"]: | |
| actions.append(RollAction("close_stop", | |
| f"unrealized loss ${-pnl * 100:.2f}/set exceeds " | |
| f"{rules['stop_loss_mult']}x credit — cut it", | |
| urgency="high")) | |
| # 3. Roll mechanics | |
| if dte <= rules["roll_dte"]: | |
| short_strikes = _short_deltas(position, chain) | |
| tested = [s for s in short_strikes if s[3] >= rules["tested_delta"]] | |
| if tested: | |
| kind, strike, expiry, d = tested[0] | |
| back = chain.expirations(min_dte=25, max_dte=60) | |
| if not back or back[0] <= expiry: | |
| actions.append(RollAction("close_stop" if pnl < 0 else "close_profit", | |
| f"DTE {dte} <= {rules['roll_dte']} and no further expiry to roll to — close")) | |
| else: | |
| new_exp = back[0] | |
| if pnl >= 0: | |
| actions.append(RollAction("roll_out", | |
| f"winning short {strike:g}{kind} at delta {d:.2f} — " | |
| f"roll to {new_exp} to harvest more theta")) | |
| elif kind == "P": | |
| new_k = chain.nearest_strike(strike * 0.97, new_exp, kind) | |
| if new_k: | |
| actions.append(RollAction("roll_out_and_down", | |
| f"tested put {strike:g} (delta {d:.2f}) — " | |
| f"roll out-and-down to {new_exp} {new_k.strike:g}P", | |
| proposed_legs=[("P", new_k.strike, new_exp, -1, 1)], | |
| urgency="high")) | |
| else: | |
| new_k = chain.nearest_strike(strike * 1.03, new_exp, kind) | |
| if new_k: | |
| actions.append(RollAction("roll_out_and_up", | |
| f"tested call {strike:g} (delta {d:.2f}) — " | |
| f"roll out-and-up to {new_exp} {new_k.strike:g}C", | |
| proposed_legs=[("C", new_k.strike, new_exp, -1, 1)], | |
| urgency="high")) | |
| else: | |
| actions.append(RollAction("hold", | |
| f"DTE {dte}, short deltas below {rules['tested_delta']} — " | |
| f"let theta work")) | |
| if not actions: | |
| actions.append(RollAction("hold", f"DTE {dte}, inside all thresholds")) | |
| return actions | |
| DEFAULT_ROLL_RULES = { | |
| "profit_target_pct": 0.50, # close at 50% of credit captured | |
| "stop_loss_mult": 2.0, # stop when loss reaches 2x entry credit | |
| "roll_dte": 21, # start roll management at 21 DTE | |
| "tested_delta": 0.40, # short leg delta that counts as tested | |
| } | |