"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): use configured default IV for HV warm-up bars (#1293)
cgycorey54abd8ff122b
diff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.pyindex 4389f91b2..3964682db 100644--- a/agent/backtest/engines/options_portfolio.py+++ b/agent/backtest/engines/options_portfolio.py@@ -34,19 +34,24 @@ from src.quantlib.options import bs_greeks, bs_price, normalise_option_type# --- Historical volatility ----def historical_volatility(close: pd.Series, window: int = 30) -> pd.Series:+def historical_volatility(+ close: pd.Series, window: int = 30, default_iv: float = 0.3+) -> pd.Series:"""Calculate annualised historical volatility from a close price series.Args:close: Close price Series.window: Rolling window in days.+ default_iv: Volatility used for bars without a full window. Backfilling+ the first computed window here would price bars before it with+ information from the window's own end (#1293).Returns:Annualised historical volatility Series."""log_ret = np.log(close / close.shift(1))hv = log_ret.rolling(window=window).std() * np.sqrt(252)- return hv.fillna(hv.dropna().iloc[0] if len(hv.dropna()) > 0 else 0.3)+ return hv.fillna(default_iv)# --- IV Smile model (v2) ---@@ -213,6 +218,7 @@ 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+ default_iv = options_cfg.get("default_iv", 0.3)# Load underlying datadata_map = loader.fetch(codes, start_date, end_date)@@ -223,7 +229,7 @@ def run_options_backtest(# Compute implied volatility (approximated by historical volatility)iv_map: Dict[str, pd.Series] = {}for code, df in data_map.items():- iv_map[code] = historical_volatility(df["close"])+ iv_map[code] = historical_volatility(df["close"], default_iv=default_iv)# Generate trade signalssignals = engine.generate(data_map)@@ -263,14 +269,22 @@ def run_options_backtest(for code, df in data_map.items():if ts in df.index:spot_prices[code] = float(df.at[ts, "close"])- ivs[code] = float(iv_map[code].at[ts]) if ts in iv_map[code].index else 0.3+ ivs[code] = (+ float(iv_map[code].at[ts])+ if ts in iv_map[code].index+ else default_iv+ )else:# Use the last available pricebefore = df.index[df.index <= ts]if len(before) > 0:last = before[-1]spot_prices[code] = float(df.at[last, "close"])- ivs[code] = float(iv_map[code].at[last]) if last in iv_map[code].index else 0.3+ ivs[code] = (+ float(iv_map[code].at[last])+ if last in iv_map[code].index+ else default_iv+ )# 2a. American early exercise (v2): exercise if intrinsic > continuationif exercise_style == "american":@@ -278,7 +292,7 @@ def run_options_backtest(if pos.is_expired(ts):continue # handled belowspot = spot_prices.get(pos.underlying_code, 0.0)- iv_val_ex = ivs.get(pos.underlying_code, 0.3)+ iv_val_ex = ivs.get(pos.underlying_code, default_iv)T_ex = pos.time_to_expiry(ts)if T_ex <= 0:continue@@ -340,7 +354,7 @@ def run_options_backtest(underlying = sig.get("underlying", codes[0] if codes else "")spot = spot_prices.get(underlying, 0.0)- iv_val = ivs.get(underlying, 0.3)+ iv_val = ivs.get(underlying, default_iv)for leg in legs:# Fold before it is priced, matched and recorded: config comes@@ -453,7 +467,7 @@ def run_options_backtest(for pos in positions:spot = spot_prices.get(pos.underlying_code, 0.0)- iv_val = ivs.get(pos.underlying_code, 0.3)+ iv_val = ivs.get(pos.underlying_code, default_iv)T = pos.time_to_expiry(ts)mark_iv = leg_iv(spot, pos.strike, iv_val, iv_skew, iv_curvature)diff --git a/agent/tests/test_options_hv_warmup.py b/agent/tests/test_options_hv_warmup.pynew file mode 100644index 000000000..338aed167--- /dev/null+++ b/agent/tests/test_options_hv_warmup.py@@ -0,0 +1,44 @@+"""Regression: the HV warm-up must not backfill the first computed window.++``historical_volatility`` filled the orphan bars of the 30-day rolling window+with the first valid value -- the volatility computed over bars 1..30, so bars+1..29 were priced with information from bar 30. Warm-up bars now use the+configured default IV instead; bars with a full window keep the real rolling+volatility. (#1293, part 2.)+"""++from __future__ import annotations++import numpy as np+import pandas as pd++from backtest.engines.options_portfolio import historical_volatility+++def test_warmup_bars_use_default_iv_not_the_first_computed_window() -> None:+ close = pd.Series([100.0] * 40)+ hv = historical_volatility(close)++ # Constant closes: the only rolling volatility anywhere is zero, so the old+ # backfill would plant 0.0 over the warm-up. The first 30 bars must be the+ # default IV instead, the rest the real (zero) rolling volatility.+ assert hv.iloc[:30].eq(0.3).all()+ assert hv.iloc[30:].eq(0.0).all()+++def test_default_iv_is_configurable() -> None:+ close = pd.Series([100.0] * 40)+ hv = historical_volatility(close, default_iv=0.5)++ assert hv.iloc[:30].eq(0.5).all()+ assert hv.iloc[30:].eq(0.0).all()+++def test_full_window_bars_are_unchanged_by_the_warmup_fix() -> None:+ """A trend keeps its real rolling vol everywhere past the warm-up."""+ close = pd.Series(np.linspace(100.0, 200.0, 60))+ hv = historical_volatility(close)++ log_ret = np.log(close / close.shift(1))+ expected = log_ret.rolling(30).std() * np.sqrt(252)+ pd.testing.assert_series_equal(hv.iloc[30:], expected.iloc[30:].fillna(0.0))