Skip to main content

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:

  1. Ask about strategy parameters
  2. Generate complete notebook code
  3. Include stop-loss/profit-target configuration
  4. Add earnings blackout if requested

Links

  • GitLab: gitlab.ivolatility.com/ivolatility/ivolatility-backtesting
  • API Docs: ivolatility.com/api/openapi.yml
  • Changelog: See CHANGELOG.md in repo

Release files for ivolatility-backtesting 2.144

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ivolatility-backtesting 2.144
File Size Uploaded
ivolatility_backtesting-2.144.tar.gz 334.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for ivolatility-backtesting 2.144
File Interpreter ABI Platform
ivolatility_backtesting-2.144-py3-none-any.whl Python 3 none any Details

Total release size: 663.8 kB

Release files / ivolatility_backtesting-2.144.tar.gz

Download URL ivolatility_backtesting-2.144.tar.gz
Size 334.4 kB
Tags Source
SHA-256 checksum
How to use checksums
fc2b49cbe98049fab9080146ebe7521b76bf3d5665bdfb1ed6fe3cadb4d831b5
BLAKE2b-256 checksum
How to use checksums
e2104ad1d1971bafe708c7ad173b7fe09b8073432d32044e354d26bbde966021
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Release files / ivolatility_backtesting-2.144-py3-none-any.whl

Download URL ivolatility_backtesting-2.144-py3-none-any.whl
Size 329.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
edd8e5f4954c8f4e3d8a02c88f37bbce308d395f9156b5d1c1fd946ad441b5c5
BLAKE2b-256 checksum
How to use checksums
4dc35cabe96779827f830719bcb8c531b619e87e7a0e172dfd5677eb86f1def5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Release history Release notifications | RSS feed

2.146

2 release files

2.145

2 release files

This release

2.144 This release

2 release files

2.143

2 release files

2.142

2 release files

2.141

2 release files

2.140

2 release files

2.139

2 release files

2.138

2 release files

2.137

2 release files

2.132

2 release files

2.0

2 release files

1.42

2 release files

1.41

2 release files

1.40

2 release files

1.39

2 release files

1.38

2 release files

1.37

2 release files

1.36

2 release files

1.35

2 release files

1.34

2 release files

1.33

2 release files

1.32

2 release files

1.31

2 release files

1.30

2 release files

1.29

2 release files

1.28

2 release files

1.27.0

2 release files

1.26.0

2 release files

1.25.0

2 release files

1.24.0

2 release files

1.23.0

2 release files

1.10.0

2 release files

1.9.0

2 release files

1.8.0

2 release files

1.7.1

2 release files

1.7.0

2 release files

1.6.0

2 release files

1.5.0

2 release files

1.4.0

2 release files

1.3.1

2 release files

1.3.0

2 release files

1.2.0

2 release files

1.1.0

2 release files

1.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page