Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Add candidate options strategy engines, backtest study and report (#1774)

mdb1230147ebd1c67b4
diff --git a/agent/scripts/options_candidates_backtest.py b/agent/scripts/options_candidates_backtest.py
new file mode 100644
index 000000000..3afe6c406
--- /dev/null
+++ b/agent/scripts/options_candidates_backtest.py
@@ -0,0 +1,180 @@
+"""Backtest the candidate options strategies in skills/options-strategy.
+
+In-sample 2016-2020 picks one parameter per strategy (best mean Sharpe over
+SPY and QQQ); out-of-sample 2021 onward reports every underlying with those
+parameters untouched. Prints markdown tables.
+
+ PYTHONPATH=agent python agent/scripts/options_candidates_backtest.py
+"""
+
+from __future__ import annotations
+
+import contextlib
+import importlib.util
+import io
+import tempfile
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+
+from backtest.engines.options_portfolio import run_options_backtest
+from backtest.loaders.yfinance_loader import DataLoader
+
+_spec = importlib.util.spec_from_file_location(
+ "options_strategy_engines",
+ Path(__file__).parents[1] / "src" / "skills" / "options-strategy" / "example_signal_engine.py",
+)
+engines = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(engines)
+
+UNDERLYINGS = {"SPY.US": 0.01, "QQQ.US": 0.01, "AAPL.US": 0.02, "MSFT.US": 0.02} # commission
+IS = ("2015-01-01", "2016-01-04", "2020-12-31") # load from, evaluate from, end
+OOS = ("2020-01-01", "2021-01-04", "2026-10-08")
+OPTIONS = {"risk_free_rate": 0.02, "iv_skew": -0.3, "iv_curvature": 0.0,
+ "default_iv": 0.3, "contract_multiplier": 1.0}
+CASH = 100_000.0
+# The engine margins every short leg as naked. Covered calls are covered by the
+# share replica and condors are sized so max loss is 10% of capital (the
+# Reg-T spread requirement), so neither is run against that margin model; left
+# on, it rejects single condor legs and leaves the rest of the structure naked.
+NO_MARGIN = {"covered_call", "protective_put", "iron_condor"}
+GRID = {
+ "covered_call": [{"delta": 0.20}, {"delta": 0.30}],
+ "cash_secured_put": [{"delta": 0.20}, {"delta": 0.30}],
+ "iron_condor": [{"short_delta": 0.10}, {"short_delta": 0.16}, {"short_delta": 0.25}],
+ "vol_gated_strangle": [{"gate": "none"}, {"gate": "contracting"}, {"gate": "elevated"}],
+ "protective_put": [{"delta": 0.15}, {"delta": 0.30}],
+}
+
+_frames: dict[str, pd.DataFrame] = {}
+
+
+class _Loader:
+ name = "yfinance"
+
+ def fetch(self, codes, start_date, end_date): # noqa: ANN001
+ missing = [c for c in codes if c not in _frames]
+ if missing:
+ _frames.update(DataLoader().fetch(missing, "2015-01-01", OOS[2]))
+ return {c: _frames[c].loc[start_date:end_date] for c in codes}
+
+
+_tbill: pd.Series | None = None
+
+
+def with_tbill(equity: pd.Series, cash: pd.Series) -> pd.Series:
+ """Credit (or charge) the 13-week T-bill rate on the engine's cash balance,
+ which the engine itself leaves at 0%. Simple interest, added post hoc."""
+ global _tbill
+ if _tbill is None:
+ import yfinance as yf
+
+ irx = yf.download("^IRX", start="2015-01-01", end=OOS[2], progress=False,
+ auto_adjust=False)["Close"].squeeze()
+ _tbill = irx.tz_localize(None) / 100.0
+ rate = _tbill.reindex(cash.index, method="ffill").fillna(0.0)
+ return equity + (cash.shift(1).fillna(0.0) * rate / 252).cumsum()
+
+
+def run(strategy: str, params: dict, code: str, window: tuple) -> tuple[pd.Series, pd.DataFrame]:
+ load_from, eval_from, end = window
+ commission = UNDERLYINGS[code]
+ engine = engines.ENGINES[strategy](
+ **{k: OPTIONS[k] for k in ("risk_free_rate", "iv_skew", "iv_curvature", "default_iv")},
+ commission=commission, capital=CASH, start_date=eval_from, **params)
+ config = {
+ "codes": [code], "start_date": load_from, "end_date": end, "source": "yfinance",
+ "engine": "options", "initial_cash": CASH, "commission": commission,
+ "evaluation_start_date": eval_from,
+ "options_config": dict(OPTIONS, margin_enabled=strategy not in NO_MARGIN),
+ }
+ with tempfile.TemporaryDirectory() as tmp, contextlib.redirect_stdout(io.StringIO()):
+ run_options_backtest(config, _Loader(), engine, Path(tmp))
+ art = Path(tmp) / "artifacts"
+ frame = pd.read_csv(art / "equity.csv", index_col="timestamp", parse_dates=True)
+ trades = pd.read_csv(art / "trades.csv")
+ return frame["equity"], trades, frame["cash"]
+
+
+def stats(equity: pd.Series, trades: pd.DataFrame | None = None,
+ cash: pd.Series | None = None) -> dict:
+ ret = equity.pct_change().dropna()
+ years = (equity.index[-1] - equity.index[0]).days / 365.25
+ monthly = equity.resample("ME").last().pct_change().dropna()
+ out = {
+ "CAGR": (equity.iloc[-1] / equity.iloc[0]) ** (1 / years) - 1,
+ "Sharpe": ret.mean() / ret.std() * np.sqrt(252),
+ "MaxDD": (equity / equity.cummax() - 1).min(),
+ "WorstMo": monthly.min(),
+ "WorstDay": ret.min(),
+ "CVaR5": ret[ret <= ret.quantile(0.05)].mean(),
+ "Skew": ret.skew(),
+ }
+ if cash is not None:
+ adj = with_tbill(equity, cash)
+ out["CAGR+bill"] = (adj.iloc[-1] / adj.iloc[0]) ** (1 / years) - 1
+ if trades is not None:
+ settled = trades[trades["side"].isin(["close", "exercise", "expire"])
+ & (trades["strike"] > 0.01)]
+ per_trade = settled.groupby(["entry_date", "expiry"])["pnl"].sum()
+ out["WinRate"] = (per_trade > 0).mean() if len(per_trade) else np.nan
+ out["Trades"] = len(per_trade)
+ out["Rejects"] = int((trades["side"] == "reject").sum())
+ return out
+
+
+def table(rows: list[dict]) -> str:
+ cols = list(dict.fromkeys(k for r in rows for k in r))
+ pct = {"CAGR", "CAGR+bill", "MaxDD", "WorstMo", "WorstDay", "CVaR5", "WinRate"}
+
+ def fmt(k: str, v: object) -> str:
+ if isinstance(v, float):
+ return f"{v:.1%}" if k in pct else f"{v:.2f}"
+ return str(v)
+
+ lines = ["| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)]
+ lines += ["| " + " | ".join(fmt(k, r.get(k, "")) for k in cols) + " |" for r in rows]
+ return "\n".join(lines)
+
+
+def main() -> None:
+ chosen, is_rows = {}, []
+ for strategy, grid in GRID.items():
+ scores = []
+ for params in grid:
+ sharpes = []
+ for code in ("SPY.US", "QQQ.US"):
+ s = stats(*run(strategy, params, code, IS))
+ sharpes.append(s["Sharpe"])
+ is_rows.append({"Strategy": strategy, "Params": params, "Code": code, **s})
+ scores.append(np.mean(sharpes))
+ chosen[strategy] = grid[int(np.argmax(scores))]
+ for code in ("SPY.US", "QQQ.US"):
+ close = _Loader().fetch([code], IS[1], IS[2])[code]["close"]
+ is_rows.append({"Strategy": "buy_and_hold", "Params": {}, "Code": code, **stats(close)})
+ print("## In-sample 2016-2020\n\n" + table(is_rows) + "\n")
+ print("Chosen: " + ", ".join(f"{k}={v}" for k, v in chosen.items()) + "\n")
+
+ oos_rows = []
+ for code in UNDERLYINGS:
+ close = _Loader().fetch([code], OOS[1], OOS[2])[code]["close"]
+ oos_rows.append({"Strategy": "buy_and_hold", "Code": code, **stats(close)})
+ for strategy, params in chosen.items():
+ oos_rows.append({"Strategy": strategy, "Code": code,
+ **stats(*run(strategy, params, code, OOS))})
+ print("## Out-of-sample 2021-2026\n\n" + table(oos_rows) + "\n")
+
+ # Smile sensitivity: the only lever on option richness the engine exposes.
+ sens_rows = []
+ for skew in (0.0, -0.3, -0.6):
+ OPTIONS["iv_skew"] = skew
+ for strategy, params in chosen.items():
+ s = stats(*run(strategy, params, "SPY.US", OOS))
+ sens_rows.append({"iv_skew": skew, "Strategy": strategy,
+ **{k: s[k] for k in ("CAGR", "CAGR+bill", "Sharpe", "MaxDD")}})
+ print("## SPY out-of-sample, smile skew sensitivity\n\n" + table(sens_rows))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/agent/src/skills/options-strategy/SKILL.md b/agent/src/skills/options-strategy/SKILL.md
index 27a2b866a..894b2e789 100644
--- a/agent/src/skills/options-strategy/SKILL.md
+++ b/agent/src/skills/options-strategy/SKILL.md
@@ -76,6 +76,11 @@ Iron Condor opening signal:
}
```
+Ready-made engines for covered call, cash-secured put, iron condor,
+vol-gated short strangle and protective put live in
+`example_signal_engine.py` next to this file. Backtest results and their
+caveats are in `docs/sessions/2026-10-09_options_strategy_candidates.md`.
+
## `config.json` Format
```json
diff --git a/agent/src/skills/options-strategy/example_signal_engine.py b/agent/src/skills/options-strategy/example_signal_engine.py
new file mode 100644
index 000000000..a27b042bb
--- /dev/null
+++ b/agent/src/skills/options-strategy/example_signal_engine.py
@@ -0,0 +1,355 @@
+"""Candidate options strategies for ``backtest.engines.options_portfolio``.
+
+Five ``OptionsSignalEngine`` implementations (see SKILL.md for the instruction
+format): covered call, cash-secured put, short iron condor, vol-gated short
+strangle and protective put. ``SignalEngine`` defaults to the iron condor.
+
+The engine calls ``generate`` once with the whole history, so trade management
+(profit targets, DTE exits, compounding size) is decided here by re-pricing
+each leg with the engine's own model -- trailing historical vol, the same
+smile, Black-Scholes -- using only bars up to the decision date. Pass the run's
+``options_config`` values (``risk_free_rate``, ``iv_skew``, ``iv_curvature``,
+``default_iv``) and ``commission`` so both sides price identically.
+
+Stock legs: the engine trades options only, so the share position of the
+covered call and protective put is a long call struck at ~0 that expires after
+the data ends (price ~= spot, delta 1). The engine's margin model cannot see
+that it covers the short call, so run those two with ``margin_enabled: false``.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Callable, Dict, List, Optional
+
+import numpy as np
+import pandas as pd
+
+from backtest.engines.options_portfolio import historical_volatility, leg_iv
+from src.quantlib.options import bs_greeks, bs_price
+
+Leg = Dict[str, Any]
+
+
+class _OptionsBook:
+ """Shared pricing, strike selection and per-underlying trade loop."""
+
+ def __init__(self, risk_free_rate: float = 0.02, iv_skew: float = 0.0,
+ iv_curvature: float = 0.0, default_iv: float = 0.3,
+ commission: float = 0.0, capital: float = 100_000.0,
+ start_date: Optional[str] = None) -> None:
+ self.r = risk_free_rate
+ self.skew = iv_skew
+ self.curvature = iv_curvature
+ self.default_iv = default_iv
+ self.commission = commission
+ self.capital = capital
+ # No entries before this date: the warm-up bars only feed vol and gates.
+ self.start = pd.Timestamp(start_date) if start_date else None
+
+ # --- pricing (mirrors the engine) ---
+
+ def _price(self, S: float, hv: float, ts: pd.Timestamp, leg: Leg) -> float:
+ T = max((pd.Timestamp(leg["expiry"]) - ts).days / 365.0, 0.0)
+ iv = leg_iv(S, leg["strike"], hv, self.skew, self.curvature)
+ return bs_price(S, leg["strike"], T, self.r, iv, leg["type"])
+
+ def _value(self, S: float, hv: float, ts: pd.Timestamp, legs: List[Leg]) -> float:
+ return sum(self._price(S, hv, ts, leg) * leg["qty"] for leg in legs)
+
+ def _strike(self, S: float, hv: float, ts: pd.Timestamp, expiry: str,
+ option_type: str, delta: float) -> float:
+ """Listed-style strike (1% of spot grid) whose |delta| is closest to target."""
+ step = 10 ** np.floor(np.log10(S / 100)) if S >= 100 else 0.5
+ T = max((pd.Timestamp(expiry) - ts).days / 365.0, 1e-3)
+ best, best_err = S, np.inf
+ for K in np.arange(np.floor(S * 0.6 / step), np.ceil(S * 1.4 / step) + 1) * step:
+ iv = leg_iv(S, K, hv, self.skew, self.curvature)
+ err = abs(abs(bs_greeks(S, K, T, self.r, iv, option_type)["delta"]) - delta)
+ if err < best_err:
+ best, best_err = float(K), err
+ return best
+
+ @staticmethod
+ def _expiry(index: pd.DatetimeIndex, i: int, dte: int) -> Optional[str]:
+ """First trading date at least ``dte`` calendar days after bar ``i``."""
+ target = index[i] + pd.Timedelta(days=dte)
+ j = index.searchsorted(target)
+ return str(index[j].date()) if j < len(index) else None
+
+ # --- driver ---
+
+ def generate(self, data_map: Dict[str, pd.DataFrame]) -> List[Dict[str, Any]]:
+ signals: List[Dict[str, Any]] = []
+ for code, df in data_map.items():
+ close = df["close"].astype(float)
+ hv = historical_volatility(close, default_iv=self.default_iv)
+ signals += self._run(code, close, hv, self.capital / len(data_map))
+ return signals
+
+ def _run(self, code: str, close: pd.Series, hv: pd.Series,
+ capital: float) -> List[Dict[str, Any]]:
+ raise NotImplementedError
+
+ @staticmethod
+ def _signal(ts: pd.Timestamp, action: str, code: str, legs: List[Leg]) -> Dict[str, Any]:
+ return {"date": str(ts.date()), "action": action, "underlying": code,
+ "legs": [dict(leg) for leg in legs]}
+
+ def _stock_legs(self, close: pd.Series, qty: float) -> List[Leg]:
+ """Share replica: call struck near zero, expiring after the data ends."""
+ expiry = close.index[-1] + pd.Timedelta(days=400)
+ return [{"type": "call", "strike": 0.01, "expiry": str(expiry.date()), "qty": qty}]
+
+
+class _ShortPremium(_OptionsBook):
+ """Open a structure, manage it to a profit target / DTE floor, repeat.
+
+ Subclasses define ``_build`` (legs for one unit plus max loss per unit, or
+ ``None`` to skip) and may override ``_gate``. Size compounds on the
+ strategy's own realized P&L, so a drawdown shrinks the next trade.
+ """
+
+ dte = 45
+ take_profit: Optional[float] = 0.5 # fraction of entry credit captured
+ exit_dte: Optional[int] = 21 # close when this few days remain
+ risk_fraction = 1.0 # capital per trade / max-loss-or-notional per unit
+
+ def _build(self, S: float, hv: float, ts: pd.Timestamp, expiry: str):
+ raise NotImplementedError
+
+ def _gate(self, close: pd.Series, hv: pd.Series, i: int) -> bool:
+ return True
+
+ def _run(self, code, close, hv, capital):
+ idx = close.index
+ out: List[Dict[str, Any]] = []
+ legs: Optional[List[Leg]] = None
+ credit = 0.0
+ for i, ts in enumerate(idx):
+ S, vol = float(close.iloc[i]), float(hv.iloc[i])
+ if legs is not None:
+ expiry = pd.Timestamp(legs[0]["expiry"])
+ value = self._value(S, vol, ts, legs) # negative for a short book
+ if ts >= expiry:
+ # The engine settles at intrinsic; mirror it in our capital.
+ intrinsic = sum(max(0.0, (S - lg["strike"]) if lg["type"] == "call"
+ else (lg["strike"] - S)) * lg["qty"] for lg in legs)
+ capital += credit + intrinsic
+ legs = None
+ elif ((self.take_profit is not None and credit > 0
+ and credit + value >= self.take_profit * credit)
+ or (self.exit_dte is not None and (expiry - ts).days <= self.exit_dte)):
+ out.append(self._signal(ts, "close", code, legs))
+ capital += credit + value - self.commission * sum(
+ abs(self._price(S, vol, ts, lg) * lg["qty"]) for lg in legs)
+ legs = None
+ continue # re-enter on the next bar, after the close fills
+ if legs is not None or (self.start is not None and ts < self.start):
+ continue
+ if i + 1 >= len(idx) or not self._gate(close, hv, i):
+ continue
+ expiry = self._expiry(idx, i, self.dte)
+ if expiry is None:
+ continue
+ built = self._build(S, vol, ts, expiry)
+ if built is None:
+ continue
+ unit_legs, unit_risk = built
+ qty = float(np.floor(self.risk_fraction * max(capital, 0.0) / unit_risk))
+ if qty <= 0:
+ continue
+ legs = [dict(lg, qty=lg["qty"] * qty) for lg in unit_legs]
+ credit = -self._value(S, vol, ts, legs) - self.commission * sum(
+ abs(self._price(S, vol, ts, lg) * lg["qty"]) for lg in legs)
+ out.append(self._signal(ts, "open", code, legs))
+ return out
+
+
+class CashSecuredPutEngine(_ShortPremium):
+ """Sell a ~0.30-delta put, ~35 DTE, sized so cash covers assignment.
+
+ Held to expiry and cash-settled (the engine has no share delivery), which
+ is a wheel whose assigned shares are sold at once instead of having calls
+ written against them.
+ """
+
+ def __init__(self, delta: float = 0.30, dte: int = 35, **kw: Any) -> None:
+ super().__init__(**kw)
+ self.delta, self.dte = delta, dte
+ self.take_profit = self.exit_dte = None
+
+ def _build(self, S, hv, ts, expiry):
+ K = self._strike(S, hv, ts, expiry, "put", self.delta)
+ return [{"type": "put", "strike": K, "expiry": expiry, "qty": -1}], K
+
+
+class IronCondorEngine(_ShortPremium):
+ """Short ~16-delta strangle with ~5-delta wings, 45 DTE, managed at
+ 50% of credit or 21 DTE. Risks ``risk_fraction`` of capital per trade."""
+
+ def __init__(self, short_delta: float = 0.16, wing_delta: float = 0.05,
+ risk_fraction: float = 0.10, **kw: Any) -> None:
+ super().__init__(**kw)
+ self.short_delta, self.wing_delta = short_delta, wing_delta
+ self.risk_fraction = risk_fraction
+
+ def _build(self, S, hv, ts, expiry):
+ sp = self._strike(S, hv, ts, expiry, "put", self.short_delta)
+ lp = self._strike(S, hv, ts, expiry, "put", self.wing_delta)
+ sc = self._strike(S, hv, ts, expiry, "call", self.short_delta)
+ lc = self._strike(S, hv, ts, expiry, "call", self.wing_delta)
+ if not (lp < sp < sc < lc):
+ return None
+ legs = [
+ {"type": "put", "strike": sp, "expiry": expiry, "qty": -1},
+ {"type": "put", "strike": lp, "expiry": expiry, "qty": 1},
+ {"type": "call", "strike": sc, "expiry": expiry, "qty": -1},
+ {"type": "call", "strike": lc, "expiry": expiry, "qty": 1},
+ ]
+ # Max loss ignoring the credit: conservative and independent of fills.
+ return legs, max(sp - lp, lc - sc)
+
+
+class VolGatedStrangleEngine(_ShortPremium):
+ """Short ~16-delta strangle, 45 DTE, managed at 50% / 21 DTE, entered only
+ when the realized-vol regime allows.
+
+ ``gate``: ``"none"``; ``"contracting"`` -- 10-day vol below 30-day vol (sell
+ after a spike has started to fade, never into a rising one); ``"elevated"``
+ -- 30-day vol above its trailing 1-year median.
+ """
+
+ def __init__(self, delta: float = 0.16, gate: str = "contracting",
+ notional_fraction: float = 1.0, **kw: Any) -> None:
+ super().__init__(**kw)
+ self.delta, self.gate = delta, gate
+ self.risk_fraction = notional_fraction
+
+ def generate(self, data_map):
+ self._hv10 = {c: historical_volatility(df["close"].astype(float), window=10,
+ default_iv=self.default_iv)
+ for c, df in data_map.items()}
+ return super().generate(data_map)
+
+ def _run(self, code, close, hv, capital):
+ self._code = code
+ return super()._run(code, close, hv, capital)
+
+ def _gate(self, close, hv, i):
+ if self.gate == "contracting":
+ return float(self._hv10[self._code].iloc[i]) < float(hv.iloc[i])
+ if self.gate == "elevated":
+ return i >= 252 and float(hv.iloc[i]) > float(hv.iloc[i - 252:i].median())
+ return True
+
+ def _build(self, S, hv, ts, expiry):
+ legs = [
+ {"type": "put", "strike": self._strike(S, hv, ts, expiry, "put", self.delta),
+ "expiry": expiry, "qty": -1},
+ {"type": "call", "strike": self._strike(S, hv, ts, expiry, "call", self.delta),
+ "expiry": expiry, "qty": -1},
+ ]
+ return legs, S
+
+
+class _StockPlusOption(_OptionsBook):
+ """Hold the share replica from the start date; ``_overlay`` adds one
+ rolling option leg (short call or long put) sized to the shares."""
+
+ option_type = "call"
+ side = -1
+
+ def __init__(self, delta: float, dte: int, roll_dte: Optional[int] = None,
+ stock_fraction: float = 1.0, **kw: Any) -> None:
+ super().__init__(**kw)
+ self.delta, self.dte, self.roll_dte = delta, dte, roll_dte
+ self.stock_fraction = stock_fraction
+
+ def _run(self, code, close, hv, capital):
+ idx = close.index
+ out: List[Dict[str, Any]] = []
+ stock = self._stock_legs(close, 0.0)[0]
+ lots: List[float] = [] # replica lots, FIFO: the engine closes the oldest match first
+ cash = capital
+ leg: Optional[Leg] = None
+ c = self.commission
+ for i, ts in enumerate(idx[:-1]):
+ if self.start is not None and ts < self.start:
+ continue
+ S, vol = float(close.iloc[i]), float(hv.iloc[i])
+ px = lambda lg: self._price(S, vol, ts, lg) # noqa: E731
+ if leg is not None:
+ expiry = pd.Timestamp(leg["expiry"])
+ if ts >= expiry:
+ intrinsic = max(0.0, (S - leg["strike"]) if leg["type"] == "call"
+ else (leg["strike"] - S))
+ cash += intrinsic * leg["qty"]
+ leg = None
+ elif self.roll_dte is not None and (expiry - ts).days <= self.roll_dte:
+ out.append(self._signal(ts, "close", code, [leg]))
+ cash += px(leg) * leg["qty"] - c * abs(px(leg) * leg["qty"])
+ leg = None
+ continue
+ if leg is not None:
+ continue
+ expiry = self._expiry(idx, i, self.dte)
+ if expiry is None:
+ continue
+ # Re-size the shares to equity each cycle, as assignment and
+ # re-buying would; otherwise settled calls/puts drift cash and leverage.
+ held = sum(lots)
+ target = float(np.floor(self.stock_fraction * (cash + held * px(stock)) / S))
+ diff = target - held
+ if held == 0 or abs(diff) > 0.02 * held:
+ if diff > 0:
+ lots.append(diff)
+ out.append(self._signal(ts, "open", code, [dict(stock, qty=diff)]))
+ else:
+ legs, left = [], -diff
+ while left > 0:
+ take = min(left, lots[0])
+ legs.append(dict(stock, qty=take))
+ lots[0] -= take
+ left -= take
+ if lots[0] == 0:
+ lots.pop(0)
+ out.append(self._signal(ts, "close", code, legs))
+ cash -= diff * px(stock) + c * abs(diff * px(stock))
+ K = self._strike(S, vol, ts, expiry, self.option_type, self.delta)
+ leg = {"type": self.option_type, "strike": K, "expiry": expiry,
+ "qty": self.side * sum(lots)}
+ out.append(self._signal(ts, "open", code, [leg]))
+ cash -= px(leg) * leg["qty"] + c * abs(px(leg) * leg["qty"])
+ return out
+
+
+class CoveredCallEngine(_StockPlusOption):
+ """Long shares, short a ~0.30-delta call ~35 DTE, held to expiry. An ITM
+ call cash-settles and the shares are re-sized to equity, which is what
+ assignment followed by re-buying amounts to."""
+
+ def __init__(self, delta: float = 0.30, dte: int = 35, **kw: Any) -> None:
+ super().__init__(delta=delta, dte=dte, **kw)
+
+
+class ProtectivePutEngine(_StockPlusOption):
+ """Long shares plus a ~0.20-delta put ~60 DTE, rolled at 21 DTE.
+ The long-vol / insurance baseline."""
+
+ option_type = "put"
+ side = 1
+
+ def __init__(self, delta: float = 0.20, dte: int = 60, roll_dte: int = 21,
+ **kw: Any) -> None:
+ super().__init__(delta=delta, dte=dte, roll_dte=roll_dte, **kw)
+
+
+ENGINES: Dict[str, Callable[..., _OptionsBook]] = {
+ "covered_call": CoveredCallEngine,
+ "cash_secured_put": CashSecuredPutEngine,
+ "iron_condor": IronCondorEngine,
+ "vol_gated_strangle": VolGatedStrangleEngine,
+ "protective_put": ProtectivePutEngine,
+}
+
+SignalEngine = IronCondorEngine
diff --git a/agent/tests/test_options_strategy_engines.py b/agent/tests/test_options_strategy_engines.py
new file mode 100644
index 000000000..d77b8e584
--- /dev/null
+++ b/agent/tests/test_options_strategy_engines.py
@@ -0,0 +1,69 @@
+"""Smoke tests for the candidate engines in skills/options-strategy.
+
+Each engine runs a short deterministic backtest on a synthetic random walk
+and must place trades, settle or close every expired leg, and produce finite
+equity.
+"""
+
+from __future__ import annotations
+
+from importlib.util import module_from_spec, spec_from_file_location
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.engines.options_portfolio import run_options_backtest
+
+_PATH = Path(__file__).parents[1] / "src" / "skills" / "options-strategy" / "example_signal_engine.py"
+_spec = spec_from_file_location("options_strategy_engines", _PATH)
+engines = module_from_spec(_spec)
+_spec.loader.exec_module(engines)
+
+_DATES = pd.bdate_range("2023-01-02", periods=260)
+_CLOSE = 100 * np.exp(np.cumsum(np.random.default_rng(7).normal(0.0003, 0.012, len(_DATES))))
+_BARS = pd.DataFrame(
+ {"open": _CLOSE, "high": _CLOSE * 1.005, "low": _CLOSE * 0.995, "close": _CLOSE,
+ "volume": 1_000},
+ index=_DATES,
+)
+_OPTS = {"risk_free_rate": 0.02, "iv_skew": -0.3, "iv_curvature": 0.0, "default_iv": 0.2}
+
+
+class _Loader:
+ name = "synthetic"
+
+ def fetch(self, codes, start_date, end_date): # noqa: ANN001
+ return {"SPY": _BARS.copy()}
+
+
[email protected]("name", sorted(engines.ENGINES))
+def test_engine_runs_and_settles(tmp_path: Path, name: str) -> None:
+ engine = engines.ENGINES[name](**_OPTS, commission=0.01, capital=100_000,
+ start_date="2023-03-01")
+ config = {
+ "codes": ["SPY"], "start_date": "2023-01-02", "end_date": "2023-12-29",
+ "initial_cash": 100_000, "commission": 0.01,
+ "evaluation_start_date": "2023-02-28",
+ "options_config": dict(_OPTS, contract_multiplier=1.0,
+ margin_enabled=name not in {"covered_call", "protective_put",
+ "iron_condor"}),
+ }
+ run_options_backtest(config, _Loader(), engine, tmp_path)
+ art = tmp_path / "artifacts"
+ trades = pd.read_csv(art / "trades.csv")
+ equity = pd.read_csv(art / "equity.csv")
+
+ opens = trades[trades["side"].isin(["buy", "sell"])]
+ assert len(opens) >= 3, trades
+ assert not (trades["side"] == "reject").any()
+ assert opens["timestamp"].min() >= "2023-03-01"
+ assert np.isfinite(equity["equity"]).all() and (equity["equity"] > 0).all()
+
+ # Every option leg that expired inside the run was settled or closed.
+ last = equity["timestamp"].iloc[-1]
+ settled = trades[trades["side"].isin(["close", "exercise", "expire"])]
+ done = settled.groupby(["strike", "expiry", "entry_date"])["qty"].sum()
+ for _, leg in opens[opens["expiry"] <= last].iterrows():
+ assert done.get((leg["strike"], leg["expiry"], leg["timestamp"]), 0) == leg["qty"], leg