ivolatility-backtesting 2.165__tar.gz → 2.167__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/PKG-INFO +1 -1
  2. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/ivolatility_backtesting/ivolatility_backtesting.py +231 -33
  3. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/PKG-INFO +1 -1
  4. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/SOURCES.txt +3 -0
  5. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/pyproject.toml +1 -1
  6. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2150_prompt_patterns.py +2 -0
  7. ivolatility_backtesting-2.167/tests/test_2167_saturday_expiration.py +181 -0
  8. ivolatility_backtesting-2.167/tests/test_2167_xsp_settlement.py +83 -0
  9. ivolatility_backtesting-2.167/tests/test_stop_reference_eod_close.py +223 -0
  10. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/README.md +0 -0
  11. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/ivolatility_backtesting/__init__.py +0 -0
  12. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/dependency_links.txt +0 -0
  13. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/requires.txt +0 -0
  14. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/top_level.txt +0 -0
  15. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/setup.cfg +0 -0
  16. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2142_fixes.py +0 -0
  17. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2144_duckdb_dedup.py +0 -0
  18. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2146_vix_vro.py +0 -0
  19. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2147_cents_multiplier.py +0 -0
  20. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2148_loader_memory.py +0 -0
  21. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2149_client_errors.py +0 -0
  22. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2152_cache_lock_and_rate_limit.py +0 -0
  23. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2153_cache_lock_kept.py +0 -0
  24. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2154_put_atm_legs.py +0 -0
  25. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2155_bar_prefetch.py +0 -0
  26. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2155_intraday_exits.py +0 -0
  27. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2155_ivx_stock_holes.py +0 -0
  28. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2155_key_redaction.py +0 -0
  29. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2155_long_expiry.py +0 -0
  30. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2155_opt_stop_merge.py +0 -0
  31. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2156_phantom_quotes.py +0 -0
  32. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2157_sl_symbol.py +0 -0
  33. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2158_default_path_golden.py +0 -0
  34. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2158_entry_time.py +0 -0
  35. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2159_entry_rule.py +0 -0
  36. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2160_day_price_order.py +0 -0
  37. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2160_exit_rule.py +0 -0
  38. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2160_option_lean_rule.py +0 -0
  39. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2160_prefetch_cancel.py +0 -0
  40. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2161_assignment.py +0 -0
  41. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2162_entry_minute_window.py +0 -0
  42. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2163_rotation.py +0 -0
  43. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2164_stock_price_stops.py +0 -0
  44. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2165_parquet_engine_error.py +0 -0
  45. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_2165_renamed_symbol.py +0 -0
  46. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_price_ta_indicators.py +0 -0
  47. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_stock_loader_coverage.py +0 -0
  48. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.167}/tests/test_vix_percentile_direction.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ivolatility_backtesting
3
- Version: 2.165
3
+ Version: 2.167
4
4
  Summary: A universal backtesting framework for financial strategies using the IVolatility API.
5
5
  Author-email: IVolatility <support@ivolatility.com>
6
6
  Project-URL: Homepage, https://ivolatility.com
@@ -1907,11 +1907,11 @@ def _pnl_pct_base(pnl, pnl_pct):
1907
1907
  return round(abs(pnl) / abs(pnl_pct) * 100, 6)
1908
1908
 
1909
1909
 
1910
- _INDEX_OPTION_ROOTS_1615 = {'SPX', 'SPXW', 'NDX', 'NDXP', 'RUT', 'RUTW', 'DJX', 'XSP', 'VIX', 'VIXW', 'OEX', 'XEO'}
1910
+ _INDEX_OPTION_ROOTS_1615 = {'SPX', 'SPXW', 'NDX', 'NDXP', 'RUT', 'RUTW', 'DJX', 'XSP', 'XSPAM', 'VIX', 'VIXW', 'OEX', 'XEO'}
1911
1911
 
1912
1912
 
1913
1913
  def _session_bars(sorted_times, symbol):
1914
- """Tradable bar times: after the 09:30 bar (it repeats the previous close) up to the close,
1914
+ """Tradable bar times: after the 09:30 bar (stale or pre-open quotes) up to the close,
1915
1915
  16:15 for cash-index options, 16:00 for equity options."""
1916
1916
  close = '16:15' if str(symbol or '').upper() in _INDEX_OPTION_ROOTS_1615 else '16:00'
1917
1917
  return [t for t in (sorted_times or []) if len(str(t)) < 16 or '09:30' < str(t)[11:16] <= close]
@@ -2001,6 +2001,35 @@ def _after_entry_bar(pos, current_date, sorted_times):
2001
2001
  return [t for t in (sorted_times or []) if len(str(t)) >= 16 and entry_ts < str(t)[:19] <= last]
2002
2002
 
2003
2003
 
2004
+ def _after_open_bar(sorted_times):
2005
+ """Bar times after 09:30: with the previous EOD close as the stop reference the 09:30 bar is not scanned."""
2006
+ return [t for t in (sorted_times or []) if len(str(t)) < 16 or str(t)[11:16] > '09:30']
2007
+
2008
+
2009
+ def _held_over_prev_close(pos, current_date):
2010
+ """True when the position was opened before current_date, so it existed at the previous session's close."""
2011
+ pos = pos or {}
2012
+ entry = _as_date_obj(pos.get('entry_timestamp') or pos.get('entry_date'))
2013
+ current = _as_date_obj(current_date)
2014
+ return entry is not None and current is not None and entry < current
2015
+
2016
+
2017
+ # (api base, symbol, date, cp, expiration, region) -> EOD CLOSE chain rows (never 15:45); past closes never change
2018
+ _PREV_CLOSE_QUOTES = {}
2019
+ _PREV_CLOSE_QUOTES_MAX = 2000
2020
+ _PREV_CLOSE_FALLBACK_WARNED = []
2021
+
2022
+
2023
+ def _warn_prev_close_fallback(symbol, prev_date, bar_time, reason):
2024
+ """Every fallback goes to the log; the console gets the first one per process."""
2025
+ msg = (f"[SL REFERENCE] {symbol}: {reason} on {prev_date}; the stop reference falls back to the "
2026
+ f"{bar_time} bar")
2027
+ _bt_logger.warning(msg)
2028
+ if not _PREV_CLOSE_FALLBACK_WARNED:
2029
+ _PREV_CLOSE_FALLBACK_WARNED.append(True)
2030
+ print(f"⚠️ {msg} (further fallbacks go to the log only)")
2031
+
2032
+
2004
2033
  _SDK_CALL_STATS = {'n': 0, 'ms': 0.0}
2005
2034
  _SDK_CALL_STATS_LOCK = threading.Lock()
2006
2035
 
@@ -10351,10 +10380,7 @@ class StopLossManager:
10351
10380
 
10352
10381
  sorted_times = sorted(bars_by_time.keys())
10353
10382
 
10354
- # NOTE: 09:30 bar contains PREVIOUS DAY CLOSE prices (stale), not real-time quotes
10355
- # We intentionally KEEP the 09:30 bar for SL baseline calculation
10356
- # This allows measuring P&L from previous close, which includes overnight gap
10357
- # The optionBidDateTime field shows when the quote was actually made (prev day ~16:00)
10383
+ # The 09:30 bar is not a tradable quote; callers drop it (_session_bars / _after_open_bar)
10358
10384
 
10359
10385
  if self.debuginfo >= 2:
10360
10386
  total_bars = sum(len(bars) for bars in bars_by_time.values())
@@ -10362,6 +10388,98 @@ class StopLossManager:
10362
10388
 
10363
10389
  return bars_by_time, sorted_times
10364
10390
 
10391
+ def _previous_session(self, current_date):
10392
+ """Trading day before current_date: from the run's trading days, else the previous weekday."""
10393
+ current = _as_date_obj(current_date)
10394
+ if current is None:
10395
+ return None
10396
+ days = (self.config.get('_trading_days')
10397
+ or (self.config.get('_runtime_parent_config') or {}).get('_trading_days') or [])
10398
+ prior = [d for d in (_as_date_obj(x) for x in days) if d is not None and d < current]
10399
+ if prior:
10400
+ return max(prior)
10401
+ return (pd.Timestamp(current) - pd.offsets.BDay(1)).date()
10402
+
10403
+ def _prev_close_chain(self, symbol, trade_date, cp, exp_str):
10404
+ """EOD close rows of one side and expiration on trade_date; None when the request failed."""
10405
+ runtime = self.config.get('_runtime_parent_config') or self.config
10406
+ region = runtime.get('region')
10407
+ key = (_API_BASE, str(symbol).upper(), trade_date, cp, exp_str, region)
10408
+ if key in _PREV_CLOSE_QUOTES:
10409
+ return _PREV_CLOSE_QUOTES[key]
10410
+ dte = (_as_date_obj(exp_str) - _as_date_obj(trade_date)).days
10411
+ params = {'symbol': symbol, 'tradeDate': trade_date, 'dteFrom': dte, 'dteTo': dte, 'cp': cp,
10412
+ 'moneynessFrom': -100, 'moneynessTo': 100}
10413
+ if region:
10414
+ params['region'] = region
10415
+ cache_config = runtime.get('cache_config') or self.config.get('cache_config') or self.cache_config or None
10416
+ try:
10417
+ # Explicit close snapshot: the loader's options may hold the 15:45 snapshot or its patch
10418
+ result = api_call(_get_options_endpoints('close')['filtered'], cache_config,
10419
+ skip_parquet_cache=True, **params)
10420
+ except Exception as e:
10421
+ _bt_logger.warning(f"[SL REFERENCE] {symbol} {trade_date} {cp} {exp_str}: close request failed: {e}")
10422
+ return None
10423
+ if result is None:
10424
+ return None
10425
+ data = result.get('data') if isinstance(result, dict) else result
10426
+ chain = data if isinstance(data, pd.DataFrame) else pd.DataFrame(data if data is not None else [])
10427
+ if not chain.empty:
10428
+ chain = normalize_dataframe(chain.copy(), data_type='options', optimize_memory=False)
10429
+ if len(_PREV_CLOSE_QUOTES) >= _PREV_CLOSE_QUOTES_MAX:
10430
+ _PREV_CLOSE_QUOTES.clear()
10431
+ _PREV_CLOSE_QUOTES[key] = chain
10432
+ return chain
10433
+
10434
+ def _prev_close_leg_bars(self, symbol, current_date, legs, expiration):
10435
+ """Each leg at the previous session's EOD close quote, shaped like intraday bars.
10436
+
10437
+ Returns (bars, trade_date, missing): bars is None and missing names the first leg without a quote."""
10438
+ prev = self._previous_session(current_date)
10439
+ if prev is None or not symbol:
10440
+ return None, None, 'no previous session'
10441
+ trade_date = prev.strftime('%Y-%m-%d')
10442
+ default_exp = _as_date_obj(expiration)
10443
+ bars = []
10444
+ for leg in legs:
10445
+ exp = _as_date_obj(leg.get('expiration')) or default_exp
10446
+ cp = 'C' if str(leg.get('type', '')).upper().startswith('C') else 'P'
10447
+ label = f"{leg.get('strike')}{cp} {exp}"
10448
+ if exp is None:
10449
+ return None, trade_date, f'{label}: no expiration'
10450
+ exp_str = exp.strftime('%Y-%m-%d')
10451
+ chain = self._prev_close_chain(symbol, trade_date, cp, exp_str)
10452
+ if chain is None:
10453
+ return None, trade_date, f'{label}: close request failed'
10454
+ rows = chain
10455
+ if not rows.empty and {'strike', 'expiration', 'type'} <= set(rows.columns):
10456
+ rows = rows[((pd.to_numeric(rows['strike'], errors='coerce') - float(leg['strike'])).abs() < 1e-6)
10457
+ & (pd.to_datetime(rows['expiration'], errors='coerce').dt.strftime('%Y-%m-%d') == exp_str)
10458
+ & (rows['type'].astype(str).str.upper().str[:1] == cp)]
10459
+ else:
10460
+ rows = rows.iloc[0:0]
10461
+ if len(rows) > 1 and 'option_symbol' in rows.columns:
10462
+ # SPX/SPXW share expiration and strike on AM-settled dates: prefer the requested root
10463
+ same_root = rows[rows['option_symbol'].astype(str).str.split().str[0].str.upper() == str(symbol).upper()]
10464
+ rows = same_root if not same_root.empty else rows
10465
+ if rows.empty:
10466
+ return None, trade_date, f'{label}: no EOD close quote'
10467
+ row = rows.iloc[0]
10468
+ bid = pd.to_numeric(row.get('bid'), errors='coerce')
10469
+ ask = pd.to_numeric(row.get('ask'), errors='coerce')
10470
+ bid = 0.0 if pd.isna(bid) else float(bid)
10471
+ ask = 0.0 if pd.isna(ask) else float(ask)
10472
+ if bid == 0 and ask == 0:
10473
+ return None, trade_date, f'{label}: EOD close quote has bid=ask=0'
10474
+ bars.append({
10475
+ 'time': trade_date, 'strike': leg['strike'], 'type': cp, 'expiration': exp_str,
10476
+ 'bid': bid, 'ask': ask, 'price': (bid + ask) / 2,
10477
+ 'delta': row.get('delta', 0), 'gamma': row.get('gamma', 0), 'vega': row.get('vega', 0),
10478
+ 'theta': row.get('theta', 0), 'iv': row.get('iv', 0),
10479
+ 'underlying_price': row.get('underlying_price', 0),
10480
+ })
10481
+ return bars, trade_date, None
10482
+
10365
10483
  def _get_position_legs(self, pos, strategy_type):
10366
10484
  """
10367
10485
  Get leg details (strike, type, direction) for a position based on strategy type.
@@ -11132,6 +11250,8 @@ class StopLossManager:
11132
11250
  bars_by_time, sorted_times = self._get_legs_intraday_data(symbol, current_date, legs, expiration, minute_interval, position=pos)
11133
11251
  if not pos.get('sl_baseline_reset'):
11134
11252
  sorted_times = _session_bars(sorted_times, symbol)
11253
+ elif pos.get('prev_day_close_source') == 'eod_close':
11254
+ sorted_times = _after_open_bar(sorted_times)
11135
11255
  sorted_times = _after_entry_bar(pos, current_date, sorted_times)
11136
11256
 
11137
11257
  if not bars_by_time or not sorted_times:
@@ -11197,7 +11317,7 @@ class StopLossManager:
11197
11317
  # [DENOM FIX] For credit strategies, measure P&L as change in close cost
11198
11318
  # relative to the baseline close cost (abs value).
11199
11319
  # P&L% = (close_cost_now - close_cost_baseline) / |close_cost_baseline|
11200
- # SL is relative to the 9:30 close cost — NOT original credit.
11320
+ # SL is relative to the close cost at the stop reference — NOT original credit.
11201
11321
  baseline_close_cost = pos.get('_sl_baseline_close_cost')
11202
11322
  original_credit = pos.get('_sl_original_credit')
11203
11323
  if baseline_close_cost is not None:
@@ -11214,7 +11334,7 @@ class StopLossManager:
11214
11334
  pnl_from_baseline = current_value - baseline_close_cost # change in close cost
11215
11335
  denom = abs(baseline_close_cost)
11216
11336
  else:
11217
- # Simple credit (straddle, single leg): entry_value is the 09:30 close cost
11337
+ # Simple credit (straddle, single leg): entry_value is the close cost at the reference
11218
11338
  # (or the credit before any reset); current_value is -close cost now
11219
11339
  pnl_from_baseline = abs(entry_value) + current_value
11220
11340
  denom = abs(entry_value)
@@ -11326,12 +11446,12 @@ class StopLossManager:
11326
11446
 
11327
11447
  # ========================================================
11328
11448
  # [SL BASELINE RESET] Reset baseline prices when monitoring starts
11329
- # For earnings strategy: SL starts on event day with 9:31 prices
11449
+ # Reference = previous session's EOD close quote; monitoring starts at the first bar after 09:30
11330
11450
  # ========================================================
11331
11451
  # [EARNINGS SL] Check position-level first for per-position control
11332
11452
  reset_baseline_on_start = pos.get('reset_baseline_on_sl_start', False) or self.config.get('reset_baseline_on_sl_start', False) or intraday_settings.get('reset_baseline_on_sl_start', False)
11333
11453
  if reset_baseline_on_start and not pos.get('sl_baseline_reset', False):
11334
- # First time SL monitoring is active - reset baseline to 9:31 intraday prices
11454
+ # First time SL monitoring is active - reset baseline to the stop reference quotes
11335
11455
  # This allows entering 14 days before earnings but only monitoring SL from event day
11336
11456
  old_entry = pos['entry_price']
11337
11457
  old_total_cost = pos.get('total_cost', 0)
@@ -11340,7 +11460,7 @@ class StopLossManager:
11340
11460
  intraday_mode = intraday_settings.get('intraday_mode', 'disabled')
11341
11461
  minute_interval = intraday_settings.get('minute_interval', 'MINUTE_5')
11342
11462
 
11343
- # [EARNINGS SL] Fetch 9:31 intraday prices for baseline when intraday_mode is auto/enabled
11463
+ # [EARNINGS SL] Fetch the reference quotes for the baseline when intraday_mode is auto/enabled
11344
11464
  # COVERED_CALL: always fetch baseline (stock intraday is always available)
11345
11465
  baseline_value = None
11346
11466
  _cc_baseline_type = pos.get('strategy_type', '')
@@ -11362,14 +11482,26 @@ class StopLossManager:
11362
11482
  )
11363
11483
  sorted_times = _after_entry_bar(pos, current_date, sorted_times)
11364
11484
  if bars_by_time and sorted_times:
11365
- # Get first bar (9:31 or earliest available)
11485
+ # Reference = previous session's EOD close quote when the position was held over
11486
+ # it; the first bar of the day (entry-day positions, missing close quote) otherwise
11366
11487
  first_time = sorted_times[0]
11367
11488
  first_bars = bars_by_time[first_time]
11368
- baseline_value = self._calculate_position_current_value(pos, first_bars, strategy_type)
11369
-
11370
- # Store 9:30 prices (prev day close) for each leg - exported to trades.csv
11371
- pos['prev_day_close_time'] = first_time
11372
- for bar in first_bars:
11489
+ ref_bars, ref_time, ref_source = first_bars, first_time, 'first_bar'
11490
+ if not _is_cc_baseline and _held_over_prev_close(pos, current_date):
11491
+ eod_bars, prev_date, missing = self._prev_close_leg_bars(
11492
+ symbol, current_date, legs, expiration)
11493
+ if eod_bars and self._calculate_position_current_value(
11494
+ pos, eod_bars, strategy_type) is not None:
11495
+ ref_bars, ref_time, ref_source = eod_bars, prev_date, 'eod_close'
11496
+ else:
11497
+ _warn_prev_close_fallback(symbol, prev_date, first_time,
11498
+ missing or 'EOD close quote does not price the position')
11499
+ baseline_value = self._calculate_position_current_value(pos, ref_bars, strategy_type)
11500
+
11501
+ # Reference quotes per leg; PositionManager copies prev_day_close_* to its position
11502
+ pos['prev_day_close_time'] = ref_time
11503
+ pos['prev_day_close_source'] = ref_source
11504
+ for bar in ref_bars:
11373
11505
  opt_type = bar.get('type', 'C')
11374
11506
  if opt_type == 'C':
11375
11507
  pos['prev_day_close_call_bid'] = bar.get('bid', 0)
@@ -11382,7 +11514,8 @@ class StopLossManager:
11382
11514
  pos['prev_day_close_underlying'] = bar['underlying_price']
11383
11515
 
11384
11516
  if baseline_value is not None and self.debuginfo >= 2:
11385
- print(f"[SL BASELINE RESET] {position_id}: Got 9:31 baseline=${baseline_value:.2f} at {first_time}")
11517
+ print(f"[SL BASELINE RESET] {position_id}: baseline=${baseline_value:.2f} "
11518
+ f"from {ref_source} {ref_time}")
11386
11519
 
11387
11520
  # COVERED_CALL: option intraday may lack underlying_price.
11388
11521
  # Fetch stock intraday at 9:31 and compute full position baseline.
@@ -12691,10 +12824,66 @@ def _as_date_obj(value):
12691
12824
  return value if isinstance(value, _d.date) else None
12692
12825
 
12693
12826
 
12694
- # AM-settled cash index roots (CBOE): standard 3rd-Friday monthlies settle on
12695
- # the OPENING print (SOQ). Their weekly series (SPXW/NDXP/RUTW/…) are never
12696
- # listed ON the 3rd Friday, so root+3rd-Friday identifies AM exactly.
12697
- _AM_SETTLED_INDEX_ROOTS = {'SPX', 'NDX', 'RUT', 'DJX', 'XSP'}
12827
+ # Standard monthlies of these roots settle on the opening print (SOQ); their weeklies never list on the 3rd Friday.
12828
+ _AM_SETTLED_INDEX_ROOTS = {'SPX', 'NDX', 'RUT', 'DJX', 'XSPAM'}
12829
+ # Root XSP is AM-settled only up to this expiration or under the XSPAM symbol.
12830
+ _XSP_AM_LAST_EXPIRATION = datetime(2013, 11, 3).date()
12831
+
12832
+
12833
+ def _is_standard_monthly_expiration(exp):
12834
+ """3rd Friday, or the Saturday after it (how the API dates older standard monthlies)."""
12835
+ if exp is None:
12836
+ return False
12837
+ if exp.weekday() == 4:
12838
+ return 15 <= exp.day <= 21
12839
+ if exp.weekday() == 5:
12840
+ return 16 <= exp.day <= 22
12841
+ return False
12842
+
12843
+
12844
+ _SETTLE_DAYS_MEMO = {}
12845
+ _SETTLE_MAX_ROLLBACK_DAYS = 4
12846
+
12847
+
12848
+ def _sorted_trading_days(config):
12849
+ cfg = config or {}
12850
+ days = cfg.get('_trading_days')
12851
+ if days is None or len(days) == 0:
12852
+ days = (cfg.get('_runtime_parent_config') or {}).get('_trading_days')
12853
+ if days is None or len(days) == 0:
12854
+ return []
12855
+ entry = _SETTLE_DAYS_MEMO.get(id(days))
12856
+ # the memo keeps the source object alive, so its id cannot be reused while cached
12857
+ if entry is not None and entry[0] is days and entry[1] == len(days):
12858
+ return entry[2]
12859
+ parsed = set()
12860
+ for d in days:
12861
+ try:
12862
+ parsed.add(pd.Timestamp(d).date())
12863
+ except (TypeError, ValueError):
12864
+ continue
12865
+ cached = sorted(parsed)
12866
+ if len(_SETTLE_DAYS_MEMO) >= 8:
12867
+ _SETTLE_DAYS_MEMO.clear()
12868
+ _SETTLE_DAYS_MEMO[id(days)] = (days, len(days), cached)
12869
+ return cached
12870
+
12871
+
12872
+ def _settlement_session(expiration, config=None):
12873
+ """Last trading day on or before the listed expiration date (the API dates older monthlies on Saturday)."""
12874
+ exp = _as_date_obj(expiration)
12875
+ if exp is None:
12876
+ return None
12877
+ days = _sorted_trading_days(config)
12878
+ if days and days[0] <= exp and (days[-1] >= exp or exp.weekday() >= 5):
12879
+ idx = bisect.bisect_right(days, exp)
12880
+ if idx:
12881
+ prev = days[idx - 1]
12882
+ if (exp - prev).days <= _SETTLE_MAX_ROLLBACK_DAYS:
12883
+ return prev
12884
+ if exp.weekday() >= 5:
12885
+ return exp - timedelta(days=exp.weekday() - 4)
12886
+ return exp
12698
12887
 
12699
12888
 
12700
12889
  def _is_am_settled_position(position):
@@ -12715,10 +12904,16 @@ def _is_am_settled_position(position):
12715
12904
  # Every VIX expiration (Wednesday, or Tue/Thu when shifted) is cash-settled
12716
12905
  # on the morning VRO print; the open is only the fallback proxy.
12717
12906
  return True
12907
+ exp = _as_date_obj(position.get('expiration'))
12908
+ if root == 'XSP':
12909
+ if str(position.get('symbol') or '').upper() == 'XSPAM':
12910
+ root = 'XSPAM'
12911
+ else:
12912
+ return (exp is not None and exp <= _XSP_AM_LAST_EXPIRATION
12913
+ and _is_standard_monthly_expiration(exp))
12718
12914
  if root not in _AM_SETTLED_INDEX_ROOTS:
12719
12915
  return False
12720
- exp = _as_date_obj(position.get('expiration'))
12721
- return exp is not None and exp.weekday() == 4 and 15 <= exp.day <= 21
12916
+ return _is_standard_monthly_expiration(exp)
12722
12917
 
12723
12918
 
12724
12919
  # Max calendar gap between a VIX expiration date and the VRO print that settles it.
@@ -12768,7 +12963,7 @@ def _vro_settlement_for(config, expiration):
12768
12963
  # config['assignment_mode']: 'cash' (intrinsic at the close) | 'shares'
12769
12964
  # config['assignment_exit']: 'next_open' | 'next_close' (liquidation of the delivered shares)
12770
12965
  _CASH_SETTLED_ROOTS = _AM_SETTLED_INDEX_ROOTS | {
12771
- 'SPXW', 'SPXPM', 'NDXP', 'RUTW', 'XSP', 'VIX', 'VIXW', 'DJX', 'XND', 'MRUT', 'NANOS', 'MXEF', 'MXEA', 'OEX', 'XEO',
12966
+ 'SPXW', 'SPXPM', 'NDXP', 'RUTW', 'XSP', 'XSPPM', 'VIX', 'VIXW', 'DJX', 'XND', 'MRUT', 'NANOS', 'MXEF', 'MXEA', 'OEX', 'XEO',
12772
12967
  }
12773
12968
 
12774
12969
 
@@ -13977,11 +14172,14 @@ class PositionManager:
13977
14172
 
13978
14173
  # Check if expired
13979
14174
  current_date_normalized = current_date.date() if hasattr(current_date, 'date') else current_date
13980
-
13981
- early_assignment = (current_date_normalized < expiration and
13982
- self._early_assignment_due(position, position_id, current_date_normalized, expiration,
14175
+ # The listed date may be a Saturday or an exchange holiday:
14176
+ # settle on the last trading day on or before it
14177
+ settle_on = _settlement_session(expiration, self.config) or expiration
14178
+
14179
+ early_assignment = (current_date_normalized < settle_on and
14180
+ self._early_assignment_due(position, position_id, current_date_normalized, settle_on,
13983
14181
  price_data, _underlying_arg))
13984
- if current_date_normalized >= expiration or early_assignment:
14182
+ if current_date_normalized >= settle_on or early_assignment:
13985
14183
  # ────────────────────────────────────────────────────────────────
13986
14184
  # SETTLEMENT-AT-EXPIRATION (universal across asset types)
13987
14185
  # ────────────────────────────────────────────────────────────────
@@ -14368,7 +14566,7 @@ class PositionManager:
14368
14566
  # Copy prev_day_close fields from SL manager's position to PositionManager's position
14369
14567
  # (SL manager stores these during baseline reset, but we need them in the exported trade)
14370
14568
  sl_pos = self.sl_manager.positions.get(position_id, {})
14371
- for key in ['prev_day_close_time', 'prev_day_close_underlying',
14569
+ for key in ['prev_day_close_time', 'prev_day_close_source', 'prev_day_close_underlying',
14372
14570
  'prev_day_close_call_bid', 'prev_day_close_call_ask',
14373
14571
  'prev_day_close_put_bid', 'prev_day_close_put_ask']:
14374
14572
  if key in sl_pos:
@@ -14514,7 +14712,7 @@ class PositionManager:
14514
14712
  is_credit = StrategyRegistry.is_credit_strategy(
14515
14713
  strategy_type=strategy_type, position=position
14516
14714
  )
14517
- # entry_value may be the reset 09:30 baseline; the trade is booked against its cost
14715
+ # entry_value may be the reset stop baseline; the trade is booked against its cost
14518
14716
  _orig_cost = abs(position.get('total_cost') or entry_value)
14519
14717
  if is_credit:
14520
14718
  intraday_pnl = _orig_cost + current_value
@@ -15087,7 +15285,7 @@ class PositionManager:
15087
15285
  continue
15088
15286
  # No PT on/after expiration: zero-quote chain rows fake a +100%
15089
15287
  # CREDIT buyback at $0; expiration settles via intrinsic instead
15090
- _pt_exp = _as_date_obj(position.get('expiration'))
15288
+ _pt_exp = _settlement_session(position.get('expiration'), self.config)
15091
15289
  _pt_now = _as_date_obj(current_date)
15092
15290
  _eod_counts = use_eod
15093
15291
  if _pt_exp is not None and _pt_now is not None and _pt_now >= _pt_exp:
@@ -15239,7 +15437,7 @@ class PositionManager:
15239
15437
  fake -100%/+100% off market quotes otherwise); None = guard not applicable."""
15240
15438
  if kwargs.get('settlement_type') == 'intrinsic':
15241
15439
  return None # already settled by check_positions
15242
- exp_d = _as_date_obj(position.get('expiration'))
15440
+ exp_d = _settlement_session(position.get('expiration'), self.config)
15243
15441
  exit_d = _as_date_obj(exit_date)
15244
15442
  if exp_d is None or exit_d is None or exit_d < exp_d:
15245
15443
  return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ivolatility_backtesting
3
- Version: 2.165
3
+ Version: 2.167
4
4
  Summary: A universal backtesting framework for financial strategies using the IVolatility API.
5
5
  Author-email: IVolatility <support@ivolatility.com>
6
6
  Project-URL: Homepage, https://ivolatility.com
@@ -39,6 +39,9 @@ tests/test_2163_rotation.py
39
39
  tests/test_2164_stock_price_stops.py
40
40
  tests/test_2165_parquet_engine_error.py
41
41
  tests/test_2165_renamed_symbol.py
42
+ tests/test_2167_saturday_expiration.py
43
+ tests/test_2167_xsp_settlement.py
42
44
  tests/test_price_ta_indicators.py
43
45
  tests/test_stock_loader_coverage.py
46
+ tests/test_stop_reference_eod_close.py
44
47
  tests/test_vix_percentile_direction.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ivolatility_backtesting"
7
- version = "2.165"
7
+ version = "2.167"
8
8
  description = "A universal backtesting framework for financial strategies using the IVolatility API."
9
9
  readme = "README.md"
10
10
  authors = [
@@ -239,6 +239,8 @@ def _event_day_stop(strategy_type, pl_loss, bars_by_time, eod_chain, **open_kwar
239
239
  'reset_baseline_on_sl_start': True}}
240
240
  pm = _pm(strategy_type, sl)
241
241
  pm.sl_manager._get_legs_intraday_data = lambda *a, **k: (bars_by_time, sorted(bars_by_time))
242
+ # Offline: the previous EOD close quote equals the fixture's 09:30 quote
243
+ pm.sl_manager._prev_close_leg_bars = lambda *a, **k: (bars_by_time['09:30'], '2024-01-04', None)
242
244
  pm.open_position(position_id='P1', symbol='SPY', entry_date=dt.date(2024, 1, 2), quantity=100,
243
245
  strategy_type=strategy_type, contracts=1, strike=470.0, expiration=EXP,
244
246
  underlying_entry_price=460.0, **open_kwargs)
@@ -0,0 +1,181 @@
1
+ # Expirations listed on a Saturday or exchange holiday settle on the last trading day before them.
2
+ # Run: python3 tests/test_2167_saturday_expiration.py or pytest
3
+ import contextlib
4
+ import io
5
+ import os
6
+ import sys
7
+ import traceback
8
+ from datetime import date
9
+
10
+ import matplotlib
11
+ matplotlib.use('Agg')
12
+
13
+ _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
+ sys.path.insert(0, os.path.join(_REPO, 'ivolatility_backtesting'))
15
+ with contextlib.redirect_stdout(io.StringIO()):
16
+ import ivolatility_backtesting as lib # noqa: E402
17
+
18
+ D = date
19
+ # (open, close) of the underlying per trading day
20
+ PX = {
21
+ 'XSP_2019': {D(2019, 11, 14): (309.08, 309.66), D(2019, 11, 15): (310.79, 312.05), D(2019, 11, 18): (311.79, 312.20),
22
+ D(2019, 11, 21): (310.85, 310.35), D(2019, 11, 22): (311.14, 311.03), D(2019, 11, 25): (311.64, 314.12)},
23
+ 'XSP_2013': {D(2013, 11, 14): (178.28, 179.06), D(2013, 11, 15): (179.07, 179.82), D(2013, 11, 18): (179.88, 179.15)},
24
+ 'XSP_2014GF': {D(2014, 4, 16): (184.60, 186.23), D(2014, 4, 17): (186.17, 186.49), D(2014, 4, 21): (186.58, 187.19)},
25
+ 'XSPAM_2012': {D(2012, 6, 14): (131.49, 132.91), D(2012, 6, 15): (132.92, 134.28), D(2012, 6, 18): (134.24, 134.48)},
26
+ 'XSPAM_2012Q': {D(2012, 6, 28): (133.15, 132.90), D(2012, 6, 29): (133.01, 136.22), D(2012, 7, 2): (136.23, 136.55)},
27
+ 'XSPAM_2013': {D(2013, 11, 14): (178.28, 179.06), D(2013, 11, 15): (179.07, 179.82), D(2013, 11, 18): (179.88, 179.15)},
28
+ 'SPX_2012': {D(2012, 6, 14): (1314.88, 1329.10), D(2012, 6, 15): (1329.19, 1342.84), D(2012, 6, 18): (1342.42, 1344.78)},
29
+ 'SPX_2014GF': {D(2014, 4, 16): (1846.01, 1862.31), D(2014, 4, 17): (1861.73, 1864.85), D(2014, 4, 21): (1865.79, 1871.89)},
30
+ }
31
+
32
+
33
+ def _settle(sym, root, exp, pxk, strike, extra=None, with_days=True):
34
+ """(day the position settled, underlying value used) for a long call held to expiration."""
35
+ px = PX[pxk]
36
+ days = sorted(px)
37
+ cfg = {'strategy_type': 'LONG_CALL', 'debuginfo': 0}
38
+ if with_days:
39
+ cfg['_trading_days'] = list(days)
40
+ pm = lib.PositionManager(cfg, debug=False)
41
+ seen = []
42
+ orig = pm._calculate_intrinsic_value
43
+
44
+ def spy(*a, **k):
45
+ seen.append(float(k.get('underlying_price')))
46
+ return orig(*a, **k)
47
+ pm._calculate_intrinsic_value = spy
48
+ kw = dict(strategy_type='LONG_CALL', expiration=date.fromisoformat(exp), strike=strike, total_cost=100.0,
49
+ contracts=1, underlying_entry_price=px[days[0]][1], opt_type='call', **(extra or {}))
50
+ if root:
51
+ kw['opt_root'] = root
52
+ with contextlib.redirect_stdout(io.StringIO()):
53
+ pm.open_position('P1', sym, days[0], 0, 1, **kw)
54
+ for d in days[1:]:
55
+ o, c = px[d]
56
+ if pm.check_positions(d, {'P1': {'underlying_price': c, 'underlying_open': o}}, c):
57
+ return d, round(seen[-1], 2)
58
+ return None, None
59
+
60
+
61
+ def _check(got, expected):
62
+ assert got[0] == expected[0] and got[1] is not None and abs(got[1] - expected[1]) < 0.02, (got, expected)
63
+
64
+
65
+ def test_s1_xsp_monthly_pm():
66
+ _check(_settle('XSP', None, '2019-11-15', 'XSP_2019', 300), (D(2019, 11, 15), 312.05))
67
+
68
+
69
+ def test_s2_xsp_monthly_explicit_pm():
70
+ _check(_settle('XSP', None, '2019-11-15', 'XSP_2019', 300, {'settlement_style': 'PM'}), (D(2019, 11, 15), 312.05))
71
+
72
+
73
+ def test_s3_xsp_weekly_pm():
74
+ _check(_settle('XSP', None, '2019-11-22', 'XSP_2019', 300), (D(2019, 11, 22), 311.03))
75
+
76
+
77
+ def test_s4_xsp_saturday_monthly_settles_friday_close():
78
+ _check(_settle('XSP', None, '2013-11-16', 'XSP_2013', 170), (D(2013, 11, 15), 179.82))
79
+
80
+
81
+ def test_s4b_saturday_without_trading_days():
82
+ _check(_settle('XSP', None, '2013-11-16', 'XSP_2013', 170, with_days=False), (D(2013, 11, 15), 179.82))
83
+
84
+
85
+ def test_s5_good_friday_settles_thursday():
86
+ _check(_settle('XSP', None, '2014-04-19', 'XSP_2014GF', 180), (D(2014, 4, 17), 186.49))
87
+
88
+
89
+ def test_s6_xspam_saturday_monthly_settles_friday_open():
90
+ _check(_settle('XSPAM', None, '2012-06-16', 'XSPAM_2012', 120), (D(2012, 6, 15), 132.92))
91
+
92
+
93
+ def test_s7_xsppm_quarterly_pm():
94
+ _check(_settle('XSPAM', 'XSPPM', '2012-06-29', 'XSPAM_2012Q', 120), (D(2012, 6, 29), 136.22))
95
+
96
+
97
+ def test_s8_xspam_explicit_pm_settles_friday_close():
98
+ _check(_settle('XSPAM', None, '2012-06-16', 'XSPAM_2012', 120, {'settlement_style': 'PM'}), (D(2012, 6, 15), 134.28))
99
+
100
+
101
+ def test_s9_spx_saturday_monthly_am():
102
+ _check(_settle('SPX', None, '2012-06-16', 'SPX_2012', 1300), (D(2012, 6, 15), 1329.19))
103
+
104
+
105
+ def test_s10_spx_good_friday_am_on_thursday_open():
106
+ _check(_settle('SPX', None, '2014-04-19', 'SPX_2014GF', 1800), (D(2014, 4, 17), 1861.73))
107
+
108
+
109
+ def test_xspam_symbol_with_root_xsp_is_am():
110
+ # contracts listed before the rename carry root XSP under the XSPAM symbol, also past the cutoff date
111
+ _check(_settle('XSPAM', 'XSP', '2013-11-16', 'XSPAM_2013', 170), (D(2013, 11, 15), 179.07))
112
+ _check(_settle('XSPAM', 'XSP', '2012-06-16', 'XSPAM_2012', 120), (D(2012, 6, 15), 132.92))
113
+
114
+
115
+ def test_xsp_symbol_with_root_xsp_is_pm():
116
+ _check(_settle('XSP', 'XSP', '2013-11-16', 'XSP_2013', 170), (D(2013, 11, 15), 179.82))
117
+
118
+
119
+ def test_root_xsp_before_cutoff_is_am():
120
+ assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': D(2012, 6, 16)}) is True
121
+ assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': D(2013, 11, 16)}) is False
122
+ assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': D(2012, 6, 22)}) is False
123
+
124
+
125
+ def test_saturday_monthly_detection():
126
+ for root in ('SPX', 'NDX', 'RUT', 'DJX', 'XSPAM'):
127
+ assert lib._is_am_settled_position({'symbol': root, 'expiration': D(2012, 6, 16)}) is True, root
128
+ assert lib._is_am_settled_position({'symbol': 'SPX', 'expiration': D(2012, 6, 9)}) is False
129
+ assert lib._is_am_settled_position({'symbol': 'SPX', 'expiration': D(2012, 6, 23)}) is False
130
+ assert lib._is_am_settled_position({'symbol': 'AAPL', 'expiration': D(2012, 6, 16)}) is False
131
+
132
+
133
+ def test_settlement_session():
134
+ days = [D(2014, 4, 16), D(2014, 4, 17), D(2014, 4, 21)]
135
+ cfg = {'_trading_days': days}
136
+ assert lib._settlement_session(D(2014, 4, 19), cfg) == D(2014, 4, 17)
137
+ assert lib._settlement_session('2014-04-19', {'_runtime_parent_config': cfg}) == D(2014, 4, 17)
138
+ assert lib._settlement_session(D(2014, 4, 17), cfg) == D(2014, 4, 17)
139
+ assert lib._settlement_session(D(2013, 11, 16), None) == D(2013, 11, 15)
140
+ assert lib._settlement_session(D(2013, 11, 17), None) == D(2013, 11, 15)
141
+ assert lib._settlement_session(D(2014, 5, 16), cfg) == D(2014, 5, 16)
142
+ assert lib._settlement_session(None, cfg) is None
143
+
144
+
145
+ def test_memo_ignores_foreign_object_with_same_id():
146
+ days = [D(2014, 4, 16), D(2014, 4, 17), D(2014, 4, 18)]
147
+ stale = [D(2014, 4, 16), D(2014, 4, 17), D(2014, 4, 21)]
148
+ lib._SETTLE_DAYS_MEMO[id(days)] = (stale, len(days), sorted(stale))
149
+ assert lib._settlement_session(D(2014, 4, 19), {'_trading_days': days}) == D(2014, 4, 18)
150
+
151
+
152
+ def test_intrinsic_guard_applies_on_settlement_day():
153
+ cfg = {'strategy_type': 'LONG_CALL', '_trading_days': sorted(PX['XSP_2013'])}
154
+ pm = lib.PositionManager(cfg, debug=False)
155
+ pos = {'expiration': D(2013, 11, 16), 'strategy_type': 'LONG_CALL', 'strike': 170, 'contracts': 1,
156
+ 'total_cost': 100.0, 'opt_type': 'call', 'entry_price': 1.0}
157
+ dead = {'call_exit_bid': 0, 'call_exit_ask': 0, 'underlying_exit_price': 179.82}
158
+ with contextlib.redirect_stdout(io.StringIO()):
159
+ assert pm._intrinsic_guard_pnl(pos, 'P1', D(2013, 11, 15), dict(dead)) is not None
160
+ assert pm._intrinsic_guard_pnl(pos, 'P1', D(2013, 11, 14), dict(dead)) is None
161
+
162
+
163
+ def test_xsppm_is_cash_settled():
164
+ assert 'XSPPM' in lib._CASH_SETTLED_ROOTS
165
+ assert 'XSPAM' in lib._CASH_SETTLED_ROOTS
166
+
167
+
168
+ if __name__ == '__main__':
169
+ tests = [(n, f) for n, f in sorted(globals().items())
170
+ if n.startswith('test_') and callable(f)]
171
+ failed = []
172
+ for name, fn in tests:
173
+ try:
174
+ fn()
175
+ print(f"PASS {name}")
176
+ except Exception:
177
+ failed.append(name)
178
+ print(f"FAIL {name}")
179
+ traceback.print_exc()
180
+ print(f"\n{len(tests) - len(failed)}/{len(tests)} passed")
181
+ sys.exit(1 if failed else 0)
@@ -0,0 +1,83 @@
1
+ # XSP 3rd-Friday = PM-settled; XSPAM = AM-settled.
2
+ # Run: python3 tests/test_2167_xsp_settlement.py or pytest
3
+ import os
4
+ import sys
5
+ import traceback
6
+ from datetime import date
7
+
8
+ import matplotlib
9
+ matplotlib.use('Agg')
10
+
11
+ _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
12
+ sys.path.insert(0, os.path.join(_REPO, 'ivolatility_backtesting'))
13
+ import ivolatility_backtesting as lib # noqa: E402
14
+
15
+ THIRD_FRIDAY = date(2019, 11, 15)
16
+
17
+
18
+ def test_xsp_third_friday_is_pm():
19
+ assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': THIRD_FRIDAY}) is False
20
+ assert lib._is_am_settled_position({'opt_root': 'XSP', 'symbol': 'XSP', 'expiration': THIRD_FRIDAY}) is False
21
+
22
+
23
+ def test_xspam_third_friday_is_am():
24
+ assert lib._is_am_settled_position({'opt_root': 'XSPAM', 'symbol': 'XSP', 'expiration': THIRD_FRIDAY}) is True
25
+
26
+
27
+ def test_explicit_style_wins():
28
+ assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': THIRD_FRIDAY, 'settlement_style': 'AM'}) is True
29
+ assert lib._is_am_settled_position({'symbol': 'SPX', 'expiration': THIRD_FRIDAY, 'settlement_style': 'PM'}) is False
30
+
31
+
32
+ def test_other_roots_unchanged():
33
+ for root in ('SPX', 'NDX', 'RUT', 'DJX'):
34
+ assert lib._is_am_settled_position({'symbol': root, 'expiration': THIRD_FRIDAY}) is True, root
35
+ assert lib._is_am_settled_position({'opt_root': 'SPXW', 'symbol': 'SPX', 'expiration': THIRD_FRIDAY}) is False
36
+ assert lib._is_am_settled_position({'symbol': 'AAPL', 'expiration': THIRD_FRIDAY}) is False
37
+ assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': date(2019, 11, 8)}) is False
38
+
39
+
40
+ XSP_OPEN, XSP_CLOSE = 310.79, 312.05
41
+
42
+
43
+ def _short_xsp_put(root):
44
+ pm = lib.PositionManager({'strategy_type': 'PUT', 'symbol': 'XSP'}, debug=False)
45
+ pm.open_position(position_id='p1', strategy_type='PUT', symbol='XSP', entry_date=date(2019, 11, 1),
46
+ entry_price=0.0, quantity=100, contracts=1, total_cost=150.0, strike=312.0,
47
+ expiration=THIRD_FRIDAY, underlying_entry_price=306.0, opt_type='put')
48
+ if root:
49
+ pm.positions['p1']['opt_root'] = root
50
+ return pm.check_positions(THIRD_FRIDAY, {'p1': {'underlying_price': XSP_CLOSE, 'underlying_open': XSP_OPEN}})[0]
51
+
52
+
53
+ def test_short_xsp_put_settles_on_the_close():
54
+ si = _short_xsp_put(None)
55
+ assert si['settlement_source'] == 'close', si.get('settlement_source')
56
+ assert abs(si['pnl'] - 150.0) < 1e-6, si['pnl']
57
+
58
+
59
+ def test_short_xspam_put_settles_on_the_open():
60
+ si = _short_xsp_put('XSPAM')
61
+ assert si['settlement_source'] == 'open', si.get('settlement_source')
62
+ assert abs(si['pnl'] - (150.0 - (312.0 - XSP_OPEN) * 100)) < 1e-6, si['pnl']
63
+
64
+
65
+ def test_xsp_stays_cash_settled():
66
+ assert 'XSP' in lib._CASH_SETTLED_ROOTS
67
+ assert 'XSPAM' in lib._CASH_SETTLED_ROOTS
68
+
69
+
70
+ if __name__ == '__main__':
71
+ tests = [(n, f) for n, f in sorted(globals().items())
72
+ if n.startswith('test_') and callable(f)]
73
+ failed = []
74
+ for name, fn in tests:
75
+ try:
76
+ fn()
77
+ print(f"PASS {name}")
78
+ except Exception:
79
+ failed.append(name)
80
+ print(f"FAIL {name}")
81
+ traceback.print_exc()
82
+ print(f"\n{len(tests) - len(failed)}/{len(tests)} passed")
83
+ sys.exit(1 if failed else 0)
@@ -0,0 +1,223 @@
1
+ # Event-day stop reference = the previous session's EOD close quote; without it, the first bar of the day.
2
+ # Run: python3 tests/test_stop_reference_eod_close.py (or pytest). Offline: the API call is replaced.
3
+ import contextlib
4
+ import datetime as dt
5
+ import io
6
+ import os
7
+ import sys
8
+ import tempfile
9
+ import traceback
10
+
11
+ import matplotlib
12
+ matplotlib.use('Agg')
13
+
14
+ os.environ.setdefault('MPLCONFIGDIR', matplotlib.get_configdir())
15
+ os.environ['HOME'] = tempfile.mkdtemp(prefix='ivb_home_')
16
+
17
+ import pandas as pd # noqa: E402
18
+
19
+ _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20
+ sys.path.insert(0, os.path.join(_REPO, 'ivolatility_backtesting'))
21
+ import ivolatility_backtesting as lib # noqa: E402
22
+
23
+ ENTRY = dt.date(2026, 10, 26)
24
+ PREV = dt.date(2026, 10, 28)
25
+ DAY = dt.date(2026, 10, 29)
26
+ EXP = pd.Timestamp('2026-10-30')
27
+ STRIKE = 270.0
28
+ TRADING_DAYS = [pd.Timestamp(d) for d in ('2026-10-26', '2026-10-27', '2026-10-28', '2026-10-29')]
29
+
30
+ CLOSE = {'C': (5.00, 5.10), 'P': (4.00, 4.10)} # EOD close of PREV: long straddle worth (5.00+4.00)x100 = 900
31
+ SNAP_1545 = {'C': (5.40, 5.50), 'P': (3.60, 3.70)} # 15:45 snapshot of PREV: never the reference
32
+ PREOPEN = (2.00, 8.00, 1.50, 7.00) # 09:30 bar: wide pre-open quotes (350)
33
+ DROP_AT_10 = {'09:30': PREOPEN, '09:31': (6.00, 6.10, 3.50, 3.60), '10:00': (3.00, 3.10, 2.30, 2.40),
34
+ '15:45': (5.20, 5.30, 3.80, 3.90)} # 10:00 = 530 = -41.1 % of 900
35
+ CALM = {'09:30': PREOPEN, '09:31': (6.00, 6.10, 3.50, 3.60), '10:00': (4.50, 4.60, 3.80, 3.90),
36
+ '15:45': (5.20, 5.30, 3.80, 3.90)} # worst bar after 09:30 = 830 = -7.8 %
37
+
38
+
39
+ def _bars(quotes):
40
+ out = {}
41
+ for t, (cb, ca, pb, pa) in quotes.items():
42
+ out[f'{DAY} {t}:00'] = [
43
+ {'strike': STRIKE, 'type': 'C', 'expiration': '2026-10-30', 'bid': cb, 'ask': ca,
44
+ 'price': (cb + ca) / 2, 'underlying_price': 271.0},
45
+ {'strike': STRIKE, 'type': 'P', 'expiration': '2026-10-30', 'bid': pb, 'ask': pa,
46
+ 'price': (pb + pa) / 2, 'underlying_price': 271.0},
47
+ ]
48
+ return out
49
+
50
+
51
+ def _api(calls, quotes=CLOSE, fail=False):
52
+ """Stand-in for lib.api_call: the API's raw stock-opts-by-param rows for one side."""
53
+ def api_call(endpoint, cache_config=None, debug=False, max_retries=3, skip_parquet_cache=False,
54
+ _chunk_info=None, **kw):
55
+ calls.append((endpoint, dict(kw)))
56
+ if fail:
57
+ return None
58
+ rows = []
59
+ for cp, (bid, ask) in (quotes or {}).items():
60
+ if cp != kw.get('cp'):
61
+ continue
62
+ rows.append({'c_date': kw['tradeDate'], 'option_symbol': f'AAPL 261030{cp}00270000',
63
+ 'dte': kw['dteFrom'], 'expiration_date': '2026-10-30', 'call_put': cp,
64
+ 'price_strike': STRIKE, 'Bid': bid, 'Ask': ask, 'price': (bid + ask) / 2,
65
+ 'underlying_price': 271.0, 'delta': 0.5 if cp == 'C' else -0.5, 'iv': 0.3})
66
+ return {'data': rows, 'status': 'success'}
67
+ return api_call
68
+
69
+
70
+ def _chain(quotes, day):
71
+ rows = []
72
+ for cp, (bid, ask) in quotes.items():
73
+ rows.append({'date': pd.Timestamp(day), 'expiration': EXP, 'strike': STRIKE, 'type': cp, 'bid': bid,
74
+ 'ask': ask, 'price': (bid + ask) / 2, 'delta': 0.5 if cp == 'C' else -0.5, 'iv': 0.3,
75
+ 'dte': (EXP.date() - day).days, 'underlying_price': 271.0})
76
+ return pd.DataFrame(rows)
77
+
78
+
79
+ @contextlib.contextmanager
80
+ def _patched(api_call):
81
+ saved = (lib.api_call, lib.get_options_for_date)
82
+ lib._PREV_CLOSE_QUOTES.clear()
83
+ lib._PREV_CLOSE_FALLBACK_WARNED.clear()
84
+ lib.api_call = api_call
85
+ # The loader's chain of PREV is the 15:45 snapshot (eod_patch_1545 default)
86
+ lib.get_options_for_date = lambda config, date, *a, **k: _chain(SNAP_1545, PREV)
87
+ try:
88
+ yield
89
+ finally:
90
+ lib.api_call, lib.get_options_for_date = saved
91
+ lib._PREV_CLOSE_QUOTES.clear()
92
+ lib._PREV_CLOSE_FALLBACK_WARNED.clear()
93
+
94
+
95
+ def _pm():
96
+ sl = {'type': 'pl_loss', 'min_days_before_check': 0, 'pl_loss_settings': {'pl_loss': 0.40},
97
+ 'reset_baseline_on_sl_start': True,
98
+ 'intraday_settings': {'intraday_mode': 'auto', 'minute_interval': 'MINUTE_1',
99
+ 'reset_baseline_on_sl_start': True}}
100
+ return lib.PositionManager({'symbol': 'AAPL', 'debuginfo': 0, 'strategy_type': 'STRADDLE',
101
+ 'stop_loss_enabled': True, 'stop_loss_config': sl, 'eod_patch_1545': True,
102
+ 'options_snapshot_mode': '1545', '_trading_days': TRADING_DAYS}, debug=False)
103
+
104
+
105
+ def _open(pm, pid='S1', entry=ENTRY):
106
+ pm.open_position(position_id=pid, symbol='AAPL', entry_date=entry, quantity=100, strategy_type='STRADDLE',
107
+ contracts=1, strike=STRIKE, expiration=EXP, underlying_entry_price=270.0,
108
+ entry_price=1000.0, total_cost=1000.0, call_entry_bid=5.0, put_entry_bid=5.0,
109
+ reset_baseline_on_sl_start=True)
110
+
111
+
112
+ def _check(pm, quotes):
113
+ pm.sl_manager._get_legs_intraday_data = lambda *a, **k: (_bars(quotes), sorted(_bars(quotes)))
114
+ chain = _chain({'C': quotes['15:45'][:2], 'P': quotes['15:45'][2:]}, DAY)
115
+ pdx = pm.build_price_data(DAY, 271.0, chain, lambda s, e, t: lib.get_option_by_strike_exp(chain, s, e, t),
116
+ stock_row=pd.DataFrame([{'date': pd.Timestamp(DAY), 'close': 271.0, 'open': 271.0,
117
+ 'high': 271.0, 'low': 271.0}]))
118
+ return pm.check_positions(DAY, pdx, underlying_price=271.0)
119
+
120
+
121
+ def test_reference_is_previous_eod_close_from_a_close_request():
122
+ calls = []
123
+ with _patched(_api(calls)):
124
+ pm = _pm()
125
+ _open(pm)
126
+ hits = _check(pm, DROP_AT_10)
127
+ sl_pos = pm.sl_manager.positions['S1']
128
+ assert [c[0] for c in calls] == ['/equities/eod/stock-opts-by-param'] * 2, calls
129
+ assert sorted(c[1]['cp'] for c in calls) == ['C', 'P'], calls
130
+ for _, kw in calls:
131
+ assert kw['tradeDate'] == '2026-10-28' and kw['dteFrom'] == kw['dteTo'] == 2, kw
132
+ assert sl_pos['prev_day_close_source'] == 'eod_close' and sl_pos['prev_day_close_time'] == '2026-10-28', sl_pos
133
+ assert (sl_pos['prev_day_close_call_bid'], sl_pos['prev_day_close_call_ask']) == CLOSE['C'], sl_pos
134
+ assert (sl_pos['prev_day_close_put_bid'], sl_pos['prev_day_close_put_ask']) == CLOSE['P'], sl_pos
135
+ assert round(sl_pos['sl_baseline_value'], 2) == 900.0, sl_pos['sl_baseline_value']
136
+ assert len(hits) == 1 and hits[0]['options_stop_trigger_time'] == f'{DAY} 10:00:00', hits
137
+ assert round(hits[0]['options_stop_trigger_pnl'], 1) == -41.1, hits[0]
138
+
139
+
140
+ def test_1545_snapshot_is_never_the_reference():
141
+ calls = []
142
+ with _patched(_api(calls)):
143
+ pm = _pm()
144
+ _open(pm)
145
+ _check(pm, CALM)
146
+ assert calls and all('1545' not in endpoint for endpoint, _ in calls), calls
147
+ sl_pos = pm.sl_manager.positions['S1']
148
+ assert sl_pos['prev_day_close_call_bid'] == CLOSE['C'][0] != SNAP_1545['C'][0], sl_pos
149
+ assert round(sl_pos['sl_baseline_value'], 2) == 900.0, sl_pos['sl_baseline_value']
150
+
151
+
152
+ def test_preopen_0930_bar_is_not_scanned():
153
+ with _patched(_api([])):
154
+ pm = _pm()
155
+ _open(pm)
156
+ hits = _check(pm, CALM)
157
+ assert hits == [], ('09:30 pre-open quote is -61 % of the close but not a tradable bar', hits)
158
+
159
+
160
+ def test_missing_close_quote_falls_back_to_the_first_bar_and_warns_once():
161
+ calls = []
162
+ out = io.StringIO()
163
+ with _patched(_api(calls, quotes={'C': CLOSE['C']})), contextlib.redirect_stdout(out):
164
+ pm = _pm()
165
+ _open(pm, 'S1')
166
+ _open(pm, 'S2')
167
+ hits = _check(pm, DROP_AT_10)
168
+ for pid in ('S1', 'S2'):
169
+ sl_pos = pm.sl_manager.positions[pid]
170
+ assert sl_pos['prev_day_close_source'] == 'first_bar', sl_pos
171
+ assert sl_pos['prev_day_close_time'] == f'{DAY} 09:30:00', sl_pos
172
+ assert round(sl_pos['sl_baseline_value'], 2) == 350.0, sl_pos['sl_baseline_value']
173
+ assert hits == [], ('every bar is measured from the 09:30 bar (350)', hits)
174
+ warned = [line for line in out.getvalue().splitlines() if '[SL REFERENCE]' in line]
175
+ assert len(warned) == 1 and 'no EOD close quote' in warned[0], out.getvalue()
176
+ assert len(calls) == 2, ('C and P requested once, the second position reuses them', calls)
177
+
178
+
179
+ def test_failed_request_falls_back_and_is_retried_later():
180
+ calls = []
181
+ with _patched(_api(calls, fail=True)), contextlib.redirect_stdout(io.StringIO()):
182
+ pm = _pm()
183
+ _open(pm, 'S1')
184
+ _open(pm, 'S2')
185
+ _check(pm, CALM)
186
+ assert len(calls) == 2, ('a failed request is not cached: one attempt per position', calls)
187
+ assert pm.sl_manager.positions['S1']['prev_day_close_source'] == 'first_bar'
188
+
189
+
190
+ def test_position_opened_on_the_check_day_keeps_the_first_bar():
191
+ calls = []
192
+ with _patched(_api(calls)):
193
+ pm = _pm()
194
+ _open(pm, entry=DAY)
195
+ _check(pm, CALM)
196
+ assert calls == [], calls
197
+ assert pm.sl_manager.positions['S1']['prev_day_close_source'] == 'first_bar'
198
+
199
+
200
+ def test_previous_session_comes_from_trading_days():
201
+ mgr = lib.StopLossManager(config={'_trading_days': [pd.Timestamp('2026-11-25'), pd.Timestamp('2026-11-27')]})
202
+ assert mgr._previous_session(dt.date(2026, 11, 27)) == dt.date(2026, 11, 25)
203
+ assert lib.StopLossManager(config={})._previous_session(dt.date(2026, 11, 2)) == dt.date(2026, 10, 30)
204
+
205
+
206
+ def test_after_open_bar():
207
+ times = [f'{DAY} 09:30:00', f'{DAY} 09:31:00', f'{DAY} 16:10:00']
208
+ assert lib._after_open_bar(times) == times[1:]
209
+ assert lib._after_open_bar(None) == []
210
+
211
+
212
+ if __name__ == '__main__':
213
+ failed = 0
214
+ for name, fn in list(globals().items()):
215
+ if name.startswith('test_') and callable(fn):
216
+ try:
217
+ fn()
218
+ print(f'PASS {name}')
219
+ except Exception:
220
+ failed += 1
221
+ print(f'FAIL {name}')
222
+ traceback.print_exc()
223
+ sys.exit(1 if failed else 0)