Skip to main content

A universal backtesting framework for financial strategies using the IVolatility API.

Project description

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ivolatility_backtesting-2.137.tar.gz (308.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ivolatility_backtesting-2.137-py3-none-any.whl (309.7 kB view details)

Uploaded Python 3

File details

Details for the file ivolatility_backtesting-2.137.tar.gz.

File metadata

  • Download URL: ivolatility_backtesting-2.137.tar.gz
  • Upload date:
  • Size: 308.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for ivolatility_backtesting-2.137.tar.gz
Algorithm Hash digest
SHA256 4bd050c1c1e82fe6ee76ac77912d433cf885b2331be63575541447b68c5e6b32
MD5 6a40891791e7197af66a6bbec414188f
BLAKE2b-256 54933eecb2b05a85d69a26e3bdb825674e7e927c3e124cb4b59416fe263b8eb6

See more details on using hashes here.

File details

Details for the file ivolatility_backtesting-2.137-py3-none-any.whl.

File metadata

File hashes

Hashes for ivolatility_backtesting-2.137-py3-none-any.whl
Algorithm Hash digest
SHA256 0a9ef9ac248b05d33f276cf95506d0a6a2dbf8a5cc39fd246b82f2a507192ec5
MD5 9519541ce4c4b8be5929d9f6e91fd1d9
BLAKE2b-256 531503cab477b6bf919c75a73b96b42ed7be1c3608ea0cfddd6dac6b9eeacb42

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page