"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Merge PR #1306: hold margin on short option legs and gate opens on buying power
Haozhe Wud89225c52d1a
diff --cc agent/backtest/engines/options_portfolio.pyindex b4c6ce21e,47af65028..68fb8a0f3--- a/agent/backtest/engines/options_portfolio.py+++ b/agent/backtest/engines/options_portfolio.py@@@ -220,10 -213,11 +220,15 @@@ def run_options_backtestexercise_style = options_cfg.get("exercise_style", "european") # v2: "european" or "american"iv_skew = options_cfg.get("iv_skew", 0.0) # v2: smile skew param (0 = flat)iv_curvature = options_cfg.get("iv_curvature", 0.0) # v2: smile curvature+ same_day_fill = options_cfg.get("same_day_fill", False)+ default_iv = options_cfg.get("default_iv", 0.3)+ if not math.isfinite(default_iv) or default_iv <= 0.0:+ raise ValueError("options_config.default_iv must be a finite, positive float")+ # Short legs hold margin and every open checks buying power; opt out for+ # research runs that intentionally model unconstrained leverage.+ margin_enabled = bool(options_cfg.get("margin_enabled", True))+ margin_rate = float(options_cfg.get("margin_rate", 0.20))+ margin_floor_rate = float(options_cfg.get("margin_floor_rate", 0.10))# Load underlying datadata_map = loader.fetch(codes, start_date, end_date)@@@ -266,25 -258,36 +271,52 @@@greeks_records: List[Dict[str, Any]] = []equity_records: List[Dict[str, Any]] = []+ def short_margin_per_unit(option_type: str, spot: float, strike: float,+ premium: float) -> float:+ """CBOE-style short margin per unit: premium plus the larger of+ ``margin_rate`` of spot minus the out-of-the-money amount and a+ ``margin_floor_rate`` floor (spot for calls, strike for puts)."""+ if option_type == "call":+ otm = max(0.0, strike - spot)+ return premium + max(margin_rate * spot - otm, margin_floor_rate * spot)+ otm = max(0.0, spot - strike)+ return premium + max(margin_rate * spot - otm, margin_floor_rate * strike)++ def current_short_margin(ts: pd.Timestamp) -> float:+ """Margin the open short legs would post right now, re-marked daily."""+ total = 0.0+ for pos in positions:+ if pos.qty >= 0:+ continue+ spot = spot_prices.get(pos.underlying_code, 0.0)+ iv_val = ivs.get(pos.underlying_code, 0.3)+ mark_iv = leg_iv(spot, pos.strike, iv_val, iv_skew, iv_curvature)+ mark = bs_price(spot, pos.strike, pos.time_to_expiry(ts),+ risk_free_rate, mark_iv, pos.option_type)+ total += short_margin_per_unit(+ pos.option_type, spot, pos.strike, mark+ ) * abs(pos.qty) * contract_multiplier+ return total+- for current_date in dates:+ for idx, current_date in enumerate(dates):+ full_idx = idx + warmup_endts = pd.Timestamp(current_date)date_str = str(ts.date()) if hasattr(ts, "date") else str(ts)+ # Signals are dated the bar they were computed on and priced/filled on+ # the next bar's close, executed end-of-day on the bar after the+ # decision (#1293). Equity engines fill the next bar's open; the+ # options engine deliberately fills the next close because signals are+ # computed on end-of-day data. A signal dated the last warm-up bar+ # fills on the first evaluated bar, matching the equity convention;+ # only signals dated before the very first loaded bar can never fill.+ # Set options_config.same_day_fill to price a signal on its own date.+ if same_day_fill:+ signal_date = date_str+ elif full_idx > 0:+ prev = pd.Timestamp(full_dates[full_idx - 1])+ signal_date = str(prev.date()) if hasattr(prev, "date") else str(prev)+ else:+ signal_date = None# 1. Get underlying price and IV for the current dayspot_prices: Dict[str, float] = {}@@@ -779,7 -810,7 +849,9 @@@ def _calc_options_metrics"sharpe": round(sharpe, 4) if sharpe is not None else None,"calmar": round(calmar, 4) if calmar is not None else None,"sortino": round(sortino, 4) if sortino is not None else None,-- "trade_count": len(trades),++ # A rejected open never reached the book; it is reported separately as++ # options_rejected_opens and must not inflate the trade count.++ "trade_count": sum(1 for t in trades if t.get("side") != "reject"),"win_rate": round(win_rate, 4),"profit_loss_ratio": round(pl_ratio, 4),"warnings": warnings,diff --cc agent/tests/test_options_margin.pyindex 000000000,626ad64b9..c05837059mode 000000,100644..100644--- a/agent/tests/test_options_margin.py+++ b/agent/tests/test_options_margin.py@@@ -1,0 -1,130 +1,152 @@@+ """Regression (#1294): the options engine now holds margin on short legs and+ rejects opens that exceed buying power.++ Previously a short open simply credited the premium and cash could go+ arbitrarily negative, so naked-selling strategies produced a free-money+ curve. The margin model is CBOE-style (premium + max(rate * spot - OTM,+ floor * base)), marked daily, with ``margin_enabled: false`` opting back into+ the legacy unconstrained behavior for research runs.+ """++ from __future__ import annotations++ from pathlib import Path++ import pandas as pd++ from backtest.engines.options_portfolio import run_options_backtest++ _DATES = pd.bdate_range("2025-01-01", periods=6)+ _BARS = pd.DataFrame(+ {+ "open": [100.0, 100.0, 100.0, 120.0, 120.0, 120.0],+ "high": [101.0, 101.0, 101.0, 121.0, 121.0, 121.0],+ "low": [99.0, 99.0, 99.0, 119.0, 119.0, 119.0],+ "close": [100.0, 100.0, 100.0, 120.0, 120.0, 120.0],+ "volume": [1000] * 6,+ },+ index=_DATES,+ )+++ class _Loader:+ name = "yfinance"++ def fetch(self, codes, start_date, end_date): # noqa: ANN001+ return {"SPY": _BARS.copy()}+++ def _engine(signals):+ class _Engine:+ def generate(self, data_map): # noqa: ANN001+ return signals++ return _Engine()+++ def _open(date, legs, underlying="SPY"):+ return {"date": date, "action": "open", "underlying": underlying, "legs": legs}+++ def _close(date, legs, underlying="SPY"):+ return {"date": date, "action": "close", "underlying": underlying, "legs": legs}+++ def _run(tmp_path: Path, signals, initial_cash=100_000, options_config=None):+ config = {+ "codes": ["SPY"],+ "start_date": "2025-01-01",+ "end_date": "2025-01-08",+ "source": "yfinance",+ "engine": "options",+ "initial_cash": initial_cash,+ "commission": 0.0,+ "options_config": options_config or {"risk_free_rate": 0.0, "contract_multiplier": 1.0},+ }+ run_options_backtest(config, _Loader(), _engine(signals), tmp_path)+ artifacts = tmp_path / "artifacts"+ trades = pd.read_csv(artifacts / "trades.csv")+ equity = pd.read_csv(artifacts / "equity.csv")+ metrics = pd.read_csv(artifacts / "metrics.csv")+ return trades, equity, metrics+++ def test_naked_short_beyond_buying_power_rejects(tmp_path: Path) -> None:- # 1 call leg of 500 contracts at spot 100: margin far exceeds the account.++ # 500 ATM calls at spot 100. With commission 0 and multiplier 1 the premium++ # cancels out of the affordability test, leaving cash >= 0.20 * spot * qty:++ # 10_000 vs 10_000 sits exactly on the boundary and is decided by float++ # noise in a premium that moves with days-to-expiry. Halve the cash so the++ # assertion is about the margin rule, not about the last bit of a float.+ signals = [_open("2025-01-01", [{"type": "call", "strike": 100.0, "expiry": "2025-03-21", "qty": -500}])]- trades, equity, metrics = _run(tmp_path, signals, initial_cash=10_000)++ trades, equity, metrics = _run(tmp_path, signals, initial_cash=5_000)++ assert trades.iloc[0]["side"] == "reject"+ assert trades.iloc[0]["reason"] == "insufficient buying power"+ assert equity["margin_hold"].max() == 0.0+ assert metrics.iloc[0]["options_rejected_opens"] == 1+++ def test_short_within_buying_power_posts_margin(tmp_path: Path) -> None:+ signals = [_open("2025-01-01", [{"type": "call", "strike": 110.0, "expiry": "2025-03-21", "qty": -10}])]+ trades, equity, metrics = _run(tmp_path, signals)++ assert trades.iloc[0]["side"] == "sell"++ # Signals fill on the bar after the decision (#1293), so bar 0 is still++ # flat; the hold appears from the fill bar onward.++ filled = equity[equity["margin_hold"] > 0.0]++ assert not filled.empty+ # CBOE put/call margin on an OTM call at entry (premium + max(20% * spot -+ # OTM, 10% * spot)); the hold must be positive and tracked daily.- assert equity.iloc[0]["margin_hold"] > 0.0++ first_hold = float(filled.iloc[0]["margin_hold"])+ # After the underlying jumps to 120, the call is ITM and the hold grows.- assert equity.iloc[-1]["margin_hold"] > equity.iloc[0]["margin_hold"]++ assert float(equity.iloc[-1]["margin_hold"]) > first_hold+++ def test_margin_releases_on_close(tmp_path: Path) -> None:+ leg = {"type": "call", "strike": 110.0, "expiry": "2025-03-21", "qty": -10}+ signals = [+ _open("2025-01-01", [leg]),+ _close("2025-01-03", [{"type": "call", "strike": 110.0, "expiry": "2025-03-21"}]),+ ]+ trades, equity, metrics = _run(tmp_path, signals)++ assert trades.iloc[0]["side"] == "sell"+ assert trades.iloc[1]["side"] == "close"+ assert equity.iloc[-1]["margin_hold"] == 0.0+++ def test_long_open_beyond_buying_power_rejects(tmp_path: Path) -> None:+ signals = [_open("2025-01-01", [{"type": "call", "strike": 100.0, "expiry": "2025-03-21", "qty": 100_000}])]+ trades, equity, metrics = _run(tmp_path, signals, initial_cash=1_000)++ assert trades.iloc[0]["side"] == "reject"+ assert metrics.iloc[0]["options_rejected_opens"] == 1+++ def test_margin_disabled_restores_unconstrained_behavior(tmp_path: Path) -> None:+ signals = [_open("2025-01-01", [{"type": "call", "strike": 100.0, "expiry": "2025-03-21", "qty": -500}])]+ trades, equity, metrics = _run(+ tmp_path,+ signals,+ initial_cash=10_000,+ options_config={"risk_free_rate": 0.0, "contract_multiplier": 1.0, "margin_enabled": False},+ )++ # Legacy path: the short opens, cash goes negative, no margin is tracked.+ assert trades.iloc[0]["side"] == "sell"+ assert equity["margin_hold"].max() == 0.0+ assert "options_rejected_opens" not in metrics.columns++++++def test_rejected_opens_do_not_count_as_trades(tmp_path: Path) -> None:++ """A rejected open is reported, not counted as a trade that happened.++++ `trade_count` counts every record in trades.csv, so appending a reject row++ would otherwise book an order the engine refused as executed volume.++ """++ signals = [_open("2025-01-01", [{"type": "call", "strike": 100.0, "expiry": "2025-03-21", "qty": -500}])]++ trades, equity, metrics = _run(tmp_path, signals, initial_cash=5_000)++++ assert (trades["side"] == "reject").sum() == 1++ assert metrics.iloc[0]["options_rejected_opens"] == 1++ assert metrics.iloc[0]["trade_count"] == 0