ivolatility-backtesting 2.165__tar.gz → 2.166__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 (46) hide show
  1. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/PKG-INFO +1 -1
  2. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/ivolatility_backtesting/ivolatility_backtesting.py +152 -19
  3. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/ivolatility_backtesting.egg-info/PKG-INFO +1 -1
  4. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/ivolatility_backtesting.egg-info/SOURCES.txt +1 -0
  5. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/pyproject.toml +1 -1
  6. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2150_prompt_patterns.py +2 -0
  7. ivolatility_backtesting-2.166/tests/test_stop_reference_eod_close.py +223 -0
  8. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/README.md +0 -0
  9. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/ivolatility_backtesting/__init__.py +0 -0
  10. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/ivolatility_backtesting.egg-info/dependency_links.txt +0 -0
  11. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/ivolatility_backtesting.egg-info/requires.txt +0 -0
  12. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/ivolatility_backtesting.egg-info/top_level.txt +0 -0
  13. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/setup.cfg +0 -0
  14. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2142_fixes.py +0 -0
  15. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2144_duckdb_dedup.py +0 -0
  16. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2146_vix_vro.py +0 -0
  17. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2147_cents_multiplier.py +0 -0
  18. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2148_loader_memory.py +0 -0
  19. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2149_client_errors.py +0 -0
  20. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2152_cache_lock_and_rate_limit.py +0 -0
  21. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2153_cache_lock_kept.py +0 -0
  22. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2154_put_atm_legs.py +0 -0
  23. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2155_bar_prefetch.py +0 -0
  24. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2155_intraday_exits.py +0 -0
  25. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2155_ivx_stock_holes.py +0 -0
  26. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2155_key_redaction.py +0 -0
  27. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2155_long_expiry.py +0 -0
  28. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2155_opt_stop_merge.py +0 -0
  29. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2156_phantom_quotes.py +0 -0
  30. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2157_sl_symbol.py +0 -0
  31. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2158_default_path_golden.py +0 -0
  32. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2158_entry_time.py +0 -0
  33. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2159_entry_rule.py +0 -0
  34. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2160_day_price_order.py +0 -0
  35. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2160_exit_rule.py +0 -0
  36. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2160_option_lean_rule.py +0 -0
  37. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2160_prefetch_cancel.py +0 -0
  38. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2161_assignment.py +0 -0
  39. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2162_entry_minute_window.py +0 -0
  40. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2163_rotation.py +0 -0
  41. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2164_stock_price_stops.py +0 -0
  42. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2165_parquet_engine_error.py +0 -0
  43. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_2165_renamed_symbol.py +0 -0
  44. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_price_ta_indicators.py +0 -0
  45. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/tests/test_stock_loader_coverage.py +0 -0
  46. {ivolatility_backtesting-2.165 → ivolatility_backtesting-2.166}/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.166
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
@@ -1911,7 +1911,7 @@ _INDEX_OPTION_ROOTS_1615 = {'SPX', 'SPXW', 'NDX', 'NDXP', 'RUT', 'RUTW', 'DJX',
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.
@@ -14368,7 +14501,7 @@ class PositionManager:
14368
14501
  # Copy prev_day_close fields from SL manager's position to PositionManager's position
14369
14502
  # (SL manager stores these during baseline reset, but we need them in the exported trade)
14370
14503
  sl_pos = self.sl_manager.positions.get(position_id, {})
14371
- for key in ['prev_day_close_time', 'prev_day_close_underlying',
14504
+ for key in ['prev_day_close_time', 'prev_day_close_source', 'prev_day_close_underlying',
14372
14505
  'prev_day_close_call_bid', 'prev_day_close_call_ask',
14373
14506
  'prev_day_close_put_bid', 'prev_day_close_put_ask']:
14374
14507
  if key in sl_pos:
@@ -14514,7 +14647,7 @@ class PositionManager:
14514
14647
  is_credit = StrategyRegistry.is_credit_strategy(
14515
14648
  strategy_type=strategy_type, position=position
14516
14649
  )
14517
- # entry_value may be the reset 09:30 baseline; the trade is booked against its cost
14650
+ # entry_value may be the reset stop baseline; the trade is booked against its cost
14518
14651
  _orig_cost = abs(position.get('total_cost') or entry_value)
14519
14652
  if is_credit:
14520
14653
  intraday_pnl = _orig_cost + current_value
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ivolatility_backtesting
3
- Version: 2.165
3
+ Version: 2.166
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
@@ -41,4 +41,5 @@ tests/test_2165_parquet_engine_error.py
41
41
  tests/test_2165_renamed_symbol.py
42
42
  tests/test_price_ta_indicators.py
43
43
  tests/test_stock_loader_coverage.py
44
+ tests/test_stop_reference_eod_close.py
44
45
  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.166"
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,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)