"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): hold margin on short option legs and gate opens on buying power
Yufeng He00dc9620c324
diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.pyindex 4389f91b2..47af65028 100644--- a/agent/backtest/engines/options_portfolio.py+++ b/agent/backtest/engines/options_portfolio.py@@ -213,6 +213,11 @@ def run_options_backtest(exercise_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+ # 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)@@ -253,6 +258,33 @@ def run_options_backtest(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:ts = pd.Timestamp(current_date)date_str = str(ts.date()) if hasattr(ts, "date") else str(ts)@@ -360,6 +392,36 @@ def run_options_backtest(if action == "open":# Open: long pays premium, short receives premiumabs_cost = opt_price * abs(qty) * contract_multiplier+ if margin_enabled:+ # Buying power: cash already posted as short margin is+ # not spendable. Longs need the premium; shorts need+ # the new leg's margin net of the premium it brings in.+ posted = current_short_margin(ts)+ if qty > 0:+ affordable = cash - posted >= abs_cost * (1 + commission)+ else:+ leg_margin = short_margin_per_unit(+ leg_type, spot, strike, opt_price+ ) * abs(qty) * contract_multiplier+ affordable = (+ cash + abs_cost * (1 - commission)+ >= posted + leg_margin+ )+ if not affordable:+ trade_records.append({+ "timestamp": date_str,+ "code": underlying,+ "option_type": leg_type,+ "strike": strike,+ "expiry": expiry,+ "side": "reject",+ "price": round(opt_price, 4),+ "qty": qty,+ "pnl": 0.0,+ "entry_date": date_str,+ "reason": "insufficient buying power",+ })+ continueif qty > 0:cash -= abs_cost * (1 + commission)else:@@ -473,6 +535,7 @@ def run_options_backtest("equity": round(portfolio_value, 4),"cash": round(cash, 4),"positions_value": round(portfolio_value - cash, 4),+ "margin_hold": round(current_short_margin(ts), 4) if margin_enabled else 0.0,})greeks_records.append({@@ -493,6 +556,13 @@ def run_options_backtest(equity_series = equity_df.set_index("timestamp")["equity"]metrics = _calc_options_metrics(equity_series, initial_cash, trade_records, bars_per_year)+ if margin_enabled:+ metrics["options_margin_hold"] = round(+ float(equity_df["margin_hold"].iloc[-1]), 4+ )+ metrics["options_rejected_opens"] = sum(+ 1 for record in trade_records if record.get("side") == "reject"+ )# Write artifactsout = run_dir / "artifacts"@@ -504,7 +574,7 @@ def run_options_backtest(equity_df.to_csv(out / "equity.csv", index=False)trade_cols = ["timestamp", "code", "option_type", "strike", "expiry",- "side", "price", "qty", "pnl", "entry_date"]+ "side", "price", "qty", "pnl", "entry_date", "reason"]pd.DataFrame(trade_records or [], columns=trade_cols).to_csv(out / "trades.csv", index=False)diff --git a/agent/tests/test_options_margin.py b/agent/tests/test_options_margin.pynew file mode 100644index 000000000..626ad64b9--- /dev/null+++ b/agent/tests/test_options_margin.py@@ -0,0 +1,130 @@+"""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.+ 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)++ 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"+ # 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+ # 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"]+++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