Skip to main content

A nimble backtesting and statistics library for options strategies

Project description

Badge Badge CI PyPI version Python

Optopsy

A nimble backtesting and statistics library for options strategies.

Optopsy is a Python backtesting engine that lets you go from "How do 45-DTE iron condors on SPX perform with a 50% profit target and 2x stop loss vs holding to expiration?" to detailed performance statistics in seconds, not spreadsheets.

Full Documentation | API Reference | Examples

🤖 Looking for AI/LLM integration?

optopsy-mcp provides a high-performance MCP server for strategy screening and backtesting. Powered by a complete Rust rewrite of the Optopsy engine, it is specifically built for seamless interaction with Large Language Models.

Features

  • 38 Built-in Strategies - From simple calls/puts to iron condors, butterflies, condors, ratio spreads, collars, calendars, and diagonals
  • Per-Leg Delta Targeting - Select strikes by delta with target, min, max per leg
  • Trade Simulator - Chronological simulation with capital tracking, position limits, and equity curves via simulate()
  • Portfolio Simulation - Weighted multi-strategy portfolio backtesting via simulate_portfolio()
  • Early Exits - Stop-loss, take-profit, and max-hold-days rules for automatic position management
  • Commissions - Model broker fees with per-contract, base fee, and min fee structures
  • Risk Metrics - Sharpe, Sortino, VaR, CVaR, Calmar, Omega, tail ratio, and more via compute_risk_metrics()
  • 80+ Entry Signals - Filter entries with TA indicators (RSI, MACD, Bollinger Bands, EMA, ATR, IV Rank) via pandas-ta-classic
  • Custom Signals - Use custom_signal() to drive entries from any DataFrame with a boolean flag column
  • Slippage Modeling - Realistic fills with mid, spread, liquidity-based, or per-leg slippage
  • Live Data Providers - Fetch options chains and stock prices directly from supported data sources (e.g. EODHD)
  • Smart Caching - Automatic local caching of fetched data with gap detection for efficient re-fetches
  • Plugin System - Extend with custom strategies, signals, and data providers via entry points

Installation

# Core library only (latest stable release)
pip install optopsy

# With Data CLI (download & cache market data)
pip install optopsy[data]

Requirements: Python 3.12-3.13, Pandas 2.0+, NumPy 1.26+

Data Management

Optopsy includes a standalone data CLI for downloading and caching historical market data.

pip install optopsy[data]

# Download historical options data (requires EODHD_API_KEY)
optopsy-data download SPY
optopsy-data download SPY AAPL TSLA

# Download stock price history
optopsy-data download SPY --stocks

# List available symbols
optopsy-data symbols
optopsy-data symbols -q SPY

# Cache management
optopsy-data cache size
optopsy-data cache clear

Data is cached locally as Parquet files at ~/.optopsy/cache/. Re-running download only fetches new data since your last download. See the Data Management documentation for full details.

Core Library Quick Start

import optopsy as op

# Load your options data
data = op.csv_data(
    "options_data.csv",
    underlying_symbol=0,
    option_type=2,
    expiration=3,
    quote_date=4,
    strike=5,
    bid=6,
    ask=7,
)

# Backtest long calls and get performance statistics
results = op.long_calls(data)
print(results)

Output:

   dte_range   delta_range  count   mean    std    min    25%    50%    75%    max
0    (0, 7]   (0.2, 0.3]    505   0.64   1.03  -1.00   0.14   0.37   0.87   7.62
1    (0, 7]   (0.3, 0.4]    269   2.34   8.65  -1.00  -1.00  -0.89   1.16  68.00
2   (7, 14]   (0.2, 0.3]    404   1.02   0.68  -0.46   0.58   0.86   1.32   4.40
...

Results are grouped by DTE (days to expiration) and delta range, showing descriptive statistics for percentage returns.

Simulator

Run a full trade-by-trade simulation with capital tracking, position limits, and performance metrics:

result = op.simulate(
    data,
    op.long_calls,
    capital=100_000,
    quantity=1,
    max_positions=1,
    selector="nearest",       # "nearest", "highest_premium", "lowest_premium", or custom callable
    max_entry_dte=45,
    exit_dte=14,
)

print(result.summary)         # win rate, profit factor, max drawdown, etc.
print(result.trade_log)       # per-trade P&L, entry/exit dates, equity
print(result.equity_curve)    # portfolio value over time

The simulator works with all 38 strategies. It selects one trade per entry date, enforces concurrent position limits, and computes a full equity curve with metrics like win rate, profit factor, max drawdown, and average days in trade.

Supported Strategies

Category Strategies
Single Leg long_calls, short_calls, long_puts, short_puts
Straddles/Strangles long_straddles, short_straddles, long_strangles, short_strangles
Vertical Spreads long_call_spread, short_call_spread, long_put_spread, short_put_spread
Butterflies long_call_butterfly, short_call_butterfly, long_put_butterfly, short_put_butterfly
Ratio Spreads call_back_spread, put_back_spread, call_front_spread, put_front_spread
Iron Condors iron_condor, reverse_iron_condor
Iron Butterflies iron_butterfly, reverse_iron_butterfly
Condors long_call_condor, short_call_condor, long_put_condor, short_put_condor
Covered & Collar covered_call, protective_put, collar, cash_secured_put (supports actual stock data via yfinance)
Calendar Spreads long_call_calendar, short_call_calendar, long_put_calendar, short_put_calendar
Diagonal Spreads long_call_diagonal, short_call_diagonal, long_put_diagonal, short_put_diagonal

Documentation

Star History

Star History Chart

Disclaimer

Optopsy is intended for research and educational purposes only. Backtest results are based on historical data and simplified assumptions — they do not account for all real-world factors such as liquidity constraints, execution slippage, assignment risk, or changing market conditions. Past performance is not indicative of future results. Always perform your own due diligence before making any trading decisions.

License

This project is licensed under the GNU Affero General Public License v3.0 - see the LICENSE file for details.

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

optopsy-2.3.0.tar.gz (1.7 MB view details)

Uploaded Source

Built Distribution

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

optopsy-2.3.0-py3-none-any.whl (314.6 kB view details)

Uploaded Python 3

File details

Details for the file optopsy-2.3.0.tar.gz.

File metadata

  • Download URL: optopsy-2.3.0.tar.gz
  • Upload date:
  • Size: 1.7 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for optopsy-2.3.0.tar.gz
Algorithm Hash digest
SHA256 98b2d764042d4b5df59e773892d26d0ffd2a636e21b4413cf25defb42ebca1cd
MD5 aa227627259342ebc0c455c379925a37
BLAKE2b-256 0ebddddb0b08e7a4a0344d83eef4ad4520bf450cd427fc9eadc5af8feba817bb

See more details on using hashes here.

Provenance

The following attestation bundles were made for optopsy-2.3.0.tar.gz:

Publisher: python-publish.yml on goldspanlabs/optopsy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file optopsy-2.3.0-py3-none-any.whl.

File metadata

  • Download URL: optopsy-2.3.0-py3-none-any.whl
  • Upload date:
  • Size: 314.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for optopsy-2.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b018826952e88109deedddde2580770c0bf239b86e69ecdb0e80dbeb5f5838fd
MD5 3f42b1b347f9b017ed98f361d0486f68
BLAKE2b-256 1385e0d0a93741cb20364efe85759f10798f571b2509c43d4497b60b8e0408ad

See more details on using hashes here.

Provenance

The following attestation bundles were made for optopsy-2.3.0-py3-none-any.whl:

Publisher: python-publish.yml on goldspanlabs/optopsy

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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