ivolatility-backtesting 2.167__tar.gz → 2.168__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 (49) hide show
  1. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/PKG-INFO +1 -1
  2. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/ivolatility_backtesting/ivolatility_backtesting.py +141 -12
  3. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/PKG-INFO +1 -1
  4. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/SOURCES.txt +1 -0
  5. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/pyproject.toml +1 -1
  6. ivolatility_backtesting-2.168/tests/test_2168_reverse_split.py +252 -0
  7. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/README.md +0 -0
  8. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/ivolatility_backtesting/__init__.py +0 -0
  9. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/dependency_links.txt +0 -0
  10. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/requires.txt +0 -0
  11. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/top_level.txt +0 -0
  12. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/setup.cfg +0 -0
  13. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2142_fixes.py +0 -0
  14. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2144_duckdb_dedup.py +0 -0
  15. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2146_vix_vro.py +0 -0
  16. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2147_cents_multiplier.py +0 -0
  17. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2148_loader_memory.py +0 -0
  18. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2149_client_errors.py +0 -0
  19. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2150_prompt_patterns.py +0 -0
  20. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2152_cache_lock_and_rate_limit.py +0 -0
  21. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2153_cache_lock_kept.py +0 -0
  22. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2154_put_atm_legs.py +0 -0
  23. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2155_bar_prefetch.py +0 -0
  24. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2155_intraday_exits.py +0 -0
  25. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2155_ivx_stock_holes.py +0 -0
  26. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2155_key_redaction.py +0 -0
  27. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2155_long_expiry.py +0 -0
  28. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2155_opt_stop_merge.py +0 -0
  29. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2156_phantom_quotes.py +0 -0
  30. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2157_sl_symbol.py +0 -0
  31. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2158_default_path_golden.py +0 -0
  32. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2158_entry_time.py +0 -0
  33. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2159_entry_rule.py +0 -0
  34. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2160_day_price_order.py +0 -0
  35. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2160_exit_rule.py +0 -0
  36. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2160_option_lean_rule.py +0 -0
  37. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2160_prefetch_cancel.py +0 -0
  38. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2161_assignment.py +0 -0
  39. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2162_entry_minute_window.py +0 -0
  40. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2163_rotation.py +0 -0
  41. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2164_stock_price_stops.py +0 -0
  42. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2165_parquet_engine_error.py +0 -0
  43. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2165_renamed_symbol.py +0 -0
  44. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2167_saturday_expiration.py +0 -0
  45. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_2167_xsp_settlement.py +0 -0
  46. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_price_ta_indicators.py +0 -0
  47. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_stock_loader_coverage.py +0 -0
  48. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/tests/test_stop_reference_eod_close.py +0 -0
  49. {ivolatility_backtesting-2.167 → ivolatility_backtesting-2.168}/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.167
3
+ Version: 2.168
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
@@ -13049,6 +13049,32 @@ def _assignment_shares(legs, settlement_price, unit_multiplier, contracts):
13049
13049
  return shares, cash
13050
13050
 
13051
13051
 
13052
+ # split_factor = unadjusted/adjusted close; float32 storage noise stays far below this
13053
+ _SPLIT_RATIO_TOLERANCE = 0.02
13054
+
13055
+
13056
+ def _reverse_split_ratio(entry_split_factor, split_factor):
13057
+ """Reverse-split ratio since entry (5.0 for 1:5): the contract then delivers 100/ratio shares.
13058
+ 1.0 when either factor is unknown, unchanged or the split was forward (forward splits keep their path)."""
13059
+ try:
13060
+ entry_sf = float(entry_split_factor)
13061
+ sf = float(split_factor)
13062
+ except (TypeError, ValueError):
13063
+ return 1.0
13064
+ if not (entry_sf > 0 and sf > 0):
13065
+ return 1.0
13066
+ ratio = sf / entry_sf
13067
+ return ratio if ratio > 1.0 + _SPLIT_RATIO_TOLERANCE else 1.0
13068
+
13069
+
13070
+ def _split_intrinsic(opt_type, strike, underlying_price, ratio=1.0):
13071
+ """Per-share intrinsic of a contract opened before a reverse split:
13072
+ max(0, S*(100/ratio) - K*100)/100 for calls, mirrored for puts."""
13073
+ s = float(underlying_price) / float(ratio or 1.0)
13074
+ k = float(strike)
13075
+ return max(0.0, s - k) if str(opt_type).strip().upper().startswith('C') else max(0.0, k - s)
13076
+
13077
+
13052
13078
  _STOCK_BAR_OPEN_COLUMNS = ('runtime_open', 'open')
13053
13079
  _STOCK_BAR_CLOSE_COLUMNS = ('runtime_close', 'price', 'unadjusted_close', 'close')
13054
13080
 
@@ -13142,6 +13168,9 @@ class PositionManager:
13142
13168
  self._stock_bars = None
13143
13169
  self._stock_bar_keys = None
13144
13170
  self._assignment_warned = set()
13171
+ self._split_factors = None
13172
+ self._split_factors_src = None
13173
+ self._split_factors_multi = False
13145
13174
 
13146
13175
  # Stop-loss enable logic:
13147
13176
  # 1) Respect explicit flag if provided (stop_loss_enabled)
@@ -13304,7 +13333,7 @@ class PositionManager:
13304
13333
  px = underlying_arg
13305
13334
  if not px or float(px) <= 0:
13306
13335
  return False
13307
- px = float(px)
13336
+ px = float(px) / self._position_split_ratio(position, today)
13308
13337
  threshold = float(self.config.get('assignment_early_itm_pct', 0.05))
13309
13338
  for t, k, q in legs:
13310
13339
  if q >= 0:
@@ -13767,6 +13796,10 @@ class PositionManager:
13767
13796
  # If caller already passed 'unit_multiplier' via kwargs, respect it.
13768
13797
  if 'unit_multiplier' not in position:
13769
13798
  position['unit_multiplier'] = get_position_multiplier(self.config)
13799
+ if position.get('entry_split_factor') is None and position.get('strategy_type') not in STOCK_STRATEGY_TYPES:
13800
+ _entry_sf = self._split_factor_on(entry_date, symbol=symbol)
13801
+ if _entry_sf is not None:
13802
+ position['entry_split_factor'] = _entry_sf
13770
13803
 
13771
13804
  if self.sl_enabled and self.sl_manager:
13772
13805
  sl_type = self.sl_config.get('type', 'fixed_pct')
@@ -13905,6 +13938,74 @@ class PositionManager:
13905
13938
  return None, None
13906
13939
  return row, _resolve_runtime_underlying_price(stock_row=row)
13907
13940
 
13941
+ def _split_factor_on(self, day, stock_row=None, symbol=None):
13942
+ """Stock split_factor (unadjusted/adjusted close) on day: stock_row first, then the preloaded stock frame."""
13943
+ sf = _first_valid_numeric_value(stock_row, ('split_factor',)) if stock_row is not None else None
13944
+ if sf is not None and sf > 0:
13945
+ return sf
13946
+ day = _as_date_obj(day)
13947
+ stock_df = self.config.get('_preloaded_stock')
13948
+ if day is None or not isinstance(stock_df, pd.DataFrame) or stock_df.empty \
13949
+ or 'date' not in stock_df.columns or 'split_factor' not in stock_df.columns:
13950
+ return None
13951
+ if self._split_factors_src is not stock_df:
13952
+ dates = pd.to_datetime(stock_df['date'], errors='coerce').dt.date
13953
+ factors = pd.to_numeric(stock_df['split_factor'], errors='coerce')
13954
+ # a multi-symbol frame (rotation) is keyed by symbol too
13955
+ multi = 'symbol' in stock_df.columns and stock_df['symbol'].nunique() > 1
13956
+ syms = stock_df['symbol'].astype(str).str.upper() if multi else [None] * len(stock_df)
13957
+ self._split_factors = {(s, d): float(f) for s, d, f in zip(syms, dates, factors)
13958
+ if d is not None and pd.notna(f) and f > 0}
13959
+ self._split_factors_multi = multi
13960
+ self._split_factors_src = stock_df
13961
+ key_sym = str(symbol).upper() if self._split_factors_multi and symbol else None
13962
+ return self._split_factors.get((key_sym, day))
13963
+
13964
+ def _position_split_ratio(self, position, day, stock_row=None):
13965
+ """Reverse-split ratio of the position's contracts on day (1.0 = deliverable unchanged)."""
13966
+ entry_sf = position.get('entry_split_factor')
13967
+ if entry_sf is None or position.get('strategy_type') in STOCK_STRATEGY_TYPES:
13968
+ return 1.0
13969
+ ratio = _reverse_split_ratio(entry_sf, self._split_factor_on(day, stock_row, position.get('symbol')))
13970
+ if ratio != 1.0:
13971
+ position['split_adjusted'] = True
13972
+ position['split_ratio'] = ratio
13973
+ return ratio
13974
+
13975
+ def _split_intrinsic_leg_data(self, position, underlying_price, ratio):
13976
+ """Leg quotes of a position past a reverse split, valued at intrinsic on the 100/ratio-share deliverable.
13977
+ The chain has no adjusted contracts: the old strike is gone or names a new 100-share contract."""
13978
+ strategy_type = position.get('strategy_type', 'UNKNOWN')
13979
+ strategy = StrategyRegistry.get(strategy_type)
13980
+ if not strategy or not strategy.get('legs') or underlying_price is None:
13981
+ return None
13982
+ leg_data = {}
13983
+ for leg in strategy['legs']:
13984
+ leg_name = leg['name']
13985
+ prefix = leg.get('field_prefix', leg_name)
13986
+ strike = position.get(f"{prefix}_strike", position.get('strike'))
13987
+ if strike is None:
13988
+ return None
13989
+ if 'call' in leg_name.lower():
13990
+ opt_type = 'C'
13991
+ elif 'put' in leg_name.lower():
13992
+ opt_type = 'P'
13993
+ elif 'PUT' in strategy_type:
13994
+ opt_type = 'P'
13995
+ elif 'CALL' in strategy_type:
13996
+ opt_type = 'C'
13997
+ else:
13998
+ return None
13999
+ value = _split_intrinsic(opt_type, strike, underlying_price, ratio)
14000
+ exp_key = leg.get('expiration_key')
14001
+ leg_data[prefix] = {
14002
+ 'bid': value, 'ask': value, 'mid': value, 'price': value, 'last': value,
14003
+ 'strike': float(strike), 'type': opt_type,
14004
+ 'expiration': position.get(exp_key, position.get('expiration')) if exp_key else position.get('expiration'),
14005
+ '_split_intrinsic': True,
14006
+ }
14007
+ return leg_data
14008
+
13908
14009
  def _post_entry_underlying_range(self, position, entry_date, close_price):
13909
14010
  """Underlying high/low after the entry bar; without bars, the entry and close prices, never the whole day."""
13910
14011
  if not self.sl_enabled or self.sl_manager is None or (self.sl_config or {}).get('type') not in ('directional', 'combined'):
@@ -14253,15 +14354,17 @@ class PositionManager:
14253
14354
  contracts = position.get('contracts', 1)
14254
14355
  entry_premium = abs(position.get('total_cost', 0))
14255
14356
 
14357
+ split_ratio = self._position_split_ratio(position, current_date_normalized)
14256
14358
  if underlying_price and underlying_price > 0:
14257
14359
  # ============================================================
14258
14360
  # PRIMARY PATH — Intrinsic settlement (canonical for expiration)
14259
14361
  # ============================================================
14362
+ # Past a reverse split the contract delivers 100/ratio shares: S/ratio against the old strikes
14260
14363
  intrinsic_value = self._calculate_intrinsic_value(
14261
14364
  position=position,
14262
14365
  position_id=position_id,
14263
14366
  strategy_type=strategy_type,
14264
- underlying_price=underlying_price,
14367
+ underlying_price=underlying_price / split_ratio,
14265
14368
  strike=strike,
14266
14369
  contracts=contracts
14267
14370
  )
@@ -14290,7 +14393,9 @@ class PositionManager:
14290
14393
  if early_assignment:
14291
14394
  assignment_info = {'early_assignment': True}
14292
14395
  if _legs:
14293
- _shares, _cash_at_strikes = _assignment_shares(_legs, underlying_price, _um, contracts)
14396
+ _shares, _cash_at_strikes = _assignment_shares(_legs, underlying_price / split_ratio,
14397
+ _um, contracts)
14398
+ _shares = _shares / split_ratio
14294
14399
  _when = 'early' if early_assignment else 'at expiration'
14295
14400
  if _shares:
14296
14401
  self._ensure_stock_bars()
@@ -14403,6 +14508,8 @@ class PositionManager:
14403
14508
  'settlement_price': underlying_price if used_intrinsic else None,
14404
14509
  **(assignment_info if used_intrinsic else {}),
14405
14510
  }
14511
+ if split_ratio != 1.0:
14512
+ stop_info.update({'split_adjusted': True, 'split_ratio': split_ratio})
14406
14513
 
14407
14514
  to_close.append(stop_info)
14408
14515
 
@@ -14456,6 +14563,11 @@ class PositionManager:
14456
14563
  if self.debug:
14457
14564
  print(f" [check_positions] ⏭️ {position_id}: skipping SL — price_data from fallback cache (stale leg)")
14458
14565
  continue
14566
+ # Intrinsic marks past a reverse split carry no time value of the adjusted contract
14567
+ if isinstance(price_data[position_id], dict) and price_data[position_id].get('split_adjusted'):
14568
+ if self.debug:
14569
+ print(f" [check_positions] ⏭️ {position_id}: skipping SL — reverse split, intrinsic marks")
14570
+ continue
14459
14571
 
14460
14572
  if isinstance(price_data[position_id], dict):
14461
14573
  data = price_data[position_id]
@@ -15010,11 +15122,18 @@ class PositionManager:
15010
15122
  for position in (self.get_open_positions() if positions is None else positions):
15011
15123
  pos_id = position['id']
15012
15124
 
15013
- # Get leg data from current market prices
15014
- leg_data = StrategyRegistry.get_leg_data_for_position(
15015
- position, options_df, get_option_func
15016
- )
15017
-
15125
+ split_ratio = self._position_split_ratio(position, current_date, stock_row)
15126
+ if split_ratio != 1.0:
15127
+ leg_data = self._split_intrinsic_leg_data(position, resolved_stock_price, split_ratio)
15128
+ if self.debug:
15129
+ print(f" [build_price_data] {pos_id}: reverse split 1:{split_ratio:g} — "
15130
+ f"legs at intrinsic on {100 / split_ratio:g} shares")
15131
+ else:
15132
+ # Get leg data from current market prices
15133
+ leg_data = StrategyRegistry.get_leg_data_for_position(
15134
+ position, options_df, get_option_func
15135
+ )
15136
+
15018
15137
  # ================================================================
15019
15138
  # FALLBACK: Per-leg price cache for diagonal/calendar spreads
15020
15139
  # ================================================================
@@ -15024,7 +15143,7 @@ class PositionManager:
15024
15143
  # This fixes SL=0 for DPS/DCS/calendar strategies without requiring
15025
15144
  # manual price_data injection in every notebook.
15026
15145
  _used_fallback = False
15027
- if leg_data is None:
15146
+ if leg_data is None and split_ratio == 1.0:
15028
15147
  fallback = self._build_fallback_leg_data(position, options_df, get_option_func)
15029
15148
  if fallback is not None:
15030
15149
  leg_data = fallback
@@ -15058,7 +15177,7 @@ class PositionManager:
15058
15177
 
15059
15178
  if leg_data is not None:
15060
15179
  # Cache per-leg prices ONLY from fresh market data (not from fallback itself)
15061
- if not _used_fallback and leg_data:
15180
+ if not _used_fallback and leg_data and split_ratio == 1.0:
15062
15181
  self._leg_price_cache[pos_id] = {k: dict(v) if hasattr(v, 'items') else v for k, v in leg_data.items()}
15063
15182
 
15064
15183
  # Auto-generate price_data (framework calculates P&L automatically!)
@@ -15074,6 +15193,8 @@ class PositionManager:
15074
15193
  # (cached leg prices from a previous day produce stale P&L → spurious SL triggers)
15075
15194
  if _used_fallback:
15076
15195
  price_data[pos_id]['_from_fallback_cache'] = True
15196
+ if split_ratio != 1.0:
15197
+ price_data[pos_id].update({'split_adjusted': True, 'split_ratio': split_ratio})
15077
15198
 
15078
15199
  # Add ALL indicators with 'exit_' prefix (universal for any strategy)
15079
15200
  if indicators:
@@ -15294,6 +15415,11 @@ class PositionManager:
15294
15415
  print(f"[PT] SKIP {position_id}: at/after expiration {_pt_exp} — settled by expiration path")
15295
15416
  continue
15296
15417
  _eod_counts = False
15418
+ # Past a reverse split the chain has no quotes of the adjusted contract
15419
+ if self._position_split_ratio(position, _pt_now, stock_row) != 1.0:
15420
+ if self.debuginfo >= 2:
15421
+ print(f"[PT] SKIP {position_id}: reverse split, no quotes of the adjusted contract")
15422
+ continue
15297
15423
  # ========================================================
15298
15424
  # Check min_days_before_check for profit target (trading days)
15299
15425
  # ========================================================
@@ -15468,7 +15594,7 @@ class PositionManager:
15468
15594
  position=position,
15469
15595
  position_id=position_id,
15470
15596
  strategy_type=strategy_type,
15471
- underlying_price=underlying_price,
15597
+ underlying_price=underlying_price / self._position_split_ratio(position, exit_d),
15472
15598
  strike=position.get('strike', 0),
15473
15599
  contracts=contracts,
15474
15600
  )
@@ -15732,7 +15858,10 @@ class PositionManager:
15732
15858
  trade['stop_level_high'] = underlying_entry * (1 + threshold)
15733
15859
  trade['stop_level_low'] = underlying_entry * (1 - threshold)
15734
15860
  trade['stop_threshold'] = threshold * 100
15735
-
15861
+ if position.get('split_adjusted'):
15862
+ trade.setdefault('split_adjusted', True)
15863
+ trade.setdefault('split_ratio', position.get('split_ratio'))
15864
+
15736
15865
  self.closed_trades.append(trade)
15737
15866
 
15738
15867
  if self.sl_enabled and self.sl_manager:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ivolatility_backtesting
3
- Version: 2.167
3
+ Version: 2.168
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,6 +41,7 @@ tests/test_2165_parquet_engine_error.py
41
41
  tests/test_2165_renamed_symbol.py
42
42
  tests/test_2167_saturday_expiration.py
43
43
  tests/test_2167_xsp_settlement.py
44
+ tests/test_2168_reverse_split.py
44
45
  tests/test_price_ta_indicators.py
45
46
  tests/test_stock_loader_coverage.py
46
47
  tests/test_stop_reference_eod_close.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ivolatility_backtesting"
7
- version = "2.167"
7
+ version = "2.168"
8
8
  description = "A universal backtesting framework for financial strategies using the IVolatility API."
9
9
  readme = "README.md"
10
10
  authors = [
@@ -0,0 +1,252 @@
1
+ """Positions held through a reverse stock split: the old contract delivers 100/ratio shares.
2
+ Run: pytest tests/test_2168_reverse_split.py. The live UVXY test needs network and an API key
3
+ (IVOL_API_KEY or the macOS keychain item ivolatility/restapi) and is skipped otherwise.
4
+ IVB_LIB_DIR overrides the library folder."""
5
+ import os
6
+ import subprocess
7
+ import sys
8
+
9
+ import pandas as pd
10
+ import pytest
11
+
12
+ _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
+ sys.path.insert(0, os.environ.get('IVB_LIB_DIR') or os.path.join(_REPO, 'ivolatility_backtesting'))
14
+ import ivolatility_backtesting as lib # noqa: E402
15
+
16
+ PositionManager = lib.PositionManager
17
+
18
+ ENTRY = '2024-04-10'
19
+ EXP = '2024-05-17'
20
+ UVXY_STOCK = pd.DataFrame({
21
+ 'date': pd.to_datetime([ENTRY, '2024-04-11', '2024-04-12', '2024-05-16', EXP, '2024-05-20']),
22
+ 'close': [6.89, 33.58, 37.85, 25.50, 25.35, 26.00],
23
+ 'split_factor': [6.89 / 172.25, 33.58 / 167.90, 37.85 / 189.25, 0.2, 0.2, 0.2],
24
+ })
25
+ UVXY_BARS = {'2024-05-17': {'open': 25.0, 'close': 25.35}, '2024-05-20': {'open': 26.0, 'close': 26.0}}
26
+ NVDA_STOCK = pd.DataFrame({'date': pd.to_datetime(['2024-06-03', '2024-06-10', '2024-06-21']),
27
+ 'close': [1150.0, 121.8, 126.6], 'split_factor': [10.0, 1.0, 1.0]})
28
+
29
+
30
+ def _pm(stock=UVXY_STOCK, **extra):
31
+ config = {'symbol': 'UVXY', 'initial_capital': 100000, 'stop_loss_enabled': False,
32
+ 'profit_target_enabled': False, '_preloaded_stock': stock}
33
+ config.update(extra)
34
+ return PositionManager(config, debug=False)
35
+
36
+
37
+ def _open(pm, strategy, pid, strike=7.0, cost=50.0, entry=ENTRY, exp=EXP, entry_px=6.89):
38
+ credit = strategy.startswith('SHORT')
39
+ pm.open_position(position_id=pid, strategy_type=strategy, symbol='UVXY', entry_date=pd.Timestamp(entry),
40
+ entry_price=0.0 if credit else cost / 100, quantity=1, contracts=1,
41
+ total_cost=-cost if credit else cost, entry_max_risk=cost, expiration=pd.Timestamp(exp),
42
+ underlying_entry_price=entry_px, strike=strike, opt_type='C' if 'CALL' in strategy else 'P')
43
+
44
+
45
+ def _settle(pm, day, px, pid):
46
+ infos = pm.check_positions(pd.Timestamp(day), {pid: {'underlying_price': px, 'pnl': 0.0, 'pnl_pct': 0.0,
47
+ 'price': 0.0}}, underlying_price=px)
48
+ return next(i for i in infos if i.get('position_id') == pid)
49
+
50
+
51
+ def test_ratio_and_deliverable_math():
52
+ assert lib._reverse_split_ratio(6.89 / 172.25, 33.58 / 167.90) == pytest.approx(5.0)
53
+ assert lib._reverse_split_ratio(0.04, 0.04) == 1.0
54
+ assert lib._reverse_split_ratio(2.0, 1.0) == 1.0
55
+ assert lib._reverse_split_ratio(None, 0.2) == 1.0
56
+ # 1:5 leaves 20 shares per contract: call max(0, 25.35*20 - 700) = 0, put 700 - 507 = 193
57
+ assert lib._split_intrinsic('C', 7.0, 25.35, 5.0) * 100 == pytest.approx(0.0)
58
+ assert lib._split_intrinsic('P', 7.0, 25.35, 5.0) * 100 == pytest.approx(193.0)
59
+ assert lib._split_intrinsic('C', 4.0, 25.35, 5.0) * 100 == pytest.approx(25.35 * 20 - 400.0)
60
+ assert lib._split_intrinsic('P', 7.0, 25.35) == 0.0
61
+
62
+
63
+ def test_entry_split_factor_stamped_on_open():
64
+ pm = _pm()
65
+ _open(pm, 'SHORT_CALL', 'C1')
66
+ assert pm.positions['C1']['entry_split_factor'] == pytest.approx(0.04)
67
+
68
+
69
+ def test_short_call_expires_worthless_after_reverse_split():
70
+ pm = _pm()
71
+ _open(pm, 'SHORT_CALL', 'C1', cost=50.0)
72
+ info = _settle(pm, EXP, 25.35, 'C1')
73
+ assert info['stop_type'] == 'expiration_intrinsic'
74
+ assert info['pnl'] == pytest.approx(50.0)
75
+ assert info['split_adjusted'] is True and info['split_ratio'] == pytest.approx(5.0)
76
+ assert info['settlement_price'] == pytest.approx(25.35)
77
+ info.pop('position_id')
78
+ trade = pm.close_position('C1', pd.Timestamp(EXP), 0.0, **info)
79
+ assert trade['split_adjusted'] is True and trade['entry_split_factor'] == pytest.approx(0.04)
80
+
81
+
82
+ def test_long_put_pays_on_20_share_deliverable():
83
+ pm = _pm()
84
+ _open(pm, 'LONG_PUT', 'P1', cost=30.0)
85
+ info = _settle(pm, EXP, 25.35, 'P1')
86
+ assert info['pnl'] == pytest.approx(193.0 - 30.0)
87
+
88
+
89
+ def test_marks_after_split_use_intrinsic_not_the_chain():
90
+ pm = _pm(stop_loss_enabled=True, stop_loss_config={'enabled': True, 'type': 'pl_loss', 'value': 50})
91
+ _open(pm, 'SHORT_CALL', 'C1', cost=50.0)
92
+ _open(pm, 'LONG_PUT', 'P1', cost=30.0)
93
+ # the post-split K=7 call is a new 100-share contract, not the old one
94
+ chain = pd.DataFrame({'strike': [7.0, 30.0], 'expiration': [pd.Timestamp(EXP)] * 2, 'type': ['C', 'C'],
95
+ 'bid': [26.0, 5.0], 'ask': [27.0, 5.5]})
96
+ row = UVXY_STOCK[UVXY_STOCK['date'] == pd.Timestamp('2024-04-12')]
97
+ marks = pm.build_price_data(pd.Timestamp('2024-04-12'), 37.85, chain,
98
+ lambda s, e, t: lib.get_option_by_strike_exp(chain, s, e, t), stock_row=row)
99
+ # 20 shares at 37.85 against 700 at the strike
100
+ assert marks['C1']['split_adjusted'] is True and marks['C1']['call_exit_ask'] == pytest.approx(0.57)
101
+ assert marks['C1']['pnl'] == pytest.approx(50.0 - 57.0)
102
+ assert marks['P1']['put_exit_bid'] == pytest.approx(0.0)
103
+ assert marks['P1']['pnl'] == pytest.approx(-30.0)
104
+ assert 'C1' not in pm._leg_price_cache
105
+ assert pm.check_positions(pd.Timestamp('2024-04-12'), marks, underlying_price=37.85) == []
106
+
107
+
108
+ def test_reverse_split_assignment_delivers_20_shares():
109
+ pm = _pm(assignment_mode='shares', _stock_bars=UVXY_BARS)
110
+ _open(pm, 'SHORT_PUT', 'P1', cost=30.0)
111
+ info = _settle(pm, EXP, 25.35, 'P1')
112
+ assert info['assigned_shares'] == pytest.approx(20.0)
113
+ assert info['assignment_pnl'] == pytest.approx(20.0 * (26.0 - 25.35))
114
+ assert info['pnl'] == pytest.approx(30.0 - 193.0 + 13.0)
115
+
116
+
117
+ def test_no_early_assignment_of_otm_call_after_reverse_split():
118
+ pm = _pm(assignment_mode='shares', _stock_bars=UVXY_BARS)
119
+ _open(pm, 'SHORT_CALL', 'C1', cost=50.0)
120
+ infos = pm.check_positions(pd.Timestamp('2024-05-16'), {'C1': {'underlying_price': 25.5, 'pnl': 0.0,
121
+ 'pnl_pct': 0.0, 'price': 0.0}},
122
+ underlying_price=25.5)
123
+ assert infos == []
124
+
125
+
126
+ def test_multi_symbol_frame_reads_the_position_symbol():
127
+ other = UVXY_STOCK.assign(symbol='SPY', split_factor=1.0)
128
+ frame = pd.concat([UVXY_STOCK.assign(symbol='UVXY'), other], ignore_index=True)
129
+ pm = _pm(stock=frame)
130
+ _open(pm, 'SHORT_CALL', 'C1', cost=50.0)
131
+ assert pm.positions['C1']['entry_split_factor'] == pytest.approx(0.04)
132
+ assert _settle(pm, EXP, 25.35, 'C1')['pnl'] == pytest.approx(50.0)
133
+ spy = _pm(stock=frame.iloc[::-1].reset_index(drop=True))
134
+ spy.open_position(position_id='S1', strategy_type='SHORT_PUT', symbol='SPY', entry_date=pd.Timestamp(ENTRY),
135
+ entry_price=0.0, quantity=1, contracts=1, total_cost=-50.0, entry_max_risk=50.0,
136
+ expiration=pd.Timestamp(EXP), underlying_entry_price=500.0, strike=450.0, opt_type='P')
137
+ assert spy.positions['S1']['entry_split_factor'] == 1.0
138
+ assert 'split_adjusted' not in _settle(spy, EXP, 440.0, 'S1')
139
+
140
+
141
+ def test_stock_positions_are_not_split_adjusted():
142
+ pm = _pm()
143
+ pm.open_position(position_id='L1', strategy_type='LONG_STOCK', symbol='UVXY', entry_date=pd.Timestamp(ENTRY),
144
+ entry_price=6.89, quantity=100, contracts=100, unit_multiplier=1, total_cost=689.0)
145
+ assert 'entry_split_factor' not in pm.positions['L1']
146
+
147
+
148
+ @pytest.mark.parametrize('strategy,strike,px', [('SHORT_PUT', 1100.0, 126.6), ('LONG_CALL', 1100.0, 126.6),
149
+ ('SHORT_PUT', 120.0, 110.0)])
150
+ def test_forward_split_settlement_unchanged(strategy, strike, px):
151
+ with_frame, without_frame = _pm(stock=NVDA_STOCK), _pm(stock=None)
152
+ for pm in (with_frame, without_frame):
153
+ _open(pm, strategy, 'F1', strike=strike, cost=500.0, entry='2024-06-03', exp='2024-06-21', entry_px=1150.0)
154
+ a = _settle(with_frame, '2024-06-21', px, 'F1')
155
+ b = _settle(without_frame, '2024-06-21', px, 'F1')
156
+ assert a['pnl'] == pytest.approx(b['pnl'])
157
+ assert 'split_adjusted' not in a
158
+ assert with_frame.positions['F1'].get('split_adjusted') is None
159
+
160
+
161
+ def test_forward_split_marks_still_resolve_the_adjusted_strike():
162
+ chain = pd.DataFrame({'strike': [110.0, 120.0], 'expiration': [pd.Timestamp('2024-06-21')] * 2,
163
+ 'type': ['P', 'P'], 'bid': [1.0, 3.0], 'ask': [1.2, 3.4]})
164
+ getter = lambda s, e, t: lib.get_option_by_strike_exp(chain, s, e, t) # noqa: E731
165
+ results = []
166
+ for stock in (NVDA_STOCK, None):
167
+ pm = _pm(stock=stock)
168
+ _open(pm, 'SHORT_PUT', 'F1', strike=1200.0, cost=500.0, entry='2024-06-03', exp='2024-06-21',
169
+ entry_px=1150.0)
170
+ row = NVDA_STOCK[NVDA_STOCK['date'] == pd.Timestamp('2024-06-10')]
171
+ results.append(pm.build_price_data(pd.Timestamp('2024-06-10'), 121.8, chain, getter, stock_row=row)['F1'])
172
+ assert results[0]['put_exit_ask'] == 3.4
173
+ assert results[0]['pnl'] == pytest.approx(results[1]['pnl'])
174
+ assert 'split_adjusted' not in results[0]
175
+
176
+
177
+ def _api_key():
178
+ key = os.environ.get('IVOL_API_KEY')
179
+ if key:
180
+ return key
181
+ try:
182
+ import pwd
183
+ # other test modules point HOME at a temp dir at import time
184
+ home = pwd.getpwuid(os.getuid()).pw_dir
185
+ out = subprocess.run(['security', 'find-generic-password', '-s', 'ivolatility/restapi', '-a', 'api_key', '-w',
186
+ os.path.join(home, 'Library', 'Keychains', 'ivolatility.keychain-db')],
187
+ capture_output=True, text=True, timeout=10)
188
+ return out.stdout.strip() or None
189
+ except Exception:
190
+ return None
191
+
192
+
193
+ @pytest.mark.skipif(os.environ.get('IVB_OFFLINE') == '1', reason='IVB_OFFLINE=1')
194
+ def test_live_uvxy_no_fake_loss_across_reverse_split():
195
+ """Short K=7 call and long K=7 put of UVXY held from before its 1:5 reverse split to expiration."""
196
+ key = _api_key()
197
+ if not key:
198
+ pytest.skip('no API key')
199
+ try:
200
+ import ivolatility as ivol
201
+ ivol.setLoginParams(apiKey=key)
202
+ stock_raw = ivol.setMethod('/equities/eod/stock-prices')(symbol='UVXY', from_='2024-04-01', to=EXP)
203
+ chains_get = ivol.setMethod('/equities/eod/options-rawiv')
204
+ except Exception as e:
205
+ pytest.skip(f'API unavailable: {type(e).__name__}: {e}')
206
+ if stock_raw is None or len(stock_raw) == 0:
207
+ pytest.skip('API returned no stock prices')
208
+ stock = lib._prepare_runtime_stock_frame(lib.normalize_dataframe(stock_raw, data_type='stock'))
209
+ exp = pd.Timestamp(EXP)
210
+
211
+ def chain_on(day):
212
+ raw = chains_get(symbol='UVXY', date=day)
213
+ if raw is None or len(raw) == 0:
214
+ return pd.DataFrame(columns=['strike', 'expiration', 'type', 'bid', 'ask'])
215
+ df = raw.rename(columns={'Call/Put': 'type'})
216
+ df['expiration'] = pd.to_datetime(df['expiration'])
217
+ return df[df['expiration'] == exp].reset_index(drop=True)
218
+
219
+ entry_chain = chain_on('2024-04-01')
220
+ call = lib.get_option_by_strike_exp(entry_chain, 7.0, exp, 'C')
221
+ put = lib.get_option_by_strike_exp(entry_chain, 7.0, exp, 'P')
222
+ assert call and put, 'K=7 contracts missing on the entry day'
223
+ credit, debit = call['bid'] * 100, put['ask'] * 100
224
+
225
+ pm = PositionManager({'symbol': 'UVXY', 'initial_capital': 100000, 'stop_loss_enabled': False,
226
+ 'profit_target_enabled': False, '_preloaded_stock': stock}, debug=False)
227
+ for pid, strategy, cost in (('C1', 'SHORT_CALL', credit), ('P1', 'LONG_PUT', debit)):
228
+ credit_side = strategy.startswith('SHORT')
229
+ pm.open_position(position_id=pid, strategy_type=strategy, symbol='UVXY', entry_date=pd.Timestamp('2024-04-01'),
230
+ entry_price=0.0 if credit_side else cost / 100, quantity=1, contracts=1,
231
+ total_cost=-cost if credit_side else cost, entry_max_risk=cost, expiration=exp,
232
+ underlying_entry_price=6.36, strike=7.0, opt_type='C' if 'CALL' in strategy else 'P')
233
+ assert pm.positions['C1']['entry_split_factor'] == pytest.approx(0.04, rel=1e-3)
234
+
235
+ for day in ('2024-04-12', '2024-04-15', '2024-05-16'):
236
+ chain = chain_on(day)
237
+ row = stock[pd.to_datetime(stock['date']) == pd.Timestamp(day)]
238
+ px = float(row['price'].iloc[0])
239
+ marks = pm.build_price_data(pd.Timestamp(day), px, chain,
240
+ lambda s, e, t, c=chain: lib.get_option_by_strike_exp(c, s, e, t), stock_row=row)
241
+ assert marks['C1']['split_adjusted'] and marks['C1']['split_ratio'] == pytest.approx(5.0, rel=1e-3)
242
+ assert marks['C1']['pnl'] == pytest.approx(credit - max(0.0, px * 20 - 700), abs=0.01)
243
+ assert marks['P1']['pnl'] == pytest.approx(max(0.0, 700 - px * 20) - debit, abs=0.01)
244
+ pm.check_positions(pd.Timestamp(day), marks, underlying_price=px)
245
+
246
+ row = stock[pd.to_datetime(stock['date']) == exp]
247
+ px = float(row['price'].iloc[0])
248
+ marks = pm.build_price_data(exp, px, chain_on(EXP), lambda s, e, t: None, stock_row=row)
249
+ infos = {i['position_id']: i for i in pm.check_positions(exp, marks, underlying_price=px)}
250
+ assert infos['C1']['pnl'] == pytest.approx(credit - max(0.0, px * 20 - 700), abs=0.01)
251
+ assert infos['P1']['pnl'] == pytest.approx(max(0.0, 700 - px * 20) - debit, abs=0.01)
252
+ assert infos['C1']['split_adjusted'] and infos['C1']['stop_type'] == 'expiration_intrinsic'