ivolatility-backtesting 2.163__tar.gz → 2.164__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.164/PKG-INFO +252 -0
- ivolatility_backtesting-2.164/README.md +228 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/ivolatility_backtesting/ivolatility_backtesting.py +5 -1
- ivolatility_backtesting-2.164/ivolatility_backtesting.egg-info/PKG-INFO +252 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/ivolatility_backtesting.egg-info/SOURCES.txt +1 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/pyproject.toml +1 -1
- ivolatility_backtesting-2.164/tests/test_2164_stock_price_stops.py +64 -0
- ivolatility_backtesting-2.163/PKG-INFO +0 -73
- ivolatility_backtesting-2.163/README.md +0 -49
- ivolatility_backtesting-2.163/ivolatility_backtesting.egg-info/PKG-INFO +0 -73
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/ivolatility_backtesting/__init__.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/ivolatility_backtesting.egg-info/dependency_links.txt +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/ivolatility_backtesting.egg-info/requires.txt +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/ivolatility_backtesting.egg-info/top_level.txt +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/setup.cfg +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2142_fixes.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2144_duckdb_dedup.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2146_vix_vro.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2147_cents_multiplier.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2148_loader_memory.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2149_client_errors.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2150_prompt_patterns.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2152_cache_lock_and_rate_limit.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2153_cache_lock_kept.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2154_put_atm_legs.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_bar_prefetch.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_intraday_exits.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_ivx_stock_holes.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_key_redaction.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_long_expiry.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_opt_stop_merge.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2156_phantom_quotes.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2157_sl_symbol.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2158_default_path_golden.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2158_entry_time.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2159_entry_rule.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2160_day_price_order.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2160_exit_rule.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2160_option_lean_rule.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2160_prefetch_cancel.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2161_assignment.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2162_entry_minute_window.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2163_rotation.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_price_ta_indicators.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_stock_loader_coverage.py +0 -0
- {ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_vix_percentile_direction.py +0 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ivolatility_backtesting
|
|
3
|
+
Version: 2.164
|
|
4
|
+
Summary: A universal backtesting framework for financial strategies using the IVolatility API.
|
|
5
|
+
Author-email: IVolatility <support@ivolatility.com>
|
|
6
|
+
Project-URL: Homepage, https://ivolatility.com
|
|
7
|
+
Keywords: backtesting,finance,trading,ivolatility
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Requires-Python: >=3.8
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
Requires-Dist: pandas<3.0,>=1.5.0
|
|
19
|
+
Requires-Dist: numpy<3.0,>=1.21.0
|
|
20
|
+
Requires-Dist: matplotlib>=3.5.0
|
|
21
|
+
Requires-Dist: seaborn>=0.11.0
|
|
22
|
+
Requires-Dist: ivolatility>=1.9.6
|
|
23
|
+
Requires-Dist: psutil>=7.1.0
|
|
24
|
+
|
|
25
|
+
# IVolatility Backtesting Framework v1.32
|
|
26
|
+
|
|
27
|
+
A universal options backtesting framework powered by the IVolatility API.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Supported Strategies
|
|
32
|
+
|
|
33
|
+
| Strategy | Description | Use Case |
|
|
34
|
+
|----------|-------------|----------|
|
|
35
|
+
| **STRADDLE** | Long/short ATM call + put | Volatility plays |
|
|
36
|
+
| **STRANGLE** | Long/short OTM call + put | Wide volatility plays |
|
|
37
|
+
| **IRON_CONDOR** | Short strangle + long wings | Range-bound income |
|
|
38
|
+
| **VERTICAL** | Bull/bear call or put spreads | Directional bets |
|
|
39
|
+
| **CALENDAR** | Same strike, different expiry | Time decay plays |
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Core Features
|
|
44
|
+
|
|
45
|
+
### Data & Caching
|
|
46
|
+
- **EOD + Intraday bars** - Both timeframes supported for stocks & options
|
|
47
|
+
- **IVolatility API integration** - Options chains, underlying prices, IV data, earnings calendar
|
|
48
|
+
- **DuckDB caching** - Local storage for fast repeated backtests
|
|
49
|
+
- **ASYNC parallel loading** - ~10x faster data preload
|
|
50
|
+
- **Connection pooling** - ~5x faster API calls
|
|
51
|
+
|
|
52
|
+
### Run Modes
|
|
53
|
+
|
|
54
|
+
| Mode | Function | Use Case |
|
|
55
|
+
|------|----------|----------|
|
|
56
|
+
| **Single Run** | `run_backtest()` | Test one specific configuration |
|
|
57
|
+
| **Baseline** | `run_optimization(run_baseline=True)` | Reference benchmark (combo_id=0) |
|
|
58
|
+
| **Combinations** | `run_optimization()` | Grid search to find optimal params |
|
|
59
|
+
| **Chunked** | `run_optimization_chunked()` | Large grids with memory management |
|
|
60
|
+
|
|
61
|
+
#### Single Run
|
|
62
|
+
Run one backtest with fixed parameters. Use for testing a specific strategy configuration.
|
|
63
|
+
```python
|
|
64
|
+
results = run_backtest(strategy_fn, config)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
#### Baseline
|
|
68
|
+
Reference run using `base_config` values before testing combinations. Saved as `combo_id=0` for comparison.
|
|
69
|
+
```python
|
|
70
|
+
all_results = run_optimization(
|
|
71
|
+
base_config=config,
|
|
72
|
+
param_grid=param_grid,
|
|
73
|
+
run_baseline=True # combo_id=0 uses base_config values
|
|
74
|
+
)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
#### Combinations
|
|
78
|
+
Grid search across all parameter combinations. Each combo gets a unique `combo_id`.
|
|
79
|
+
```python
|
|
80
|
+
param_grid = {
|
|
81
|
+
'z_entry': [-2.0, -1.5, -1.0],
|
|
82
|
+
'z_exit': [0.5, 1.0],
|
|
83
|
+
'dte_target': [30, 45]
|
|
84
|
+
}
|
|
85
|
+
# Runs 3 × 2 × 2 = 12 combinations + baseline = 13 total
|
|
86
|
+
all_results = run_optimization(
|
|
87
|
+
base_config=config,
|
|
88
|
+
param_grid=param_grid,
|
|
89
|
+
run_baseline=True
|
|
90
|
+
)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
#### Chunked Optimization
|
|
94
|
+
Memory-efficient mode for large parameter spaces. Processes in batches.
|
|
95
|
+
```python
|
|
96
|
+
run_optimization_chunked(
|
|
97
|
+
base_config=config,
|
|
98
|
+
param_grid=large_grid, # 1000+ combinations
|
|
99
|
+
chunk_size=50,
|
|
100
|
+
run_baseline=True
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Supported Indicators
|
|
105
|
+
|
|
106
|
+
| Indicator | Source | Description |
|
|
107
|
+
|-----------|--------|-------------|
|
|
108
|
+
| `iv_rank` | Options | Current IV position in historical range (0-100) |
|
|
109
|
+
| `iv_rank_ivx` | IVX API | IV Rank from pre-calculated IVX data (faster) |
|
|
110
|
+
| `iv_percentile_ivx` | IVX API | IV Percentile from IVX data |
|
|
111
|
+
| `iv_lean_zscore` | Options | Call-Put IV spread normalized (mean reversion) |
|
|
112
|
+
| `iv_lean_zscore_ivx` | IVX API | IV Lean Z-score from IVX (faster) |
|
|
113
|
+
| `iv_term_structure` | IVX API | Volatility curve slope across tenors |
|
|
114
|
+
| `iv_skew` | Options | Put/Call IV skew at target delta |
|
|
115
|
+
| `vix_percentile` | VIX | VIX percentile rank over lookback |
|
|
116
|
+
| `realized_vol` | Stock | Historical volatility (annualized) |
|
|
117
|
+
|
|
118
|
+
### Entry Signals
|
|
119
|
+
- **Threshold-based** - Enter when indicator crosses level
|
|
120
|
+
- **Z-score signals** - Mean reversion entries
|
|
121
|
+
- **Delta-based selection** - Select strikes by delta target
|
|
122
|
+
- **Custom indicators** - Extensible via INDICATOR_REGISTRY
|
|
123
|
+
|
|
124
|
+
### Position & P&L Management
|
|
125
|
+
- **PositionManager** - Track open positions, calculate real-time P&L
|
|
126
|
+
- **Greeks tracking** - Delta, gamma, theta, vega per leg
|
|
127
|
+
- **Capital at risk** - 1.5x safety buffer for EOD backtests
|
|
128
|
+
- **Multi-leg support** - Spreads, condors, straddles
|
|
129
|
+
|
|
130
|
+
### Exit Management (StopLossManager)
|
|
131
|
+
- **DTE-based exit** - Close at target days to expiry
|
|
132
|
+
- **Stop-loss types:**
|
|
133
|
+
- Directional (underlying moves X%)
|
|
134
|
+
- P&L-based (position loses X%)
|
|
135
|
+
- Combined (both conditions required)
|
|
136
|
+
- **Profit targets** - Close at X% gain (same manager handles SL + PT)
|
|
137
|
+
- **Intraday monitoring** - Check stops on each bar
|
|
138
|
+
- **Earnings blackout** - Skip entries near earnings dates
|
|
139
|
+
|
|
140
|
+
### Analytics & Reporting
|
|
141
|
+
- **BacktestAnalyzer** - Sharpe ratio, max drawdown, win rate, profit factor
|
|
142
|
+
- **Equity curve** - Track portfolio value over time
|
|
143
|
+
- **ResultsReporter** - Generate summary tables and statistics
|
|
144
|
+
- **Trade-level details** - Entry/exit prices, Greeks, stop levels
|
|
145
|
+
|
|
146
|
+
### Visualization (ChartGenerator)
|
|
147
|
+
- **Equity curve charts** - Portfolio growth over time
|
|
148
|
+
- **Drawdown analysis** - Visualize underwater periods
|
|
149
|
+
- **Stop-loss analysis** - Compare exit reasons
|
|
150
|
+
- **Optimization heatmaps** - Parameter sensitivity
|
|
151
|
+
- **Monthly returns** - Calendar view of performance
|
|
152
|
+
|
|
153
|
+
### Optimization
|
|
154
|
+
- **Parameter grid search** - Test multiple configurations
|
|
155
|
+
- **Parallel execution** - Run combinations concurrently
|
|
156
|
+
- **Memory-efficient chunking** - Handle large parameter spaces
|
|
157
|
+
- **Results comparison** - Side-by-side analysis
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## Architecture
|
|
162
|
+
|
|
163
|
+
```
|
|
164
|
+
┌─────────────────────────────────────────────────────────┐
|
|
165
|
+
│ User Notebook │
|
|
166
|
+
├─────────────────────────────────────────────────────────┤
|
|
167
|
+
│ run_backtest() / run_backtest_with_stoploss() │
|
|
168
|
+
├──────────────┬──────────────┬───────────────────────────┤
|
|
169
|
+
│ PositionMgr │ StopLossMgr │ DuckDBIndicatorManager │
|
|
170
|
+
├──────────────┴──────────────┴───────────────────────────┤
|
|
171
|
+
│ OptionsChunkManager (async) │
|
|
172
|
+
├─────────────────────────────────────────────────────────┤
|
|
173
|
+
│ DuckDBCacheManager │
|
|
174
|
+
├─────────────────────────────────────────────────────────┤
|
|
175
|
+
│ APIManager → IVolatility API │
|
|
176
|
+
└─────────────────────────────────────────────────────────┘
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## Key Classes
|
|
182
|
+
|
|
183
|
+
| Class | Purpose |
|
|
184
|
+
|-------|---------|
|
|
185
|
+
| `APIManager` | Unified API access with auth |
|
|
186
|
+
| `DuckDBCacheManager` | Persistent data caching (EOD + intraday) |
|
|
187
|
+
| `OptionsChunkManager` | Async parallel data loading |
|
|
188
|
+
| `DuckDBIndicatorManager` | Pre-calculate & cache indicators |
|
|
189
|
+
| `PositionManager` | Track positions, calculate P&L, manage Greeks |
|
|
190
|
+
| `StopLossManager` | Monitor stops + profit targets (intraday capable) |
|
|
191
|
+
| `StrategyRegistry` | Strategy definitions & metadata |
|
|
192
|
+
| `BacktestAnalyzer` | Calculate metrics: Sharpe, drawdown, win rate |
|
|
193
|
+
| `ResultsReporter` | Generate summary tables & statistics |
|
|
194
|
+
| `ChartGenerator` | Create equity curves, heatmaps, analysis charts |
|
|
195
|
+
|
|
196
|
+
---
|
|
197
|
+
|
|
198
|
+
## Quick Start
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
from ivolatility_backtesting import run_backtest, preload_data
|
|
202
|
+
|
|
203
|
+
# Configure
|
|
204
|
+
config = {
|
|
205
|
+
'symbol': 'SPY',
|
|
206
|
+
'start_date': '2024-01-01',
|
|
207
|
+
'end_date': '2024-12-31',
|
|
208
|
+
'strategy_type': 'STRADDLE',
|
|
209
|
+
'dte_target': 30,
|
|
210
|
+
'entry_signal': 'iv_rank',
|
|
211
|
+
'entry_threshold': 50,
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
# Preload data (uses async for speed)
|
|
215
|
+
preloaded = preload_data(config)
|
|
216
|
+
|
|
217
|
+
# Run backtest
|
|
218
|
+
results = run_backtest(
|
|
219
|
+
strategy_function=straddle_strategy,
|
|
220
|
+
config={**config, **preloaded}
|
|
221
|
+
)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
---
|
|
225
|
+
|
|
226
|
+
## Performance
|
|
227
|
+
|
|
228
|
+
| Metric | Before v1.32 | After v1.32 |
|
|
229
|
+
|--------|--------------|-------------|
|
|
230
|
+
| Data preload | ~60s | ~6s (10x faster) |
|
|
231
|
+
| API calls | Sequential | Pooled (5x faster) |
|
|
232
|
+
| Memory usage | High | Chunked (stable) |
|
|
233
|
+
| DuckDB stability | Crashes | Legacy mode (stable) |
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## Integration with Claude
|
|
238
|
+
|
|
239
|
+
Use `system_straddle_simple_20260206.promt` as a system prompt to have Claude generate backtesting notebooks. Claude will:
|
|
240
|
+
|
|
241
|
+
1. Ask about strategy parameters
|
|
242
|
+
2. Generate complete notebook code
|
|
243
|
+
3. Include stop-loss/profit-target configuration
|
|
244
|
+
4. Add earnings blackout if requested
|
|
245
|
+
|
|
246
|
+
---
|
|
247
|
+
|
|
248
|
+
## Links
|
|
249
|
+
|
|
250
|
+
- **GitLab:** `gitlab.ivolatility.com/ivolatility/ivolatility-backtesting`
|
|
251
|
+
- **API Docs:** `ivolatility.com/api/openapi.yml`
|
|
252
|
+
- **Changelog:** See `CHANGELOG.md` in repo
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# IVolatility Backtesting Framework v1.32
|
|
2
|
+
|
|
3
|
+
A universal options backtesting framework powered by the IVolatility API.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Supported Strategies
|
|
8
|
+
|
|
9
|
+
| Strategy | Description | Use Case |
|
|
10
|
+
|----------|-------------|----------|
|
|
11
|
+
| **STRADDLE** | Long/short ATM call + put | Volatility plays |
|
|
12
|
+
| **STRANGLE** | Long/short OTM call + put | Wide volatility plays |
|
|
13
|
+
| **IRON_CONDOR** | Short strangle + long wings | Range-bound income |
|
|
14
|
+
| **VERTICAL** | Bull/bear call or put spreads | Directional bets |
|
|
15
|
+
| **CALENDAR** | Same strike, different expiry | Time decay plays |
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Core Features
|
|
20
|
+
|
|
21
|
+
### Data & Caching
|
|
22
|
+
- **EOD + Intraday bars** - Both timeframes supported for stocks & options
|
|
23
|
+
- **IVolatility API integration** - Options chains, underlying prices, IV data, earnings calendar
|
|
24
|
+
- **DuckDB caching** - Local storage for fast repeated backtests
|
|
25
|
+
- **ASYNC parallel loading** - ~10x faster data preload
|
|
26
|
+
- **Connection pooling** - ~5x faster API calls
|
|
27
|
+
|
|
28
|
+
### Run Modes
|
|
29
|
+
|
|
30
|
+
| Mode | Function | Use Case |
|
|
31
|
+
|------|----------|----------|
|
|
32
|
+
| **Single Run** | `run_backtest()` | Test one specific configuration |
|
|
33
|
+
| **Baseline** | `run_optimization(run_baseline=True)` | Reference benchmark (combo_id=0) |
|
|
34
|
+
| **Combinations** | `run_optimization()` | Grid search to find optimal params |
|
|
35
|
+
| **Chunked** | `run_optimization_chunked()` | Large grids with memory management |
|
|
36
|
+
|
|
37
|
+
#### Single Run
|
|
38
|
+
Run one backtest with fixed parameters. Use for testing a specific strategy configuration.
|
|
39
|
+
```python
|
|
40
|
+
results = run_backtest(strategy_fn, config)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
#### Baseline
|
|
44
|
+
Reference run using `base_config` values before testing combinations. Saved as `combo_id=0` for comparison.
|
|
45
|
+
```python
|
|
46
|
+
all_results = run_optimization(
|
|
47
|
+
base_config=config,
|
|
48
|
+
param_grid=param_grid,
|
|
49
|
+
run_baseline=True # combo_id=0 uses base_config values
|
|
50
|
+
)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
#### Combinations
|
|
54
|
+
Grid search across all parameter combinations. Each combo gets a unique `combo_id`.
|
|
55
|
+
```python
|
|
56
|
+
param_grid = {
|
|
57
|
+
'z_entry': [-2.0, -1.5, -1.0],
|
|
58
|
+
'z_exit': [0.5, 1.0],
|
|
59
|
+
'dte_target': [30, 45]
|
|
60
|
+
}
|
|
61
|
+
# Runs 3 × 2 × 2 = 12 combinations + baseline = 13 total
|
|
62
|
+
all_results = run_optimization(
|
|
63
|
+
base_config=config,
|
|
64
|
+
param_grid=param_grid,
|
|
65
|
+
run_baseline=True
|
|
66
|
+
)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
#### Chunked Optimization
|
|
70
|
+
Memory-efficient mode for large parameter spaces. Processes in batches.
|
|
71
|
+
```python
|
|
72
|
+
run_optimization_chunked(
|
|
73
|
+
base_config=config,
|
|
74
|
+
param_grid=large_grid, # 1000+ combinations
|
|
75
|
+
chunk_size=50,
|
|
76
|
+
run_baseline=True
|
|
77
|
+
)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Supported Indicators
|
|
81
|
+
|
|
82
|
+
| Indicator | Source | Description |
|
|
83
|
+
|-----------|--------|-------------|
|
|
84
|
+
| `iv_rank` | Options | Current IV position in historical range (0-100) |
|
|
85
|
+
| `iv_rank_ivx` | IVX API | IV Rank from pre-calculated IVX data (faster) |
|
|
86
|
+
| `iv_percentile_ivx` | IVX API | IV Percentile from IVX data |
|
|
87
|
+
| `iv_lean_zscore` | Options | Call-Put IV spread normalized (mean reversion) |
|
|
88
|
+
| `iv_lean_zscore_ivx` | IVX API | IV Lean Z-score from IVX (faster) |
|
|
89
|
+
| `iv_term_structure` | IVX API | Volatility curve slope across tenors |
|
|
90
|
+
| `iv_skew` | Options | Put/Call IV skew at target delta |
|
|
91
|
+
| `vix_percentile` | VIX | VIX percentile rank over lookback |
|
|
92
|
+
| `realized_vol` | Stock | Historical volatility (annualized) |
|
|
93
|
+
|
|
94
|
+
### Entry Signals
|
|
95
|
+
- **Threshold-based** - Enter when indicator crosses level
|
|
96
|
+
- **Z-score signals** - Mean reversion entries
|
|
97
|
+
- **Delta-based selection** - Select strikes by delta target
|
|
98
|
+
- **Custom indicators** - Extensible via INDICATOR_REGISTRY
|
|
99
|
+
|
|
100
|
+
### Position & P&L Management
|
|
101
|
+
- **PositionManager** - Track open positions, calculate real-time P&L
|
|
102
|
+
- **Greeks tracking** - Delta, gamma, theta, vega per leg
|
|
103
|
+
- **Capital at risk** - 1.5x safety buffer for EOD backtests
|
|
104
|
+
- **Multi-leg support** - Spreads, condors, straddles
|
|
105
|
+
|
|
106
|
+
### Exit Management (StopLossManager)
|
|
107
|
+
- **DTE-based exit** - Close at target days to expiry
|
|
108
|
+
- **Stop-loss types:**
|
|
109
|
+
- Directional (underlying moves X%)
|
|
110
|
+
- P&L-based (position loses X%)
|
|
111
|
+
- Combined (both conditions required)
|
|
112
|
+
- **Profit targets** - Close at X% gain (same manager handles SL + PT)
|
|
113
|
+
- **Intraday monitoring** - Check stops on each bar
|
|
114
|
+
- **Earnings blackout** - Skip entries near earnings dates
|
|
115
|
+
|
|
116
|
+
### Analytics & Reporting
|
|
117
|
+
- **BacktestAnalyzer** - Sharpe ratio, max drawdown, win rate, profit factor
|
|
118
|
+
- **Equity curve** - Track portfolio value over time
|
|
119
|
+
- **ResultsReporter** - Generate summary tables and statistics
|
|
120
|
+
- **Trade-level details** - Entry/exit prices, Greeks, stop levels
|
|
121
|
+
|
|
122
|
+
### Visualization (ChartGenerator)
|
|
123
|
+
- **Equity curve charts** - Portfolio growth over time
|
|
124
|
+
- **Drawdown analysis** - Visualize underwater periods
|
|
125
|
+
- **Stop-loss analysis** - Compare exit reasons
|
|
126
|
+
- **Optimization heatmaps** - Parameter sensitivity
|
|
127
|
+
- **Monthly returns** - Calendar view of performance
|
|
128
|
+
|
|
129
|
+
### Optimization
|
|
130
|
+
- **Parameter grid search** - Test multiple configurations
|
|
131
|
+
- **Parallel execution** - Run combinations concurrently
|
|
132
|
+
- **Memory-efficient chunking** - Handle large parameter spaces
|
|
133
|
+
- **Results comparison** - Side-by-side analysis
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## Architecture
|
|
138
|
+
|
|
139
|
+
```
|
|
140
|
+
┌─────────────────────────────────────────────────────────┐
|
|
141
|
+
│ User Notebook │
|
|
142
|
+
├─────────────────────────────────────────────────────────┤
|
|
143
|
+
│ run_backtest() / run_backtest_with_stoploss() │
|
|
144
|
+
├──────────────┬──────────────┬───────────────────────────┤
|
|
145
|
+
│ PositionMgr │ StopLossMgr │ DuckDBIndicatorManager │
|
|
146
|
+
├──────────────┴──────────────┴───────────────────────────┤
|
|
147
|
+
│ OptionsChunkManager (async) │
|
|
148
|
+
├─────────────────────────────────────────────────────────┤
|
|
149
|
+
│ DuckDBCacheManager │
|
|
150
|
+
├─────────────────────────────────────────────────────────┤
|
|
151
|
+
│ APIManager → IVolatility API │
|
|
152
|
+
└─────────────────────────────────────────────────────────┘
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## Key Classes
|
|
158
|
+
|
|
159
|
+
| Class | Purpose |
|
|
160
|
+
|-------|---------|
|
|
161
|
+
| `APIManager` | Unified API access with auth |
|
|
162
|
+
| `DuckDBCacheManager` | Persistent data caching (EOD + intraday) |
|
|
163
|
+
| `OptionsChunkManager` | Async parallel data loading |
|
|
164
|
+
| `DuckDBIndicatorManager` | Pre-calculate & cache indicators |
|
|
165
|
+
| `PositionManager` | Track positions, calculate P&L, manage Greeks |
|
|
166
|
+
| `StopLossManager` | Monitor stops + profit targets (intraday capable) |
|
|
167
|
+
| `StrategyRegistry` | Strategy definitions & metadata |
|
|
168
|
+
| `BacktestAnalyzer` | Calculate metrics: Sharpe, drawdown, win rate |
|
|
169
|
+
| `ResultsReporter` | Generate summary tables & statistics |
|
|
170
|
+
| `ChartGenerator` | Create equity curves, heatmaps, analysis charts |
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
## Quick Start
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
from ivolatility_backtesting import run_backtest, preload_data
|
|
178
|
+
|
|
179
|
+
# Configure
|
|
180
|
+
config = {
|
|
181
|
+
'symbol': 'SPY',
|
|
182
|
+
'start_date': '2024-01-01',
|
|
183
|
+
'end_date': '2024-12-31',
|
|
184
|
+
'strategy_type': 'STRADDLE',
|
|
185
|
+
'dte_target': 30,
|
|
186
|
+
'entry_signal': 'iv_rank',
|
|
187
|
+
'entry_threshold': 50,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
# Preload data (uses async for speed)
|
|
191
|
+
preloaded = preload_data(config)
|
|
192
|
+
|
|
193
|
+
# Run backtest
|
|
194
|
+
results = run_backtest(
|
|
195
|
+
strategy_function=straddle_strategy,
|
|
196
|
+
config={**config, **preloaded}
|
|
197
|
+
)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
---
|
|
201
|
+
|
|
202
|
+
## Performance
|
|
203
|
+
|
|
204
|
+
| Metric | Before v1.32 | After v1.32 |
|
|
205
|
+
|--------|--------------|-------------|
|
|
206
|
+
| Data preload | ~60s | ~6s (10x faster) |
|
|
207
|
+
| API calls | Sequential | Pooled (5x faster) |
|
|
208
|
+
| Memory usage | High | Chunked (stable) |
|
|
209
|
+
| DuckDB stability | Crashes | Legacy mode (stable) |
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
## Integration with Claude
|
|
214
|
+
|
|
215
|
+
Use `system_straddle_simple_20260206.promt` as a system prompt to have Claude generate backtesting notebooks. Claude will:
|
|
216
|
+
|
|
217
|
+
1. Ask about strategy parameters
|
|
218
|
+
2. Generate complete notebook code
|
|
219
|
+
3. Include stop-loss/profit-target configuration
|
|
220
|
+
4. Add earnings blackout if requested
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## Links
|
|
225
|
+
|
|
226
|
+
- **GitLab:** `gitlab.ivolatility.com/ivolatility/ivolatility-backtesting`
|
|
227
|
+
- **API Docs:** `ivolatility.com/api/openapi.yml`
|
|
228
|
+
- **Changelog:** See `CHANGELOG.md` in repo
|
|
@@ -14333,11 +14333,14 @@ class PositionManager:
|
|
|
14333
14333
|
'symbol': position.get('symbol')
|
|
14334
14334
|
}
|
|
14335
14335
|
|
|
14336
|
+
_st = position.get('strategy_type', 'LONG')
|
|
14337
|
+
if _st in STOCK_STRATEGY_TYPES:
|
|
14338
|
+
_st = 'SHORT' if _st in SHORT_STOCK_TYPES else 'LONG'
|
|
14336
14339
|
triggered, stop_level, stop_type, intraday_data = self.sl_manager.check_stop(
|
|
14337
14340
|
position_id=position_id,
|
|
14338
14341
|
current_price=check_value,
|
|
14339
14342
|
current_date=current_date,
|
|
14340
|
-
position_type=
|
|
14343
|
+
position_type=_st,
|
|
14341
14344
|
**stop_kwargs
|
|
14342
14345
|
)
|
|
14343
14346
|
|
|
@@ -14827,6 +14830,7 @@ class PositionManager:
|
|
|
14827
14830
|
pnl_pct = (pnl / entry_cost * 100) if entry_cost > 0 else 0
|
|
14828
14831
|
price_data[pos_id] = {
|
|
14829
14832
|
'current_price': stock_price,
|
|
14833
|
+
'price': stock_price,
|
|
14830
14834
|
'pnl': pnl,
|
|
14831
14835
|
'pnl_pct': pnl_pct,
|
|
14832
14836
|
'underlying_price': stock_price,
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ivolatility_backtesting
|
|
3
|
+
Version: 2.164
|
|
4
|
+
Summary: A universal backtesting framework for financial strategies using the IVolatility API.
|
|
5
|
+
Author-email: IVolatility <support@ivolatility.com>
|
|
6
|
+
Project-URL: Homepage, https://ivolatility.com
|
|
7
|
+
Keywords: backtesting,finance,trading,ivolatility
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Requires-Python: >=3.8
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
Requires-Dist: pandas<3.0,>=1.5.0
|
|
19
|
+
Requires-Dist: numpy<3.0,>=1.21.0
|
|
20
|
+
Requires-Dist: matplotlib>=3.5.0
|
|
21
|
+
Requires-Dist: seaborn>=0.11.0
|
|
22
|
+
Requires-Dist: ivolatility>=1.9.6
|
|
23
|
+
Requires-Dist: psutil>=7.1.0
|
|
24
|
+
|
|
25
|
+
# IVolatility Backtesting Framework v1.32
|
|
26
|
+
|
|
27
|
+
A universal options backtesting framework powered by the IVolatility API.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Supported Strategies
|
|
32
|
+
|
|
33
|
+
| Strategy | Description | Use Case |
|
|
34
|
+
|----------|-------------|----------|
|
|
35
|
+
| **STRADDLE** | Long/short ATM call + put | Volatility plays |
|
|
36
|
+
| **STRANGLE** | Long/short OTM call + put | Wide volatility plays |
|
|
37
|
+
| **IRON_CONDOR** | Short strangle + long wings | Range-bound income |
|
|
38
|
+
| **VERTICAL** | Bull/bear call or put spreads | Directional bets |
|
|
39
|
+
| **CALENDAR** | Same strike, different expiry | Time decay plays |
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Core Features
|
|
44
|
+
|
|
45
|
+
### Data & Caching
|
|
46
|
+
- **EOD + Intraday bars** - Both timeframes supported for stocks & options
|
|
47
|
+
- **IVolatility API integration** - Options chains, underlying prices, IV data, earnings calendar
|
|
48
|
+
- **DuckDB caching** - Local storage for fast repeated backtests
|
|
49
|
+
- **ASYNC parallel loading** - ~10x faster data preload
|
|
50
|
+
- **Connection pooling** - ~5x faster API calls
|
|
51
|
+
|
|
52
|
+
### Run Modes
|
|
53
|
+
|
|
54
|
+
| Mode | Function | Use Case |
|
|
55
|
+
|------|----------|----------|
|
|
56
|
+
| **Single Run** | `run_backtest()` | Test one specific configuration |
|
|
57
|
+
| **Baseline** | `run_optimization(run_baseline=True)` | Reference benchmark (combo_id=0) |
|
|
58
|
+
| **Combinations** | `run_optimization()` | Grid search to find optimal params |
|
|
59
|
+
| **Chunked** | `run_optimization_chunked()` | Large grids with memory management |
|
|
60
|
+
|
|
61
|
+
#### Single Run
|
|
62
|
+
Run one backtest with fixed parameters. Use for testing a specific strategy configuration.
|
|
63
|
+
```python
|
|
64
|
+
results = run_backtest(strategy_fn, config)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
#### Baseline
|
|
68
|
+
Reference run using `base_config` values before testing combinations. Saved as `combo_id=0` for comparison.
|
|
69
|
+
```python
|
|
70
|
+
all_results = run_optimization(
|
|
71
|
+
base_config=config,
|
|
72
|
+
param_grid=param_grid,
|
|
73
|
+
run_baseline=True # combo_id=0 uses base_config values
|
|
74
|
+
)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
#### Combinations
|
|
78
|
+
Grid search across all parameter combinations. Each combo gets a unique `combo_id`.
|
|
79
|
+
```python
|
|
80
|
+
param_grid = {
|
|
81
|
+
'z_entry': [-2.0, -1.5, -1.0],
|
|
82
|
+
'z_exit': [0.5, 1.0],
|
|
83
|
+
'dte_target': [30, 45]
|
|
84
|
+
}
|
|
85
|
+
# Runs 3 × 2 × 2 = 12 combinations + baseline = 13 total
|
|
86
|
+
all_results = run_optimization(
|
|
87
|
+
base_config=config,
|
|
88
|
+
param_grid=param_grid,
|
|
89
|
+
run_baseline=True
|
|
90
|
+
)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
#### Chunked Optimization
|
|
94
|
+
Memory-efficient mode for large parameter spaces. Processes in batches.
|
|
95
|
+
```python
|
|
96
|
+
run_optimization_chunked(
|
|
97
|
+
base_config=config,
|
|
98
|
+
param_grid=large_grid, # 1000+ combinations
|
|
99
|
+
chunk_size=50,
|
|
100
|
+
run_baseline=True
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Supported Indicators
|
|
105
|
+
|
|
106
|
+
| Indicator | Source | Description |
|
|
107
|
+
|-----------|--------|-------------|
|
|
108
|
+
| `iv_rank` | Options | Current IV position in historical range (0-100) |
|
|
109
|
+
| `iv_rank_ivx` | IVX API | IV Rank from pre-calculated IVX data (faster) |
|
|
110
|
+
| `iv_percentile_ivx` | IVX API | IV Percentile from IVX data |
|
|
111
|
+
| `iv_lean_zscore` | Options | Call-Put IV spread normalized (mean reversion) |
|
|
112
|
+
| `iv_lean_zscore_ivx` | IVX API | IV Lean Z-score from IVX (faster) |
|
|
113
|
+
| `iv_term_structure` | IVX API | Volatility curve slope across tenors |
|
|
114
|
+
| `iv_skew` | Options | Put/Call IV skew at target delta |
|
|
115
|
+
| `vix_percentile` | VIX | VIX percentile rank over lookback |
|
|
116
|
+
| `realized_vol` | Stock | Historical volatility (annualized) |
|
|
117
|
+
|
|
118
|
+
### Entry Signals
|
|
119
|
+
- **Threshold-based** - Enter when indicator crosses level
|
|
120
|
+
- **Z-score signals** - Mean reversion entries
|
|
121
|
+
- **Delta-based selection** - Select strikes by delta target
|
|
122
|
+
- **Custom indicators** - Extensible via INDICATOR_REGISTRY
|
|
123
|
+
|
|
124
|
+
### Position & P&L Management
|
|
125
|
+
- **PositionManager** - Track open positions, calculate real-time P&L
|
|
126
|
+
- **Greeks tracking** - Delta, gamma, theta, vega per leg
|
|
127
|
+
- **Capital at risk** - 1.5x safety buffer for EOD backtests
|
|
128
|
+
- **Multi-leg support** - Spreads, condors, straddles
|
|
129
|
+
|
|
130
|
+
### Exit Management (StopLossManager)
|
|
131
|
+
- **DTE-based exit** - Close at target days to expiry
|
|
132
|
+
- **Stop-loss types:**
|
|
133
|
+
- Directional (underlying moves X%)
|
|
134
|
+
- P&L-based (position loses X%)
|
|
135
|
+
- Combined (both conditions required)
|
|
136
|
+
- **Profit targets** - Close at X% gain (same manager handles SL + PT)
|
|
137
|
+
- **Intraday monitoring** - Check stops on each bar
|
|
138
|
+
- **Earnings blackout** - Skip entries near earnings dates
|
|
139
|
+
|
|
140
|
+
### Analytics & Reporting
|
|
141
|
+
- **BacktestAnalyzer** - Sharpe ratio, max drawdown, win rate, profit factor
|
|
142
|
+
- **Equity curve** - Track portfolio value over time
|
|
143
|
+
- **ResultsReporter** - Generate summary tables and statistics
|
|
144
|
+
- **Trade-level details** - Entry/exit prices, Greeks, stop levels
|
|
145
|
+
|
|
146
|
+
### Visualization (ChartGenerator)
|
|
147
|
+
- **Equity curve charts** - Portfolio growth over time
|
|
148
|
+
- **Drawdown analysis** - Visualize underwater periods
|
|
149
|
+
- **Stop-loss analysis** - Compare exit reasons
|
|
150
|
+
- **Optimization heatmaps** - Parameter sensitivity
|
|
151
|
+
- **Monthly returns** - Calendar view of performance
|
|
152
|
+
|
|
153
|
+
### Optimization
|
|
154
|
+
- **Parameter grid search** - Test multiple configurations
|
|
155
|
+
- **Parallel execution** - Run combinations concurrently
|
|
156
|
+
- **Memory-efficient chunking** - Handle large parameter spaces
|
|
157
|
+
- **Results comparison** - Side-by-side analysis
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## Architecture
|
|
162
|
+
|
|
163
|
+
```
|
|
164
|
+
┌─────────────────────────────────────────────────────────┐
|
|
165
|
+
│ User Notebook │
|
|
166
|
+
├─────────────────────────────────────────────────────────┤
|
|
167
|
+
│ run_backtest() / run_backtest_with_stoploss() │
|
|
168
|
+
├──────────────┬──────────────┬───────────────────────────┤
|
|
169
|
+
│ PositionMgr │ StopLossMgr │ DuckDBIndicatorManager │
|
|
170
|
+
├──────────────┴──────────────┴───────────────────────────┤
|
|
171
|
+
│ OptionsChunkManager (async) │
|
|
172
|
+
├─────────────────────────────────────────────────────────┤
|
|
173
|
+
│ DuckDBCacheManager │
|
|
174
|
+
├─────────────────────────────────────────────────────────┤
|
|
175
|
+
│ APIManager → IVolatility API │
|
|
176
|
+
└─────────────────────────────────────────────────────────┘
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## Key Classes
|
|
182
|
+
|
|
183
|
+
| Class | Purpose |
|
|
184
|
+
|-------|---------|
|
|
185
|
+
| `APIManager` | Unified API access with auth |
|
|
186
|
+
| `DuckDBCacheManager` | Persistent data caching (EOD + intraday) |
|
|
187
|
+
| `OptionsChunkManager` | Async parallel data loading |
|
|
188
|
+
| `DuckDBIndicatorManager` | Pre-calculate & cache indicators |
|
|
189
|
+
| `PositionManager` | Track positions, calculate P&L, manage Greeks |
|
|
190
|
+
| `StopLossManager` | Monitor stops + profit targets (intraday capable) |
|
|
191
|
+
| `StrategyRegistry` | Strategy definitions & metadata |
|
|
192
|
+
| `BacktestAnalyzer` | Calculate metrics: Sharpe, drawdown, win rate |
|
|
193
|
+
| `ResultsReporter` | Generate summary tables & statistics |
|
|
194
|
+
| `ChartGenerator` | Create equity curves, heatmaps, analysis charts |
|
|
195
|
+
|
|
196
|
+
---
|
|
197
|
+
|
|
198
|
+
## Quick Start
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
from ivolatility_backtesting import run_backtest, preload_data
|
|
202
|
+
|
|
203
|
+
# Configure
|
|
204
|
+
config = {
|
|
205
|
+
'symbol': 'SPY',
|
|
206
|
+
'start_date': '2024-01-01',
|
|
207
|
+
'end_date': '2024-12-31',
|
|
208
|
+
'strategy_type': 'STRADDLE',
|
|
209
|
+
'dte_target': 30,
|
|
210
|
+
'entry_signal': 'iv_rank',
|
|
211
|
+
'entry_threshold': 50,
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
# Preload data (uses async for speed)
|
|
215
|
+
preloaded = preload_data(config)
|
|
216
|
+
|
|
217
|
+
# Run backtest
|
|
218
|
+
results = run_backtest(
|
|
219
|
+
strategy_function=straddle_strategy,
|
|
220
|
+
config={**config, **preloaded}
|
|
221
|
+
)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
---
|
|
225
|
+
|
|
226
|
+
## Performance
|
|
227
|
+
|
|
228
|
+
| Metric | Before v1.32 | After v1.32 |
|
|
229
|
+
|--------|--------------|-------------|
|
|
230
|
+
| Data preload | ~60s | ~6s (10x faster) |
|
|
231
|
+
| API calls | Sequential | Pooled (5x faster) |
|
|
232
|
+
| Memory usage | High | Chunked (stable) |
|
|
233
|
+
| DuckDB stability | Crashes | Legacy mode (stable) |
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## Integration with Claude
|
|
238
|
+
|
|
239
|
+
Use `system_straddle_simple_20260206.promt` as a system prompt to have Claude generate backtesting notebooks. Claude will:
|
|
240
|
+
|
|
241
|
+
1. Ask about strategy parameters
|
|
242
|
+
2. Generate complete notebook code
|
|
243
|
+
3. Include stop-loss/profit-target configuration
|
|
244
|
+
4. Add earnings blackout if requested
|
|
245
|
+
|
|
246
|
+
---
|
|
247
|
+
|
|
248
|
+
## Links
|
|
249
|
+
|
|
250
|
+
- **GitLab:** `gitlab.ivolatility.com/ivolatility/ivolatility-backtesting`
|
|
251
|
+
- **API Docs:** `ivolatility.com/api/openapi.yml`
|
|
252
|
+
- **Changelog:** See `CHANGELOG.md` in repo
|
|
@@ -36,6 +36,7 @@ tests/test_2160_prefetch_cancel.py
|
|
|
36
36
|
tests/test_2161_assignment.py
|
|
37
37
|
tests/test_2162_entry_minute_window.py
|
|
38
38
|
tests/test_2163_rotation.py
|
|
39
|
+
tests/test_2164_stock_price_stops.py
|
|
39
40
|
tests/test_price_ta_indicators.py
|
|
40
41
|
tests/test_stock_loader_coverage.py
|
|
41
42
|
tests/test_vix_percentile_direction.py
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "ivolatility_backtesting"
|
|
7
|
-
version = "2.
|
|
7
|
+
version = "2.164"
|
|
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,64 @@
|
|
|
1
|
+
"""Price stops (trailing, fixed_pct) on stock positions: the stock price reaches the stop check and a long is a long.
|
|
2
|
+
Run: pytest tests/test_2164_stock_price_stops.py. No network. IVB_LIB_DIR overrides the library folder."""
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
_TESTS = os.path.dirname(os.path.abspath(__file__))
|
|
9
|
+
sys.path.insert(0, _TESTS)
|
|
10
|
+
from test_2158_entry_time import lib # noqa: E402
|
|
11
|
+
|
|
12
|
+
PRICES = [100, 105, 110, 104, 100, 96, 90, 85]
|
|
13
|
+
DATES = pd.bdate_range('2024-01-02', periods=len(PRICES))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _run(strategy_type, stop_cfg, prices=PRICES):
|
|
17
|
+
stop_cfg = dict(stop_cfg, intraday_settings={'intraday_mode': 'disabled'})
|
|
18
|
+
cfg = {'symbol': 'SPY', 'strategy_type': strategy_type, 'initial_capital': 100_000, 'stop_loss_enabled': True,
|
|
19
|
+
'stop_loss_config': stop_cfg, 'debuginfo': 0, 'start_date': '2024-01-02', 'end_date': '2024-01-31'}
|
|
20
|
+
pm = lib.PositionManager(cfg, debug=False)
|
|
21
|
+
for i, (d, p) in enumerate(zip(DATES, prices)):
|
|
22
|
+
row = pd.DataFrame([{'date': d, 'close': p, 'open': p, 'high': p, 'low': p, 'price': p}])
|
|
23
|
+
pdata = pm.build_price_data(d, float(p), pd.DataFrame(), lambda s, e, t: None, stock_row=row)
|
|
24
|
+
fired = pm.check_positions(d, pdata)
|
|
25
|
+
if fired:
|
|
26
|
+
return i, p
|
|
27
|
+
if i == 0:
|
|
28
|
+
short = strategy_type in lib.SHORT_STOCK_TYPES
|
|
29
|
+
pm.open_position(position_id='t', strategy_type=strategy_type, symbol='SPY', entry_date=d,
|
|
30
|
+
entry_price=float(p), entry_max_risk=p * 100, quantity=100, contracts=0,
|
|
31
|
+
total_cost=p * 100, is_short_bias=short, position_type='SHORT' if short else 'LONG',
|
|
32
|
+
underlying_entry_price=float(p))
|
|
33
|
+
return None, None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_stock_price_reaches_the_stop_check():
|
|
37
|
+
pm = lib.PositionManager({'symbol': 'SPY', 'strategy_type': 'DIRECTIONAL_LONG', 'debuginfo': 0}, debug=False)
|
|
38
|
+
pm.open_position(position_id='t', strategy_type='DIRECTIONAL_LONG', symbol='SPY', entry_date=DATES[0],
|
|
39
|
+
entry_price=100.0, entry_max_risk=10_000, quantity=100, contracts=0, total_cost=10_000,
|
|
40
|
+
is_short_bias=False, position_type='LONG', underlying_entry_price=100.0)
|
|
41
|
+
row = pd.DataFrame([{'date': DATES[1], 'close': 105, 'open': 105, 'high': 105, 'low': 105, 'price': 105}])
|
|
42
|
+
pdata = pm.build_price_data(DATES[1], 105.0, pd.DataFrame(), lambda s, e, t: None, stock_row=row)
|
|
43
|
+
assert pdata['t']['price'] == 105.0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_trailing_stop_on_long_stock_fires_five_pct_below_the_peak():
|
|
47
|
+
assert _run('DIRECTIONAL_LONG', {'type': 'trailing', 'value': 0.05}) == (3, 104)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_trailing_stop_on_long_stock_does_not_fire_on_the_rise():
|
|
51
|
+
day, _ = _run('DIRECTIONAL_LONG', {'type': 'trailing', 'value': 0.05}, prices=[100, 105, 110, 116, 120])
|
|
52
|
+
assert day is None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_fixed_pct_stop_on_long_stock_fires_five_pct_below_entry():
|
|
56
|
+
assert _run('DIRECTIONAL_LONG', {'type': 'fixed_pct', 'value': 0.05}) == (6, 90)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_trailing_stop_on_short_stock_fires_on_the_rise():
|
|
60
|
+
assert _run('DIRECTIONAL_SHORT', {'type': 'trailing', 'value': 0.05}, prices=[100, 96, 90, 95, 100]) == (3, 95)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_pl_loss_stop_on_long_stock_unchanged():
|
|
64
|
+
assert _run('DIRECTIONAL_LONG', {'type': 'pl_loss', 'pl_loss_settings': {'pl_loss': 0.05}}) == (6, 90)
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: ivolatility_backtesting
|
|
3
|
-
Version: 2.163
|
|
4
|
-
Summary: A universal backtesting framework for financial strategies using the IVolatility API.
|
|
5
|
-
Author-email: IVolatility <support@ivolatility.com>
|
|
6
|
-
Project-URL: Homepage, https://ivolatility.com
|
|
7
|
-
Keywords: backtesting,finance,trading,ivolatility
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
10
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
11
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
-
Classifier: Operating System :: OS Independent
|
|
16
|
-
Requires-Python: >=3.8
|
|
17
|
-
Description-Content-Type: text/markdown
|
|
18
|
-
Requires-Dist: pandas<3.0,>=1.5.0
|
|
19
|
-
Requires-Dist: numpy<3.0,>=1.21.0
|
|
20
|
-
Requires-Dist: matplotlib>=3.5.0
|
|
21
|
-
Requires-Dist: seaborn>=0.11.0
|
|
22
|
-
Requires-Dist: ivolatility>=1.9.6
|
|
23
|
-
Requires-Dist: psutil>=7.1.0
|
|
24
|
-
|
|
25
|
-
# IVolatility Backtesting
|
|
26
|
-
A universal backtesting framework for financial strategies using the IVolatility API.
|
|
27
|
-
|
|
28
|
-
## Installation
|
|
29
|
-
```bash
|
|
30
|
-
pip install ivolatility_backtesting
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
## Usage
|
|
34
|
-
```python
|
|
35
|
-
from ivolatility_backtesting import run_backtest, init_api
|
|
36
|
-
|
|
37
|
-
# Initialize API
|
|
38
|
-
init_api("your-api-key")
|
|
39
|
-
|
|
40
|
-
# Define your strategy
|
|
41
|
-
def my_strategy(config):
|
|
42
|
-
# Strategy logic
|
|
43
|
-
return BacktestResults(
|
|
44
|
-
equity_curve=[100000, 110000],
|
|
45
|
-
equity_dates=["2023-01-01", "2023-01-02"],
|
|
46
|
-
trades=[{"pnl": 1000, "entry_date": "2023-01-01", "exit_date": "2023-01-02"}],
|
|
47
|
-
initial_capital=100000,
|
|
48
|
-
config=config
|
|
49
|
-
)
|
|
50
|
-
|
|
51
|
-
# Run backtest
|
|
52
|
-
CONFIG = {
|
|
53
|
-
"initial_capital": 100000,
|
|
54
|
-
"start_date": "2023-01-01",
|
|
55
|
-
"end_date": "2024-01-01",
|
|
56
|
-
"strategy_name": "My Strategy"
|
|
57
|
-
}
|
|
58
|
-
analyzer = run_backtest(my_strategy, CONFIG)
|
|
59
|
-
|
|
60
|
-
# Access metrics
|
|
61
|
-
print(f"Sharpe Ratio: {analyzer.metrics['sharpe']:.2f}")
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
## Requirements
|
|
65
|
-
- Python >= 3.8
|
|
66
|
-
- pandas >= 1.5.0
|
|
67
|
-
- numpy >= 1.21.0
|
|
68
|
-
- matplotlib >= 3.5.0
|
|
69
|
-
- seaborn >= 0.11.0
|
|
70
|
-
- ivolatility >= 1.8.2
|
|
71
|
-
|
|
72
|
-
## Test CI
|
|
73
|
-
## Test CI1
|
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
# IVolatility Backtesting
|
|
2
|
-
A universal backtesting framework for financial strategies using the IVolatility API.
|
|
3
|
-
|
|
4
|
-
## Installation
|
|
5
|
-
```bash
|
|
6
|
-
pip install ivolatility_backtesting
|
|
7
|
-
```
|
|
8
|
-
|
|
9
|
-
## Usage
|
|
10
|
-
```python
|
|
11
|
-
from ivolatility_backtesting import run_backtest, init_api
|
|
12
|
-
|
|
13
|
-
# Initialize API
|
|
14
|
-
init_api("your-api-key")
|
|
15
|
-
|
|
16
|
-
# Define your strategy
|
|
17
|
-
def my_strategy(config):
|
|
18
|
-
# Strategy logic
|
|
19
|
-
return BacktestResults(
|
|
20
|
-
equity_curve=[100000, 110000],
|
|
21
|
-
equity_dates=["2023-01-01", "2023-01-02"],
|
|
22
|
-
trades=[{"pnl": 1000, "entry_date": "2023-01-01", "exit_date": "2023-01-02"}],
|
|
23
|
-
initial_capital=100000,
|
|
24
|
-
config=config
|
|
25
|
-
)
|
|
26
|
-
|
|
27
|
-
# Run backtest
|
|
28
|
-
CONFIG = {
|
|
29
|
-
"initial_capital": 100000,
|
|
30
|
-
"start_date": "2023-01-01",
|
|
31
|
-
"end_date": "2024-01-01",
|
|
32
|
-
"strategy_name": "My Strategy"
|
|
33
|
-
}
|
|
34
|
-
analyzer = run_backtest(my_strategy, CONFIG)
|
|
35
|
-
|
|
36
|
-
# Access metrics
|
|
37
|
-
print(f"Sharpe Ratio: {analyzer.metrics['sharpe']:.2f}")
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
## Requirements
|
|
41
|
-
- Python >= 3.8
|
|
42
|
-
- pandas >= 1.5.0
|
|
43
|
-
- numpy >= 1.21.0
|
|
44
|
-
- matplotlib >= 3.5.0
|
|
45
|
-
- seaborn >= 0.11.0
|
|
46
|
-
- ivolatility >= 1.8.2
|
|
47
|
-
|
|
48
|
-
## Test CI
|
|
49
|
-
## Test CI1
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: ivolatility_backtesting
|
|
3
|
-
Version: 2.163
|
|
4
|
-
Summary: A universal backtesting framework for financial strategies using the IVolatility API.
|
|
5
|
-
Author-email: IVolatility <support@ivolatility.com>
|
|
6
|
-
Project-URL: Homepage, https://ivolatility.com
|
|
7
|
-
Keywords: backtesting,finance,trading,ivolatility
|
|
8
|
-
Classifier: Programming Language :: Python :: 3
|
|
9
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
10
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
11
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
-
Classifier: Operating System :: OS Independent
|
|
16
|
-
Requires-Python: >=3.8
|
|
17
|
-
Description-Content-Type: text/markdown
|
|
18
|
-
Requires-Dist: pandas<3.0,>=1.5.0
|
|
19
|
-
Requires-Dist: numpy<3.0,>=1.21.0
|
|
20
|
-
Requires-Dist: matplotlib>=3.5.0
|
|
21
|
-
Requires-Dist: seaborn>=0.11.0
|
|
22
|
-
Requires-Dist: ivolatility>=1.9.6
|
|
23
|
-
Requires-Dist: psutil>=7.1.0
|
|
24
|
-
|
|
25
|
-
# IVolatility Backtesting
|
|
26
|
-
A universal backtesting framework for financial strategies using the IVolatility API.
|
|
27
|
-
|
|
28
|
-
## Installation
|
|
29
|
-
```bash
|
|
30
|
-
pip install ivolatility_backtesting
|
|
31
|
-
```
|
|
32
|
-
|
|
33
|
-
## Usage
|
|
34
|
-
```python
|
|
35
|
-
from ivolatility_backtesting import run_backtest, init_api
|
|
36
|
-
|
|
37
|
-
# Initialize API
|
|
38
|
-
init_api("your-api-key")
|
|
39
|
-
|
|
40
|
-
# Define your strategy
|
|
41
|
-
def my_strategy(config):
|
|
42
|
-
# Strategy logic
|
|
43
|
-
return BacktestResults(
|
|
44
|
-
equity_curve=[100000, 110000],
|
|
45
|
-
equity_dates=["2023-01-01", "2023-01-02"],
|
|
46
|
-
trades=[{"pnl": 1000, "entry_date": "2023-01-01", "exit_date": "2023-01-02"}],
|
|
47
|
-
initial_capital=100000,
|
|
48
|
-
config=config
|
|
49
|
-
)
|
|
50
|
-
|
|
51
|
-
# Run backtest
|
|
52
|
-
CONFIG = {
|
|
53
|
-
"initial_capital": 100000,
|
|
54
|
-
"start_date": "2023-01-01",
|
|
55
|
-
"end_date": "2024-01-01",
|
|
56
|
-
"strategy_name": "My Strategy"
|
|
57
|
-
}
|
|
58
|
-
analyzer = run_backtest(my_strategy, CONFIG)
|
|
59
|
-
|
|
60
|
-
# Access metrics
|
|
61
|
-
print(f"Sharpe Ratio: {analyzer.metrics['sharpe']:.2f}")
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
## Requirements
|
|
65
|
-
- Python >= 3.8
|
|
66
|
-
- pandas >= 1.5.0
|
|
67
|
-
- numpy >= 1.21.0
|
|
68
|
-
- matplotlib >= 3.5.0
|
|
69
|
-
- seaborn >= 0.11.0
|
|
70
|
-
- ivolatility >= 1.8.2
|
|
71
|
-
|
|
72
|
-
## Test CI
|
|
73
|
-
## Test CI1
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/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.163 → ivolatility_backtesting-2.164}/tests/test_2144_duckdb_dedup.py
RENAMED
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2147_cents_multiplier.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2148_loader_memory.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2149_client_errors.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2150_prompt_patterns.py
RENAMED
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2153_cache_lock_kept.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2154_put_atm_legs.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_bar_prefetch.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_intraday_exits.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_ivx_stock_holes.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_key_redaction.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_long_expiry.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2155_opt_stop_merge.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2156_phantom_quotes.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2157_sl_symbol.py
RENAMED
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2158_entry_time.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2159_entry_rule.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2160_day_price_order.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2160_exit_rule.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2160_option_lean_rule.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2160_prefetch_cancel.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_2161_assignment.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_price_ta_indicators.py
RENAMED
|
File without changes
|
{ivolatility_backtesting-2.163 → ivolatility_backtesting-2.164}/tests/test_stock_loader_coverage.py
RENAMED
|
File without changes
|
|
File without changes
|