Metadata-Version: 2.4
Name: ivolatility_backtesting
Version: 2.139
Summary: A universal backtesting framework for financial strategies using the IVolatility API.
Author-email: IVolatility <support@ivolatility.com>
Project-URL: Homepage, https://ivolatility.com
Keywords: backtesting,finance,trading,ivolatility
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: pandas>=1.5.0
Requires-Dist: numpy>=1.21.0
Requires-Dist: matplotlib>=3.5.0
Requires-Dist: seaborn>=0.11.0
Requires-Dist: ivolatility>=1.8.2
Requires-Dist: psutil>=7.1.0

# 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.
```python
results = run_backtest(strategy_fn, config)
```

#### Baseline
Reference run using `base_config` values before testing combinations. Saved as `combo_id=0` for comparison.
```python
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`.
```python
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.
```python
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

```python
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
