IVolatility Backtesting Framework v1.32
A universal options backtesting framework powered by the IVolatility API.
Supported Strategies
| Strategy | Description | Use Case |
|---|---|---|
| STRADDLE | Long/short ATM call + put | Volatility plays |
| STRANGLE | Long/short OTM call + put | Wide volatility plays |
| IRON_CONDOR | Short strangle + long wings | Range-bound income |
| VERTICAL | Bull/bear call or put spreads | Directional bets |
| CALENDAR | Same strike, different expiry | Time decay plays |
Core Features
Data & Caching
- EOD + Intraday bars - Both timeframes supported for stocks & options
- IVolatility API integration - Options chains, underlying prices, IV data, earnings calendar
- DuckDB caching - Local storage for fast repeated backtests
- ASYNC parallel loading - ~10x faster data preload
- Connection pooling - ~5x faster API calls
Run Modes
| Mode | Function | Use Case |
|---|---|---|
| Single Run | run_backtest() |
Test one specific configuration |
| Baseline | run_optimization(run_baseline=True) |
Reference benchmark (combo_id=0) |
| Combinations | run_optimization() |
Grid search to find optimal params |
| Chunked | run_optimization_chunked() |
Large grids with memory management |
Single Run
Run one backtest with fixed parameters. Use for testing a specific strategy configuration.
results = run_backtest(strategy_fn, config)
Baseline
Reference run using base_config values before testing combinations. Saved as combo_id=0 for comparison.
all_results = run_optimization(
base_config=config,
param_grid=param_grid,
run_baseline=True # combo_id=0 uses base_config values
)
Combinations
Grid search across all parameter combinations. Each combo gets a unique combo_id.
param_grid = {
'z_entry': [-2.0, -1.5, -1.0],
'z_exit': [0.5, 1.0],
'dte_target': [30, 45]
}
# Runs 3 × 2 × 2 = 12 combinations + baseline = 13 total
all_results = run_optimization(
base_config=config,
param_grid=param_grid,
run_baseline=True
)
Chunked Optimization
Memory-efficient mode for large parameter spaces. Processes in batches.
run_optimization_chunked(
base_config=config,
param_grid=large_grid, # 1000+ combinations
chunk_size=50,
run_baseline=True
)
Supported Indicators
| Indicator | Source | Description |
|---|---|---|
iv_rank |
Options | Current IV position in historical range (0-100) |
iv_rank_ivx |
IVX API | IV Rank from pre-calculated IVX data (faster) |
iv_percentile_ivx |
IVX API | IV Percentile from IVX data |
iv_lean_zscore |
Options | Call-Put IV spread normalized (mean reversion) |
iv_lean_zscore_ivx |
IVX API | IV Lean Z-score from IVX (faster) |
iv_term_structure |
IVX API | Volatility curve slope across tenors |
iv_skew |
Options | Put/Call IV skew at target delta |
vix_percentile |
VIX | VIX percentile rank over lookback |
realized_vol |
Stock | Historical volatility (annualized) |
Entry Signals
- Threshold-based - Enter when indicator crosses level
- Z-score signals - Mean reversion entries
- Delta-based selection - Select strikes by delta target
- Custom indicators - Extensible via INDICATOR_REGISTRY
Position & P&L Management
- PositionManager - Track open positions, calculate real-time P&L
- Greeks tracking - Delta, gamma, theta, vega per leg
- Capital at risk - 1.5x safety buffer for EOD backtests
- Multi-leg support - Spreads, condors, straddles
Exit Management (StopLossManager)
- DTE-based exit - Close at target days to expiry
- Stop-loss types:
- Directional (underlying moves X%)
- P&L-based (position loses X%)
- Combined (both conditions required)
- Profit targets - Close at X% gain (same manager handles SL + PT)
- Intraday monitoring - Check stops on each bar
- Earnings blackout - Skip entries near earnings dates
Analytics & Reporting
- BacktestAnalyzer - Sharpe ratio, max drawdown, win rate, profit factor
- Equity curve - Track portfolio value over time
- ResultsReporter - Generate summary tables and statistics
- Trade-level details - Entry/exit prices, Greeks, stop levels
Visualization (ChartGenerator)
- Equity curve charts - Portfolio growth over time
- Drawdown analysis - Visualize underwater periods
- Stop-loss analysis - Compare exit reasons
- Optimization heatmaps - Parameter sensitivity
- Monthly returns - Calendar view of performance
Optimization
- Parameter grid search - Test multiple configurations
- Parallel execution - Run combinations concurrently
- Memory-efficient chunking - Handle large parameter spaces
- Results comparison - Side-by-side analysis
Architecture
┌─────────────────────────────────────────────────────────┐
│ User Notebook │
├─────────────────────────────────────────────────────────┤
│ run_backtest() / run_backtest_with_stoploss() │
├──────────────┬──────────────┬───────────────────────────┤
│ PositionMgr │ StopLossMgr │ DuckDBIndicatorManager │
├──────────────┴──────────────┴───────────────────────────┤
│ OptionsChunkManager (async) │
├─────────────────────────────────────────────────────────┤
│ DuckDBCacheManager │
├─────────────────────────────────────────────────────────┤
│ APIManager → IVolatility API │
└─────────────────────────────────────────────────────────┘
Key Classes
| Class | Purpose |
|---|---|
APIManager |
Unified API access with auth |
DuckDBCacheManager |
Persistent data caching (EOD + intraday) |
OptionsChunkManager |
Async parallel data loading |
DuckDBIndicatorManager |
Pre-calculate & cache indicators |
PositionManager |
Track positions, calculate P&L, manage Greeks |
StopLossManager |
Monitor stops + profit targets (intraday capable) |
StrategyRegistry |
Strategy definitions & metadata |
BacktestAnalyzer |
Calculate metrics: Sharpe, drawdown, win rate |
ResultsReporter |
Generate summary tables & statistics |
ChartGenerator |
Create equity curves, heatmaps, analysis charts |
Quick Start
from ivolatility_backtesting import run_backtest, preload_data
# Configure
config = {
'symbol': 'SPY',
'start_date': '2024-01-01',
'end_date': '2024-12-31',
'strategy_type': 'STRADDLE',
'dte_target': 30,
'entry_signal': 'iv_rank',
'entry_threshold': 50,
}
# Preload data (uses async for speed)
preloaded = preload_data(config)
# Run backtest
results = run_backtest(
strategy_function=straddle_strategy,
config={**config, **preloaded}
)
Performance
| Metric | Before v1.32 | After v1.32 |
|---|---|---|
| Data preload | ~60s | ~6s (10x faster) |
| API calls | Sequential | Pooled (5x faster) |
| Memory usage | High | Chunked (stable) |
| DuckDB stability | Crashes | Legacy mode (stable) |
Integration with Claude
Use system_straddle_simple_20260206.promt as a system prompt to have Claude generate backtesting notebooks. Claude will:
- Ask about strategy parameters
- Generate complete notebook code
- Include stop-loss/profit-target configuration
- Add earnings blackout if requested
Links
- GitLab:
gitlab.ivolatility.com/ivolatility/ivolatility-backtesting - API Docs:
ivolatility.com/api/openapi.yml - Changelog: See
CHANGELOG.mdin repo
Release files for ivolatility-backtesting 2.140
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| ivolatility_backtesting-2.140.tar.gz | 317.8 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| ivolatility_backtesting-2.140-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 636.5 kB
Release files / ivolatility_backtesting-2.140.tar.gz
| Download URL | ivolatility_backtesting-2.140.tar.gz |
|---|---|
| Size | 317.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3ac9bf9bb965abdc3e3fa30be2e38ced17376191f76f92a7cf28f6fb082dcfd8
|
|
BLAKE2b-256 checksum How to use checksums |
def9b8f10200dcfa77f6bf2b652e3a89b371d941e3af3d56bf30f29e30e6c0aa
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.15
|
Release files / ivolatility_backtesting-2.140-py3-none-any.whl
| Download URL | ivolatility_backtesting-2.140-py3-none-any.whl |
|---|---|
| Size | 318.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b137e2fb2e1a794cfa0cbb9a6fec10acc53cf734d948bcf2c25d0c820e0cfa6e
|
|
BLAKE2b-256 checksum How to use checksums |
0f7463fd8fc4066f65c5a883904f35464cb312daa53220ea15f31fa87e548635
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.15
|