ivolatility-backtesting 2.166__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.166 → ivolatility_backtesting-2.167}/PKG-INFO +1 -1
  2. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/ivolatility_backtesting/ivolatility_backtesting.py +79 -14
  3. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/PKG-INFO +1 -1
  4. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/SOURCES.txt +2 -0
  5. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/pyproject.toml +1 -1
  6. ivolatility_backtesting-2.167/tests/test_2167_saturday_expiration.py +181 -0
  7. ivolatility_backtesting-2.167/tests/test_2167_xsp_settlement.py +83 -0
  8. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/README.md +0 -0
  9. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/ivolatility_backtesting/__init__.py +0 -0
  10. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/dependency_links.txt +0 -0
  11. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/requires.txt +0 -0
  12. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/ivolatility_backtesting.egg-info/top_level.txt +0 -0
  13. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/setup.cfg +0 -0
  14. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2142_fixes.py +0 -0
  15. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2144_duckdb_dedup.py +0 -0
  16. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2146_vix_vro.py +0 -0
  17. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2147_cents_multiplier.py +0 -0
  18. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2148_loader_memory.py +0 -0
  19. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2149_client_errors.py +0 -0
  20. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2150_prompt_patterns.py +0 -0
  21. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2152_cache_lock_and_rate_limit.py +0 -0
  22. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2153_cache_lock_kept.py +0 -0
  23. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2154_put_atm_legs.py +0 -0
  24. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2155_bar_prefetch.py +0 -0
  25. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2155_intraday_exits.py +0 -0
  26. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2155_ivx_stock_holes.py +0 -0
  27. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2155_key_redaction.py +0 -0
  28. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2155_long_expiry.py +0 -0
  29. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2155_opt_stop_merge.py +0 -0
  30. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2156_phantom_quotes.py +0 -0
  31. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2157_sl_symbol.py +0 -0
  32. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2158_default_path_golden.py +0 -0
  33. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2158_entry_time.py +0 -0
  34. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2159_entry_rule.py +0 -0
  35. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2160_day_price_order.py +0 -0
  36. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2160_exit_rule.py +0 -0
  37. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2160_option_lean_rule.py +0 -0
  38. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2160_prefetch_cancel.py +0 -0
  39. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2161_assignment.py +0 -0
  40. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2162_entry_minute_window.py +0 -0
  41. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2163_rotation.py +0 -0
  42. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2164_stock_price_stops.py +0 -0
  43. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2165_parquet_engine_error.py +0 -0
  44. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_2165_renamed_symbol.py +0 -0
  45. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_price_ta_indicators.py +0 -0
  46. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_stock_loader_coverage.py +0 -0
  47. {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.167}/tests/test_stop_reference_eod_close.py +0 -0
  48. {ivolatility_backtesting-2.166 → 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.166
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,7 +1907,7 @@ 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):
@@ -12824,10 +12824,66 @@ def _as_date_obj(value):
12824
12824
  return value if isinstance(value, _d.date) else None
12825
12825
 
12826
12826
 
12827
- # AM-settled cash index roots (CBOE): standard 3rd-Friday monthlies settle on
12828
- # the OPENING print (SOQ). Their weekly series (SPXW/NDXP/RUTW/…) are never
12829
- # listed ON the 3rd Friday, so root+3rd-Friday identifies AM exactly.
12830
- _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
12831
12887
 
12832
12888
 
12833
12889
  def _is_am_settled_position(position):
@@ -12848,10 +12904,16 @@ def _is_am_settled_position(position):
12848
12904
  # Every VIX expiration (Wednesday, or Tue/Thu when shifted) is cash-settled
12849
12905
  # on the morning VRO print; the open is only the fallback proxy.
12850
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))
12851
12914
  if root not in _AM_SETTLED_INDEX_ROOTS:
12852
12915
  return False
12853
- exp = _as_date_obj(position.get('expiration'))
12854
- return exp is not None and exp.weekday() == 4 and 15 <= exp.day <= 21
12916
+ return _is_standard_monthly_expiration(exp)
12855
12917
 
12856
12918
 
12857
12919
  # Max calendar gap between a VIX expiration date and the VRO print that settles it.
@@ -12901,7 +12963,7 @@ def _vro_settlement_for(config, expiration):
12901
12963
  # config['assignment_mode']: 'cash' (intrinsic at the close) | 'shares'
12902
12964
  # config['assignment_exit']: 'next_open' | 'next_close' (liquidation of the delivered shares)
12903
12965
  _CASH_SETTLED_ROOTS = _AM_SETTLED_INDEX_ROOTS | {
12904
- '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',
12905
12967
  }
12906
12968
 
12907
12969
 
@@ -14110,11 +14172,14 @@ class PositionManager:
14110
14172
 
14111
14173
  # Check if expired
14112
14174
  current_date_normalized = current_date.date() if hasattr(current_date, 'date') else current_date
14113
-
14114
- early_assignment = (current_date_normalized < expiration and
14115
- 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,
14116
14181
  price_data, _underlying_arg))
14117
- if current_date_normalized >= expiration or early_assignment:
14182
+ if current_date_normalized >= settle_on or early_assignment:
14118
14183
  # ────────────────────────────────────────────────────────────────
14119
14184
  # SETTLEMENT-AT-EXPIRATION (universal across asset types)
14120
14185
  # ────────────────────────────────────────────────────────────────
@@ -15220,7 +15285,7 @@ class PositionManager:
15220
15285
  continue
15221
15286
  # No PT on/after expiration: zero-quote chain rows fake a +100%
15222
15287
  # CREDIT buyback at $0; expiration settles via intrinsic instead
15223
- _pt_exp = _as_date_obj(position.get('expiration'))
15288
+ _pt_exp = _settlement_session(position.get('expiration'), self.config)
15224
15289
  _pt_now = _as_date_obj(current_date)
15225
15290
  _eod_counts = use_eod
15226
15291
  if _pt_exp is not None and _pt_now is not None and _pt_now >= _pt_exp:
@@ -15372,7 +15437,7 @@ class PositionManager:
15372
15437
  fake -100%/+100% off market quotes otherwise); None = guard not applicable."""
15373
15438
  if kwargs.get('settlement_type') == 'intrinsic':
15374
15439
  return None # already settled by check_positions
15375
- exp_d = _as_date_obj(position.get('expiration'))
15440
+ exp_d = _settlement_session(position.get('expiration'), self.config)
15376
15441
  exit_d = _as_date_obj(exit_date)
15377
15442
  if exp_d is None or exit_d is None or exit_d < exp_d:
15378
15443
  return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ivolatility_backtesting
3
- Version: 2.166
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,8 @@ 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
44
46
  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.166"
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 = [
@@ -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)