ivolatility-backtesting 2.166__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.
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/PKG-INFO +1 -1
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/ivolatility_backtesting/ivolatility_backtesting.py +220 -26
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/PKG-INFO +1 -1
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/SOURCES.txt +3 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/pyproject.toml +1 -1
- ivolatility_backtesting-2.168/tests/test_2167_saturday_expiration.py +181 -0
- ivolatility_backtesting-2.168/tests/test_2167_xsp_settlement.py +83 -0
- ivolatility_backtesting-2.168/tests/test_2168_reverse_split.py +252 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/README.md +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/ivolatility_backtesting/__init__.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/dependency_links.txt +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/requires.txt +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/ivolatility_backtesting.egg-info/top_level.txt +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/setup.cfg +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2142_fixes.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2144_duckdb_dedup.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2146_vix_vro.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2147_cents_multiplier.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2148_loader_memory.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2149_client_errors.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2150_prompt_patterns.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2152_cache_lock_and_rate_limit.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2153_cache_lock_kept.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2154_put_atm_legs.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_bar_prefetch.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_intraday_exits.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_ivx_stock_holes.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_key_redaction.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_long_expiry.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_opt_stop_merge.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2156_phantom_quotes.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2157_sl_symbol.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2158_default_path_golden.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2158_entry_time.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2159_entry_rule.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2160_day_price_order.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2160_exit_rule.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2160_option_lean_rule.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2160_prefetch_cancel.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2161_assignment.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2162_entry_minute_window.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2163_rotation.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2164_stock_price_stops.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2165_parquet_engine_error.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2165_renamed_symbol.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_price_ta_indicators.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_stock_loader_coverage.py +0 -0
- {ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_stop_reference_eod_close.py +0 -0
- {ivolatility_backtesting-2.166 → 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.
|
|
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
|
|
@@ -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
|
-
#
|
|
12828
|
-
|
|
12829
|
-
#
|
|
12830
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -12987,6 +13049,32 @@ def _assignment_shares(legs, settlement_price, unit_multiplier, contracts):
|
|
|
12987
13049
|
return shares, cash
|
|
12988
13050
|
|
|
12989
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
|
+
|
|
12990
13078
|
_STOCK_BAR_OPEN_COLUMNS = ('runtime_open', 'open')
|
|
12991
13079
|
_STOCK_BAR_CLOSE_COLUMNS = ('runtime_close', 'price', 'unadjusted_close', 'close')
|
|
12992
13080
|
|
|
@@ -13080,6 +13168,9 @@ class PositionManager:
|
|
|
13080
13168
|
self._stock_bars = None
|
|
13081
13169
|
self._stock_bar_keys = None
|
|
13082
13170
|
self._assignment_warned = set()
|
|
13171
|
+
self._split_factors = None
|
|
13172
|
+
self._split_factors_src = None
|
|
13173
|
+
self._split_factors_multi = False
|
|
13083
13174
|
|
|
13084
13175
|
# Stop-loss enable logic:
|
|
13085
13176
|
# 1) Respect explicit flag if provided (stop_loss_enabled)
|
|
@@ -13242,7 +13333,7 @@ class PositionManager:
|
|
|
13242
13333
|
px = underlying_arg
|
|
13243
13334
|
if not px or float(px) <= 0:
|
|
13244
13335
|
return False
|
|
13245
|
-
px = float(px)
|
|
13336
|
+
px = float(px) / self._position_split_ratio(position, today)
|
|
13246
13337
|
threshold = float(self.config.get('assignment_early_itm_pct', 0.05))
|
|
13247
13338
|
for t, k, q in legs:
|
|
13248
13339
|
if q >= 0:
|
|
@@ -13705,6 +13796,10 @@ class PositionManager:
|
|
|
13705
13796
|
# If caller already passed 'unit_multiplier' via kwargs, respect it.
|
|
13706
13797
|
if 'unit_multiplier' not in position:
|
|
13707
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
|
|
13708
13803
|
|
|
13709
13804
|
if self.sl_enabled and self.sl_manager:
|
|
13710
13805
|
sl_type = self.sl_config.get('type', 'fixed_pct')
|
|
@@ -13843,6 +13938,74 @@ class PositionManager:
|
|
|
13843
13938
|
return None, None
|
|
13844
13939
|
return row, _resolve_runtime_underlying_price(stock_row=row)
|
|
13845
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
|
+
|
|
13846
14009
|
def _post_entry_underlying_range(self, position, entry_date, close_price):
|
|
13847
14010
|
"""Underlying high/low after the entry bar; without bars, the entry and close prices, never the whole day."""
|
|
13848
14011
|
if not self.sl_enabled or self.sl_manager is None or (self.sl_config or {}).get('type') not in ('directional', 'combined'):
|
|
@@ -14110,11 +14273,14 @@ class PositionManager:
|
|
|
14110
14273
|
|
|
14111
14274
|
# Check if expired
|
|
14112
14275
|
current_date_normalized = current_date.date() if hasattr(current_date, 'date') else current_date
|
|
14113
|
-
|
|
14114
|
-
|
|
14115
|
-
|
|
14276
|
+
# The listed date may be a Saturday or an exchange holiday:
|
|
14277
|
+
# settle on the last trading day on or before it
|
|
14278
|
+
settle_on = _settlement_session(expiration, self.config) or expiration
|
|
14279
|
+
|
|
14280
|
+
early_assignment = (current_date_normalized < settle_on and
|
|
14281
|
+
self._early_assignment_due(position, position_id, current_date_normalized, settle_on,
|
|
14116
14282
|
price_data, _underlying_arg))
|
|
14117
|
-
if current_date_normalized >=
|
|
14283
|
+
if current_date_normalized >= settle_on or early_assignment:
|
|
14118
14284
|
# ────────────────────────────────────────────────────────────────
|
|
14119
14285
|
# SETTLEMENT-AT-EXPIRATION (universal across asset types)
|
|
14120
14286
|
# ────────────────────────────────────────────────────────────────
|
|
@@ -14188,15 +14354,17 @@ class PositionManager:
|
|
|
14188
14354
|
contracts = position.get('contracts', 1)
|
|
14189
14355
|
entry_premium = abs(position.get('total_cost', 0))
|
|
14190
14356
|
|
|
14357
|
+
split_ratio = self._position_split_ratio(position, current_date_normalized)
|
|
14191
14358
|
if underlying_price and underlying_price > 0:
|
|
14192
14359
|
# ============================================================
|
|
14193
14360
|
# PRIMARY PATH — Intrinsic settlement (canonical for expiration)
|
|
14194
14361
|
# ============================================================
|
|
14362
|
+
# Past a reverse split the contract delivers 100/ratio shares: S/ratio against the old strikes
|
|
14195
14363
|
intrinsic_value = self._calculate_intrinsic_value(
|
|
14196
14364
|
position=position,
|
|
14197
14365
|
position_id=position_id,
|
|
14198
14366
|
strategy_type=strategy_type,
|
|
14199
|
-
underlying_price=underlying_price,
|
|
14367
|
+
underlying_price=underlying_price / split_ratio,
|
|
14200
14368
|
strike=strike,
|
|
14201
14369
|
contracts=contracts
|
|
14202
14370
|
)
|
|
@@ -14225,7 +14393,9 @@ class PositionManager:
|
|
|
14225
14393
|
if early_assignment:
|
|
14226
14394
|
assignment_info = {'early_assignment': True}
|
|
14227
14395
|
if _legs:
|
|
14228
|
-
_shares, _cash_at_strikes = _assignment_shares(_legs, underlying_price
|
|
14396
|
+
_shares, _cash_at_strikes = _assignment_shares(_legs, underlying_price / split_ratio,
|
|
14397
|
+
_um, contracts)
|
|
14398
|
+
_shares = _shares / split_ratio
|
|
14229
14399
|
_when = 'early' if early_assignment else 'at expiration'
|
|
14230
14400
|
if _shares:
|
|
14231
14401
|
self._ensure_stock_bars()
|
|
@@ -14338,6 +14508,8 @@ class PositionManager:
|
|
|
14338
14508
|
'settlement_price': underlying_price if used_intrinsic else None,
|
|
14339
14509
|
**(assignment_info if used_intrinsic else {}),
|
|
14340
14510
|
}
|
|
14511
|
+
if split_ratio != 1.0:
|
|
14512
|
+
stop_info.update({'split_adjusted': True, 'split_ratio': split_ratio})
|
|
14341
14513
|
|
|
14342
14514
|
to_close.append(stop_info)
|
|
14343
14515
|
|
|
@@ -14391,6 +14563,11 @@ class PositionManager:
|
|
|
14391
14563
|
if self.debug:
|
|
14392
14564
|
print(f" [check_positions] ⏭️ {position_id}: skipping SL — price_data from fallback cache (stale leg)")
|
|
14393
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
|
|
14394
14571
|
|
|
14395
14572
|
if isinstance(price_data[position_id], dict):
|
|
14396
14573
|
data = price_data[position_id]
|
|
@@ -14945,11 +15122,18 @@ class PositionManager:
|
|
|
14945
15122
|
for position in (self.get_open_positions() if positions is None else positions):
|
|
14946
15123
|
pos_id = position['id']
|
|
14947
15124
|
|
|
14948
|
-
|
|
14949
|
-
|
|
14950
|
-
position,
|
|
14951
|
-
|
|
14952
|
-
|
|
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
|
+
|
|
14953
15137
|
# ================================================================
|
|
14954
15138
|
# FALLBACK: Per-leg price cache for diagonal/calendar spreads
|
|
14955
15139
|
# ================================================================
|
|
@@ -14959,7 +15143,7 @@ class PositionManager:
|
|
|
14959
15143
|
# This fixes SL=0 for DPS/DCS/calendar strategies without requiring
|
|
14960
15144
|
# manual price_data injection in every notebook.
|
|
14961
15145
|
_used_fallback = False
|
|
14962
|
-
if leg_data is None:
|
|
15146
|
+
if leg_data is None and split_ratio == 1.0:
|
|
14963
15147
|
fallback = self._build_fallback_leg_data(position, options_df, get_option_func)
|
|
14964
15148
|
if fallback is not None:
|
|
14965
15149
|
leg_data = fallback
|
|
@@ -14993,7 +15177,7 @@ class PositionManager:
|
|
|
14993
15177
|
|
|
14994
15178
|
if leg_data is not None:
|
|
14995
15179
|
# Cache per-leg prices ONLY from fresh market data (not from fallback itself)
|
|
14996
|
-
if not _used_fallback and leg_data:
|
|
15180
|
+
if not _used_fallback and leg_data and split_ratio == 1.0:
|
|
14997
15181
|
self._leg_price_cache[pos_id] = {k: dict(v) if hasattr(v, 'items') else v for k, v in leg_data.items()}
|
|
14998
15182
|
|
|
14999
15183
|
# Auto-generate price_data (framework calculates P&L automatically!)
|
|
@@ -15009,6 +15193,8 @@ class PositionManager:
|
|
|
15009
15193
|
# (cached leg prices from a previous day produce stale P&L → spurious SL triggers)
|
|
15010
15194
|
if _used_fallback:
|
|
15011
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})
|
|
15012
15198
|
|
|
15013
15199
|
# Add ALL indicators with 'exit_' prefix (universal for any strategy)
|
|
15014
15200
|
if indicators:
|
|
@@ -15220,7 +15406,7 @@ class PositionManager:
|
|
|
15220
15406
|
continue
|
|
15221
15407
|
# No PT on/after expiration: zero-quote chain rows fake a +100%
|
|
15222
15408
|
# CREDIT buyback at $0; expiration settles via intrinsic instead
|
|
15223
|
-
_pt_exp =
|
|
15409
|
+
_pt_exp = _settlement_session(position.get('expiration'), self.config)
|
|
15224
15410
|
_pt_now = _as_date_obj(current_date)
|
|
15225
15411
|
_eod_counts = use_eod
|
|
15226
15412
|
if _pt_exp is not None and _pt_now is not None and _pt_now >= _pt_exp:
|
|
@@ -15229,6 +15415,11 @@ class PositionManager:
|
|
|
15229
15415
|
print(f"[PT] SKIP {position_id}: at/after expiration {_pt_exp} — settled by expiration path")
|
|
15230
15416
|
continue
|
|
15231
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
|
|
15232
15423
|
# ========================================================
|
|
15233
15424
|
# Check min_days_before_check for profit target (trading days)
|
|
15234
15425
|
# ========================================================
|
|
@@ -15372,7 +15563,7 @@ class PositionManager:
|
|
|
15372
15563
|
fake -100%/+100% off market quotes otherwise); None = guard not applicable."""
|
|
15373
15564
|
if kwargs.get('settlement_type') == 'intrinsic':
|
|
15374
15565
|
return None # already settled by check_positions
|
|
15375
|
-
exp_d =
|
|
15566
|
+
exp_d = _settlement_session(position.get('expiration'), self.config)
|
|
15376
15567
|
exit_d = _as_date_obj(exit_date)
|
|
15377
15568
|
if exp_d is None or exit_d is None or exit_d < exp_d:
|
|
15378
15569
|
return None
|
|
@@ -15403,7 +15594,7 @@ class PositionManager:
|
|
|
15403
15594
|
position=position,
|
|
15404
15595
|
position_id=position_id,
|
|
15405
15596
|
strategy_type=strategy_type,
|
|
15406
|
-
underlying_price=underlying_price,
|
|
15597
|
+
underlying_price=underlying_price / self._position_split_ratio(position, exit_d),
|
|
15407
15598
|
strike=position.get('strike', 0),
|
|
15408
15599
|
contracts=contracts,
|
|
15409
15600
|
)
|
|
@@ -15667,7 +15858,10 @@ class PositionManager:
|
|
|
15667
15858
|
trade['stop_level_high'] = underlying_entry * (1 + threshold)
|
|
15668
15859
|
trade['stop_level_low'] = underlying_entry * (1 - threshold)
|
|
15669
15860
|
trade['stop_threshold'] = threshold * 100
|
|
15670
|
-
|
|
15861
|
+
if position.get('split_adjusted'):
|
|
15862
|
+
trade.setdefault('split_adjusted', True)
|
|
15863
|
+
trade.setdefault('split_ratio', position.get('split_ratio'))
|
|
15864
|
+
|
|
15671
15865
|
self.closed_trades.append(trade)
|
|
15672
15866
|
|
|
15673
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.
|
|
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
|
|
@@ -39,6 +39,9 @@ tests/test_2163_rotation.py
|
|
|
39
39
|
tests/test_2164_stock_price_stops.py
|
|
40
40
|
tests/test_2165_parquet_engine_error.py
|
|
41
41
|
tests/test_2165_renamed_symbol.py
|
|
42
|
+
tests/test_2167_saturday_expiration.py
|
|
43
|
+
tests/test_2167_xsp_settlement.py
|
|
44
|
+
tests/test_2168_reverse_split.py
|
|
42
45
|
tests/test_price_ta_indicators.py
|
|
43
46
|
tests/test_stock_loader_coverage.py
|
|
44
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.
|
|
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,181 @@
|
|
|
1
|
+
# Expirations listed on a Saturday or exchange holiday settle on the last trading day before them.
|
|
2
|
+
# Run: python3 tests/test_2167_saturday_expiration.py or pytest
|
|
3
|
+
import contextlib
|
|
4
|
+
import io
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import traceback
|
|
8
|
+
from datetime import date
|
|
9
|
+
|
|
10
|
+
import matplotlib
|
|
11
|
+
matplotlib.use('Agg')
|
|
12
|
+
|
|
13
|
+
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
14
|
+
sys.path.insert(0, os.path.join(_REPO, 'ivolatility_backtesting'))
|
|
15
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
16
|
+
import ivolatility_backtesting as lib # noqa: E402
|
|
17
|
+
|
|
18
|
+
D = date
|
|
19
|
+
# (open, close) of the underlying per trading day
|
|
20
|
+
PX = {
|
|
21
|
+
'XSP_2019': {D(2019, 11, 14): (309.08, 309.66), D(2019, 11, 15): (310.79, 312.05), D(2019, 11, 18): (311.79, 312.20),
|
|
22
|
+
D(2019, 11, 21): (310.85, 310.35), D(2019, 11, 22): (311.14, 311.03), D(2019, 11, 25): (311.64, 314.12)},
|
|
23
|
+
'XSP_2013': {D(2013, 11, 14): (178.28, 179.06), D(2013, 11, 15): (179.07, 179.82), D(2013, 11, 18): (179.88, 179.15)},
|
|
24
|
+
'XSP_2014GF': {D(2014, 4, 16): (184.60, 186.23), D(2014, 4, 17): (186.17, 186.49), D(2014, 4, 21): (186.58, 187.19)},
|
|
25
|
+
'XSPAM_2012': {D(2012, 6, 14): (131.49, 132.91), D(2012, 6, 15): (132.92, 134.28), D(2012, 6, 18): (134.24, 134.48)},
|
|
26
|
+
'XSPAM_2012Q': {D(2012, 6, 28): (133.15, 132.90), D(2012, 6, 29): (133.01, 136.22), D(2012, 7, 2): (136.23, 136.55)},
|
|
27
|
+
'XSPAM_2013': {D(2013, 11, 14): (178.28, 179.06), D(2013, 11, 15): (179.07, 179.82), D(2013, 11, 18): (179.88, 179.15)},
|
|
28
|
+
'SPX_2012': {D(2012, 6, 14): (1314.88, 1329.10), D(2012, 6, 15): (1329.19, 1342.84), D(2012, 6, 18): (1342.42, 1344.78)},
|
|
29
|
+
'SPX_2014GF': {D(2014, 4, 16): (1846.01, 1862.31), D(2014, 4, 17): (1861.73, 1864.85), D(2014, 4, 21): (1865.79, 1871.89)},
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _settle(sym, root, exp, pxk, strike, extra=None, with_days=True):
|
|
34
|
+
"""(day the position settled, underlying value used) for a long call held to expiration."""
|
|
35
|
+
px = PX[pxk]
|
|
36
|
+
days = sorted(px)
|
|
37
|
+
cfg = {'strategy_type': 'LONG_CALL', 'debuginfo': 0}
|
|
38
|
+
if with_days:
|
|
39
|
+
cfg['_trading_days'] = list(days)
|
|
40
|
+
pm = lib.PositionManager(cfg, debug=False)
|
|
41
|
+
seen = []
|
|
42
|
+
orig = pm._calculate_intrinsic_value
|
|
43
|
+
|
|
44
|
+
def spy(*a, **k):
|
|
45
|
+
seen.append(float(k.get('underlying_price')))
|
|
46
|
+
return orig(*a, **k)
|
|
47
|
+
pm._calculate_intrinsic_value = spy
|
|
48
|
+
kw = dict(strategy_type='LONG_CALL', expiration=date.fromisoformat(exp), strike=strike, total_cost=100.0,
|
|
49
|
+
contracts=1, underlying_entry_price=px[days[0]][1], opt_type='call', **(extra or {}))
|
|
50
|
+
if root:
|
|
51
|
+
kw['opt_root'] = root
|
|
52
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
53
|
+
pm.open_position('P1', sym, days[0], 0, 1, **kw)
|
|
54
|
+
for d in days[1:]:
|
|
55
|
+
o, c = px[d]
|
|
56
|
+
if pm.check_positions(d, {'P1': {'underlying_price': c, 'underlying_open': o}}, c):
|
|
57
|
+
return d, round(seen[-1], 2)
|
|
58
|
+
return None, None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _check(got, expected):
|
|
62
|
+
assert got[0] == expected[0] and got[1] is not None and abs(got[1] - expected[1]) < 0.02, (got, expected)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_s1_xsp_monthly_pm():
|
|
66
|
+
_check(_settle('XSP', None, '2019-11-15', 'XSP_2019', 300), (D(2019, 11, 15), 312.05))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_s2_xsp_monthly_explicit_pm():
|
|
70
|
+
_check(_settle('XSP', None, '2019-11-15', 'XSP_2019', 300, {'settlement_style': 'PM'}), (D(2019, 11, 15), 312.05))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_s3_xsp_weekly_pm():
|
|
74
|
+
_check(_settle('XSP', None, '2019-11-22', 'XSP_2019', 300), (D(2019, 11, 22), 311.03))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_s4_xsp_saturday_monthly_settles_friday_close():
|
|
78
|
+
_check(_settle('XSP', None, '2013-11-16', 'XSP_2013', 170), (D(2013, 11, 15), 179.82))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_s4b_saturday_without_trading_days():
|
|
82
|
+
_check(_settle('XSP', None, '2013-11-16', 'XSP_2013', 170, with_days=False), (D(2013, 11, 15), 179.82))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_s5_good_friday_settles_thursday():
|
|
86
|
+
_check(_settle('XSP', None, '2014-04-19', 'XSP_2014GF', 180), (D(2014, 4, 17), 186.49))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_s6_xspam_saturday_monthly_settles_friday_open():
|
|
90
|
+
_check(_settle('XSPAM', None, '2012-06-16', 'XSPAM_2012', 120), (D(2012, 6, 15), 132.92))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_s7_xsppm_quarterly_pm():
|
|
94
|
+
_check(_settle('XSPAM', 'XSPPM', '2012-06-29', 'XSPAM_2012Q', 120), (D(2012, 6, 29), 136.22))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_s8_xspam_explicit_pm_settles_friday_close():
|
|
98
|
+
_check(_settle('XSPAM', None, '2012-06-16', 'XSPAM_2012', 120, {'settlement_style': 'PM'}), (D(2012, 6, 15), 134.28))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_s9_spx_saturday_monthly_am():
|
|
102
|
+
_check(_settle('SPX', None, '2012-06-16', 'SPX_2012', 1300), (D(2012, 6, 15), 1329.19))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_s10_spx_good_friday_am_on_thursday_open():
|
|
106
|
+
_check(_settle('SPX', None, '2014-04-19', 'SPX_2014GF', 1800), (D(2014, 4, 17), 1861.73))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_xspam_symbol_with_root_xsp_is_am():
|
|
110
|
+
# contracts listed before the rename carry root XSP under the XSPAM symbol, also past the cutoff date
|
|
111
|
+
_check(_settle('XSPAM', 'XSP', '2013-11-16', 'XSPAM_2013', 170), (D(2013, 11, 15), 179.07))
|
|
112
|
+
_check(_settle('XSPAM', 'XSP', '2012-06-16', 'XSPAM_2012', 120), (D(2012, 6, 15), 132.92))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_xsp_symbol_with_root_xsp_is_pm():
|
|
116
|
+
_check(_settle('XSP', 'XSP', '2013-11-16', 'XSP_2013', 170), (D(2013, 11, 15), 179.82))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_root_xsp_before_cutoff_is_am():
|
|
120
|
+
assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': D(2012, 6, 16)}) is True
|
|
121
|
+
assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': D(2013, 11, 16)}) is False
|
|
122
|
+
assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': D(2012, 6, 22)}) is False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_saturday_monthly_detection():
|
|
126
|
+
for root in ('SPX', 'NDX', 'RUT', 'DJX', 'XSPAM'):
|
|
127
|
+
assert lib._is_am_settled_position({'symbol': root, 'expiration': D(2012, 6, 16)}) is True, root
|
|
128
|
+
assert lib._is_am_settled_position({'symbol': 'SPX', 'expiration': D(2012, 6, 9)}) is False
|
|
129
|
+
assert lib._is_am_settled_position({'symbol': 'SPX', 'expiration': D(2012, 6, 23)}) is False
|
|
130
|
+
assert lib._is_am_settled_position({'symbol': 'AAPL', 'expiration': D(2012, 6, 16)}) is False
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_settlement_session():
|
|
134
|
+
days = [D(2014, 4, 16), D(2014, 4, 17), D(2014, 4, 21)]
|
|
135
|
+
cfg = {'_trading_days': days}
|
|
136
|
+
assert lib._settlement_session(D(2014, 4, 19), cfg) == D(2014, 4, 17)
|
|
137
|
+
assert lib._settlement_session('2014-04-19', {'_runtime_parent_config': cfg}) == D(2014, 4, 17)
|
|
138
|
+
assert lib._settlement_session(D(2014, 4, 17), cfg) == D(2014, 4, 17)
|
|
139
|
+
assert lib._settlement_session(D(2013, 11, 16), None) == D(2013, 11, 15)
|
|
140
|
+
assert lib._settlement_session(D(2013, 11, 17), None) == D(2013, 11, 15)
|
|
141
|
+
assert lib._settlement_session(D(2014, 5, 16), cfg) == D(2014, 5, 16)
|
|
142
|
+
assert lib._settlement_session(None, cfg) is None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_memo_ignores_foreign_object_with_same_id():
|
|
146
|
+
days = [D(2014, 4, 16), D(2014, 4, 17), D(2014, 4, 18)]
|
|
147
|
+
stale = [D(2014, 4, 16), D(2014, 4, 17), D(2014, 4, 21)]
|
|
148
|
+
lib._SETTLE_DAYS_MEMO[id(days)] = (stale, len(days), sorted(stale))
|
|
149
|
+
assert lib._settlement_session(D(2014, 4, 19), {'_trading_days': days}) == D(2014, 4, 18)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_intrinsic_guard_applies_on_settlement_day():
|
|
153
|
+
cfg = {'strategy_type': 'LONG_CALL', '_trading_days': sorted(PX['XSP_2013'])}
|
|
154
|
+
pm = lib.PositionManager(cfg, debug=False)
|
|
155
|
+
pos = {'expiration': D(2013, 11, 16), 'strategy_type': 'LONG_CALL', 'strike': 170, 'contracts': 1,
|
|
156
|
+
'total_cost': 100.0, 'opt_type': 'call', 'entry_price': 1.0}
|
|
157
|
+
dead = {'call_exit_bid': 0, 'call_exit_ask': 0, 'underlying_exit_price': 179.82}
|
|
158
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
159
|
+
assert pm._intrinsic_guard_pnl(pos, 'P1', D(2013, 11, 15), dict(dead)) is not None
|
|
160
|
+
assert pm._intrinsic_guard_pnl(pos, 'P1', D(2013, 11, 14), dict(dead)) is None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_xsppm_is_cash_settled():
|
|
164
|
+
assert 'XSPPM' in lib._CASH_SETTLED_ROOTS
|
|
165
|
+
assert 'XSPAM' in lib._CASH_SETTLED_ROOTS
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
if __name__ == '__main__':
|
|
169
|
+
tests = [(n, f) for n, f in sorted(globals().items())
|
|
170
|
+
if n.startswith('test_') and callable(f)]
|
|
171
|
+
failed = []
|
|
172
|
+
for name, fn in tests:
|
|
173
|
+
try:
|
|
174
|
+
fn()
|
|
175
|
+
print(f"PASS {name}")
|
|
176
|
+
except Exception:
|
|
177
|
+
failed.append(name)
|
|
178
|
+
print(f"FAIL {name}")
|
|
179
|
+
traceback.print_exc()
|
|
180
|
+
print(f"\n{len(tests) - len(failed)}/{len(tests)} passed")
|
|
181
|
+
sys.exit(1 if failed else 0)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# XSP 3rd-Friday = PM-settled; XSPAM = AM-settled.
|
|
2
|
+
# Run: python3 tests/test_2167_xsp_settlement.py or pytest
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
import traceback
|
|
6
|
+
from datetime import date
|
|
7
|
+
|
|
8
|
+
import matplotlib
|
|
9
|
+
matplotlib.use('Agg')
|
|
10
|
+
|
|
11
|
+
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
12
|
+
sys.path.insert(0, os.path.join(_REPO, 'ivolatility_backtesting'))
|
|
13
|
+
import ivolatility_backtesting as lib # noqa: E402
|
|
14
|
+
|
|
15
|
+
THIRD_FRIDAY = date(2019, 11, 15)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_xsp_third_friday_is_pm():
|
|
19
|
+
assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': THIRD_FRIDAY}) is False
|
|
20
|
+
assert lib._is_am_settled_position({'opt_root': 'XSP', 'symbol': 'XSP', 'expiration': THIRD_FRIDAY}) is False
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_xspam_third_friday_is_am():
|
|
24
|
+
assert lib._is_am_settled_position({'opt_root': 'XSPAM', 'symbol': 'XSP', 'expiration': THIRD_FRIDAY}) is True
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_explicit_style_wins():
|
|
28
|
+
assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': THIRD_FRIDAY, 'settlement_style': 'AM'}) is True
|
|
29
|
+
assert lib._is_am_settled_position({'symbol': 'SPX', 'expiration': THIRD_FRIDAY, 'settlement_style': 'PM'}) is False
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_other_roots_unchanged():
|
|
33
|
+
for root in ('SPX', 'NDX', 'RUT', 'DJX'):
|
|
34
|
+
assert lib._is_am_settled_position({'symbol': root, 'expiration': THIRD_FRIDAY}) is True, root
|
|
35
|
+
assert lib._is_am_settled_position({'opt_root': 'SPXW', 'symbol': 'SPX', 'expiration': THIRD_FRIDAY}) is False
|
|
36
|
+
assert lib._is_am_settled_position({'symbol': 'AAPL', 'expiration': THIRD_FRIDAY}) is False
|
|
37
|
+
assert lib._is_am_settled_position({'symbol': 'XSP', 'expiration': date(2019, 11, 8)}) is False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
XSP_OPEN, XSP_CLOSE = 310.79, 312.05
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _short_xsp_put(root):
|
|
44
|
+
pm = lib.PositionManager({'strategy_type': 'PUT', 'symbol': 'XSP'}, debug=False)
|
|
45
|
+
pm.open_position(position_id='p1', strategy_type='PUT', symbol='XSP', entry_date=date(2019, 11, 1),
|
|
46
|
+
entry_price=0.0, quantity=100, contracts=1, total_cost=150.0, strike=312.0,
|
|
47
|
+
expiration=THIRD_FRIDAY, underlying_entry_price=306.0, opt_type='put')
|
|
48
|
+
if root:
|
|
49
|
+
pm.positions['p1']['opt_root'] = root
|
|
50
|
+
return pm.check_positions(THIRD_FRIDAY, {'p1': {'underlying_price': XSP_CLOSE, 'underlying_open': XSP_OPEN}})[0]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_short_xsp_put_settles_on_the_close():
|
|
54
|
+
si = _short_xsp_put(None)
|
|
55
|
+
assert si['settlement_source'] == 'close', si.get('settlement_source')
|
|
56
|
+
assert abs(si['pnl'] - 150.0) < 1e-6, si['pnl']
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_short_xspam_put_settles_on_the_open():
|
|
60
|
+
si = _short_xsp_put('XSPAM')
|
|
61
|
+
assert si['settlement_source'] == 'open', si.get('settlement_source')
|
|
62
|
+
assert abs(si['pnl'] - (150.0 - (312.0 - XSP_OPEN) * 100)) < 1e-6, si['pnl']
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_xsp_stays_cash_settled():
|
|
66
|
+
assert 'XSP' in lib._CASH_SETTLED_ROOTS
|
|
67
|
+
assert 'XSPAM' in lib._CASH_SETTLED_ROOTS
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
if __name__ == '__main__':
|
|
71
|
+
tests = [(n, f) for n, f in sorted(globals().items())
|
|
72
|
+
if n.startswith('test_') and callable(f)]
|
|
73
|
+
failed = []
|
|
74
|
+
for name, fn in tests:
|
|
75
|
+
try:
|
|
76
|
+
fn()
|
|
77
|
+
print(f"PASS {name}")
|
|
78
|
+
except Exception:
|
|
79
|
+
failed.append(name)
|
|
80
|
+
print(f"FAIL {name}")
|
|
81
|
+
traceback.print_exc()
|
|
82
|
+
print(f"\n{len(tests) - len(failed)}/{len(tests)} passed")
|
|
83
|
+
sys.exit(1 if failed else 0)
|
|
@@ -0,0 +1,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'
|
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/ivolatility_backtesting/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2144_duckdb_dedup.py
RENAMED
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2147_cents_multiplier.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2148_loader_memory.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2149_client_errors.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2150_prompt_patterns.py
RENAMED
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2153_cache_lock_kept.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2154_put_atm_legs.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_bar_prefetch.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_intraday_exits.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_ivx_stock_holes.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_key_redaction.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_long_expiry.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2155_opt_stop_merge.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2156_phantom_quotes.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2157_sl_symbol.py
RENAMED
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2158_entry_time.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2159_entry_rule.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2160_day_price_order.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2160_exit_rule.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2160_option_lean_rule.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2160_prefetch_cancel.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2161_assignment.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2164_stock_price_stops.py
RENAMED
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_2165_renamed_symbol.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_price_ta_indicators.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.166 → ivolatility_backtesting-2.168}/tests/test_stock_loader_coverage.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|