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

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

Metadata

Release files for ivolatility-backtesting 2.147

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.147
File Size Uploaded Provenance
ivolatility_backtesting-2.147.tar.gz 345.0 kB Without provenance Details

Built distribution (wheel)

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

Total release size: 679.7 kB

Release files / ivolatility_backtesting-2.147.tar.gz

Download URL ivolatility_backtesting-2.147.tar.gz
Size 345.0 kB
Tags Source
SHA-256 checksum
How to use checksums
a804170ccb2aa6ab1c9b2b1db5eadbf745ee10d3315117ef2f8b92fc91eb927a
BLAKE2b-256 checksum
How to use checksums
6b94625a2fcbaeb285e7c6df1a07d02e1f85ae01642a1f39080d02ba2d9f4da5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

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

Download URL ivolatility_backtesting-2.147-py3-none-any.whl
Size 334.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4600d253c3236e8aea60405fe829fc03e1ef09a9b92afa244576a4335c4dfd59
BLAKE2b-256 checksum
How to use checksums
b7fc318b7dbbd089e59a6620e3c904afaed1ccd67867540a2f158ddc7dc822e6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Security for ivolatility-backtesting 2.147

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

2.147 This release

2 release files No provenance

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