### Install Dependencies with uv Source: https://goldspanlabs.github.io/optopsy/contributing Install project dependencies using the 'uv' package manager. ```bash uv sync --extra ui ``` -------------------------------- ### Install Optopsy Core Library Source: https://goldspanlabs.github.io/optopsy Installs the core Optopsy library, which includes strategies, signals, simulation, and metrics. ```bash pip install optopsy ``` -------------------------------- ### Install Optopsy with Data CLI Source: https://goldspanlabs.github.io/optopsy Installs Optopsy along with the Data CLI for downloading and caching market data. ```bash pip install optopsy[data] ``` -------------------------------- ### Verify Installation with Pytest Source: https://goldspanlabs.github.io/optopsy/contributing Run all tests using pytest to verify the installation and development setup. ```bash uv run pytest tests/ -v ``` -------------------------------- ### Install Optopsy Data Package Source: https://goldspanlabs.github.io/optopsy/data Install the data package and CLI tools using pip. ```bash pip install optopsy[data] ``` -------------------------------- ### Install and Serve MkDocs Locally Source: https://goldspanlabs.github.io/optopsy/contributing Commands to install MkDocs and its plugins, then serve the documentation locally for preview. Visit the provided URL to view the documentation. ```bash # Install MkDocs and required plugins pip install mkdocs mkdocs-material "mkdocstrings[python]" # Serve docs locally mkdocs serve # Visit http://127.0.0.1:8000 ``` -------------------------------- ### Install yfinance Source: https://goldspanlabs.github.io/optopsy/strategies/covered Install the yfinance library for downloading stock data. This is a prerequisite for using actual stock prices with Optopsy strategies. ```python pip install yfinance ``` -------------------------------- ### Install Pre-commit Hooks Source: https://goldspanlabs.github.io/optopsy/contributing Install pre-commit hooks to ensure code quality before committing changes. This includes setting up pre-push hooks. ```bash uv run pre-commit install --hook-type pre-push ``` -------------------------------- ### Launch Chat Interface Source: https://goldspanlabs.github.io/optopsy/chat-ui Start the Optopsy chat application. ```bash optopsy-chat ``` -------------------------------- ### Install Optopsy with AI Chat UI Source: https://goldspanlabs.github.io/optopsy/getting-started Install Optopsy with the AI Chat UI, which includes the data package for natural language backtesting. ```bash pip install optopsy[ui] ``` -------------------------------- ### Install Optopsy Core Library Source: https://goldspanlabs.github.io/optopsy/getting-started Install the core Optopsy library for strategies, signals, simulation, and metrics. No external data dependencies are required for this package. ```bash pip install optopsy ``` -------------------------------- ### Using Strategy Type Hints for Autocomplete Source: https://goldspanlabs.github.io/optopsy/api-reference Demonstrates how to use imported type hints like `StrategyParamsDict` for better IDE autocompletion when calling strategy functions. This example shows calling the `iron_condor` strategy with various parameters. ```python import optopsy as op from optopsy import StrategyParamsDict # Your IDE will now provide autocomplete for all parameters results = op.iron_condor( data, max_entry_dte=45, # Type: int exit_dte=21, # Type: int slippage='liquidity', # Type: Literal['mid', 'spread', 'liquidity'] fill_ratio=0.5, # Type: float ) ``` -------------------------------- ### Type Hinting Example Source: https://goldspanlabs.github.io/optopsy/contributing Example of Python function with comprehensive type hints for parameters and return values, including imports for common types. ```python from typing import Any, Dict, List import pandas as pd def process_data( data: pd.DataFrame, params: Dict[str, Any] ) -> List[pd.DataFrame]: ... ``` -------------------------------- ### Google-Style Docstring Example Source: https://goldspanlabs.github.io/optopsy/contributing Example of a Python function with a Google-style docstring, including sections for arguments, return values, and raised exceptions. ```python def function_name(param1: str, param2: int) -> bool: """ Brief description of function. Longer description if needed, explaining behavior, edge cases, or important details. Args: param1: Description of param1 param2: Description of param2 Returns: Description of return value Raises: ValueError: When param1 is invalid """ pass ``` -------------------------------- ### Define a New Options Strategy Source: https://goldspanlabs.github.io/optopsy/contributing Example of defining a new options strategy function in Python, including type hints and a docstring. ```python def new_strategy(data: pd.DataFrame, **kwargs: Any) -> pd.DataFrame: """ Generate new strategy statistics. A clear description of what this strategy does, including: - Leg composition - Market outlook - Profit/loss characteristics Args: data: DataFrame containing option chain data **kwargs: Optional strategy parameters Returns: DataFrame with strategy performance statistics """ return _helper(data, leg_def=[...], **kwargs) ``` -------------------------------- ### Run Chronological Options Strategy Simulation Source: https://goldspanlabs.github.io/optopsy/api-reference Use this function to simulate a single options strategy over historical data. It requires option chain data and a strategy function, with options for starting capital, contract quantity, and trade selection. ```python simulate( data: DataFrame, strategy: Callable[..., DataFrame], capital: float = 100000.0, quantity: int = 1, max_positions: int = 1, multiplier: int = 100, selector: Union[ Literal[ "nearest", "highest_premium", "lowest_premium", "first", ], Callable[[DataFrame], Series], ] = "nearest", **strategy_kwargs: Any, ) -> SimulationResult ``` -------------------------------- ### Example PR Template Source: https://goldspanlabs.github.io/optopsy/contributing A template for Pull Request descriptions, including sections for changes, type of change, testing instructions, and a checklist. ```markdown ## Description Brief description of changes ## Type of Change - [ ] Bug fix - [ ] New feature - [ ] Breaking change - [ ] Documentation update ## Testing How to test these changes ## Checklist - [ ] Tests pass - [ ] Code formatted with Ruff - [ ] Documentation updated - [ ] Type hints included ``` -------------------------------- ### Execute Strategy with Full Configuration Source: https://goldspanlabs.github.io/optopsy/parameters Demonstrates a complete strategy execution including timing, delta targeting, filtering, slippage, and exit rules. ```python import optopsy as op data = op.csv_data('SPX_options.csv') results = op.iron_condor( data, # Timing max_entry_dte=45, exit_dte=21, # Per-leg delta targeting leg2_delta={"target": 0.20, "min": 0.15, "max": 0.25}, leg3_delta={"target": 0.20, "min": 0.15, "max": 0.25}, # Filtering min_bid_ask=0.15, # Grouping dte_interval=7, delta_interval=0.05, # Slippage slippage='liquidity', fill_ratio=0.5, reference_volume=5000, # Early exits stop_loss=-1.0, take_profit=0.50, # Commission commission=0.65, # Output raw=False, drop_nan=True ) print(results.head()) ``` -------------------------------- ### Launch Chat with Custom Options Source: https://goldspanlabs.github.io/optopsy/chat-ui Run the chat interface with specific port, headless mode, and debug logging enabled. ```bash optopsy-chat run --port 9000 --headless --debug ``` -------------------------------- ### Prepare stock data for signals Source: https://goldspanlabs.github.io/optopsy/entry-signals Shows how to load cached stock data or construct a custom DataFrame with the required columns for signal computation. ```python # Stock data needs: underlying_symbol, quote_date, close # Optional: open, high, low, volume (for OHLCV signals) stocks = op.load_cached_stocks("SPY") # Or bring your own DataFrame stocks = pd.DataFrame({ "underlying_symbol": "SPY", "quote_date": my_dates, "close": my_prices, }) ``` -------------------------------- ### POST /simulator/simulate Source: https://goldspanlabs.github.io/optopsy/api-reference Run a chronological simulation of an options strategy based on provided data and strategy parameters. ```APIDOC ## POST /simulator/simulate ### Description Run a chronological simulation of an options strategy. ### Method POST ### Endpoint /simulator/simulate ### Parameters #### Request Body - **data** (DataFrame) - Required - Option chain DataFrame. - **strategy** (Callable) - Required - Optopsy strategy function. - **capital** (float) - Optional - Starting capital in dollars (Default: 100000.0). - **quantity** (int) - Optional - Number of contracts per trade (Default: 1). - **max_positions** (int) - Optional - Maximum concurrent open positions (Default: 1). - **multiplier** (int) - Optional - Contract multiplier (Default: 100). - **selector** (Union) - Optional - Trade selection logic: 'nearest', 'highest_premium', 'lowest_premium', 'first', or custom callable (Default: 'nearest'). - **strategy_kwargs** (Any) - Optional - Additional arguments passed to the strategy function. ### Response #### Success Response (200) - **SimulationResult** (dataclass) - Contains trade_log (DataFrame), equity_curve (Series), and summary (dict). ``` -------------------------------- ### Update Column Definitions Source: https://goldspanlabs.github.io/optopsy/contributing Example of defining new internal column names for a strategy in Python. This list specifies the required columns for the strategy's internal processing. ```python new_strategy_internal_cols: List[str] = [ "underlying_symbol", "strike_leg1", # ... other columns ] ``` -------------------------------- ### Add Strike Validation Rule Source: https://goldspanlabs.github.io/optopsy/contributing Example of adding a strike validation rule for a new strategy in Python. This function should return a filtered DataFrame based on specified criteria. ```python def _rule_new_strategy_strikes(df: pd.DataFrame) -> pd.DataFrame: """ Validate strike ordering for new strategy. Rule: [Describe your rule here] """ # Implementation return df[mask] ``` -------------------------------- ### Configure Environment Variables Source: https://goldspanlabs.github.io/optopsy/chat-ui Define API keys in a .env file for LLM and data provider access. ```text ANTHROPIC_API_KEY=sk-... # or OPENAI_API_KEY for OpenAI models EODHD_API_KEY=... ``` -------------------------------- ### Implement Custom Data Provider Source: https://goldspanlabs.github.io/optopsy/data Create a custom provider by subclassing DataProvider. Providers are auto-detected via their environment key. ```python from optopsy.data.providers.base import DataProvider class MyProvider(DataProvider): name = "my_provider" env_key = "MY_PROVIDER_API_KEY" def get_tool_schemas(self): ... def get_tool_names(self): ... async def execute(self, tool_name, arguments): ... ``` -------------------------------- ### Delta-Neutral Iron Condor Strategy Source: https://goldspanlabs.github.io/optopsy/strategies/iron-strategies Implement an Iron Condor strategy targeting delta-neutral positioning. This example includes parameters for strike delta, delta interval, and slippage. ```python # Target delta-neutral positioning results = op.iron_condor( data, max_entry_dte=45, exit_dte=21, # Target specific delta for short strikes leg2_delta={"target": 0.16, "min": 0.15, "max": 0.20}, leg3_delta={"target": 0.16, "min": 0.15, "max": 0.20}, delta_interval=0.05, min_bid_ask=0.10, slippage='liquidity' ) ``` -------------------------------- ### List Available Symbols Source: https://goldspanlabs.github.io/optopsy/data Query the provider for symbols with available options data. ```bash # List all available symbols optopsy-data symbols # Search for a specific symbol optopsy-data symbols -q SPY ``` -------------------------------- ### Get Raw Trade Data from Backtest Source: https://goldspanlabs.github.io/optopsy/getting-started Retrieve individual trade details from a backtest by setting the `raw` parameter to `True`. This provides every trade for custom analysis. ```python results = op.long_calls(data, raw=True) print(results.columns) # ['underlying_symbol', 'expiration', 'dte_entry', 'strike', 'entry', 'exit', 'pct_change', ...] ``` -------------------------------- ### Simulate Weighted Portfolio Source: https://goldspanlabs.github.io/optopsy/examples Simulates a weighted portfolio across multiple strategies using `simulate_portfolio()`. Loads data, defines legs with strategies and weights, and prints portfolio-level summaries. ```python import optopsy as op spy = op.csv_data('SPY_2023.csv') qqq = op.csv_data('QQQ_2023.csv') result = op.simulate_portfolio( legs=[ { "data": spy, "strategy": op.short_puts, "weight": 0.6, "max_entry_dte": 45, "exit_dte": 14, }, { "data": qqq, "strategy": op.iron_condor, "weight": 0.4, "max_entry_dte": 30, "exit_dte": 7, }, ], capital=100_000, ) # Portfolio-level summary print(result.summary) # Combined trade log (includes a 'leg' column) print(result.trade_log) # Portfolio equity curve print(result.equity_curve) # Access individual leg results for name, leg_result in result.leg_results.items(): print(f"\n{name}:") print(leg_result.summary) ``` -------------------------------- ### POST /simulator/simulate_portfolio Source: https://goldspanlabs.github.io/optopsy/api-reference Run a weighted portfolio simulation across multiple strategy legs, combining results into a single equity curve and trade log. ```APIDOC ## POST /simulator/simulate_portfolio ### Description Run a weighted portfolio simulation across multiple strategy legs. ### Method POST ### Endpoint /simulator/simulate_portfolio ### Parameters #### Request Body - **legs** (list[dict]) - Required - List of leg dicts containing data, strategy, and weight. - **capital** (float) - Optional - Total starting capital in dollars (Default: 100000.0). ### Response #### Success Response (200) - **PortfolioResult** (dataclass) - Contains trade_log, equity_curve, summary, and leg_results. ``` -------------------------------- ### Chronological Strategy Simulation Source: https://goldspanlabs.github.io/optopsy/examples Simulates a trading strategy chronologically using `simulate()`, including capital tracking, position limits, and a full equity curve. Demonstrates simulation of short puts with specified parameters. ```python import optopsy as op data = op.csv_data('SPX_2023.csv') # Simulate short puts with $100k capital result = op.simulate( data, op.short_puts, capital=100_000, quantity=1, max_positions=2, multiplier=100, selector='nearest', # Pick ATM strike per entry date max_entry_dte=45, exit_dte=14, ) # Summary statistics (includes Sharpe, Sortino, VaR, max drawdown, etc.) print(result.summary) # Individual trade log with P&L print(result.trade_log) # Equity curve indexed by exit date print(result.equity_curve) ``` -------------------------------- ### Configure Commission Structures Source: https://goldspanlabs.github.io/optopsy/parameters Apply commission fees using either a simple float for per-contract fees or a Commission object for detailed fee structures. ```python results = op.short_puts(data, commission=0.65) # $0.65 per contract ``` ```python from optopsy import Commission results = op.iron_condor( data, commission=Commission( per_contract=0.65, # Per option contract base_fee=9.99, # Flat fee per trade ) ) ``` -------------------------------- ### Run Weighted Portfolio Simulation Source: https://goldspanlabs.github.io/optopsy/api-reference Simulate a portfolio of multiple options strategies, each with an independent capital allocation and its own set of parameters. Results are aggregated into a single portfolio view. ```python simulate_portfolio( legs: list[dict], capital: float = 100000.0 ) -> PortfolioResult ``` ```python result = op.simulate_portfolio( legs=[ {"data": spy, "strategy": op.short_puts, "weight": 0.6, "max_entry_dte": 45, "exit_dte": 14}, {"data": qqq, "strategy": op.iron_condor, "weight": 0.4, "max_entry_dte": 30, "exit_dte": 7}, ], capital=100_000, ) ``` -------------------------------- ### Configure Early Exit Parameters Source: https://goldspanlabs.github.io/optopsy/parameters Set thresholds for stop-loss, take-profit, and maximum holding periods to close positions early. ```python results = op.short_puts( data, stop_loss=-0.50, # Close if losing 50% or more raw=True ) ``` ```python results = op.iron_condor( data, take_profit=0.50, # Close if gaining 50% or more raw=True ) ``` ```python results = op.short_puts( data, max_hold_days=21, # Exit after 21 calendar days raw=True ) ``` -------------------------------- ### Custom DataProvider Plugin Source: https://goldspanlabs.github.io/optopsy/plugins Create a DataProvider subclass for custom data backends. Ensure the class has a unique 'name' and 'env_key' attribute. The provider is auto-detected if its env_key environment variable is set. ```python from optopsy.data.providers.base import DataProvider class MyProvider(DataProvider): name = "my_provider" env_key = "MY_PROVIDER_API_KEY" def get_tool_schemas(self): ... def get_tool_names(self): ... async def execute(self, tool_name, arguments): ... ``` -------------------------------- ### Execute Put Front Spread Source: https://goldspanlabs.github.io/optopsy/strategies/spreads Calculates a put ratio spread using the optopsy library. ```python results = op.put_front_spread(data, max_entry_dte=45, exit_dte=21) ``` -------------------------------- ### Registering Optopsy Plugins in pyproject.toml Source: https://goldspanlabs.github.io/optopsy/plugins Define plugin entry points in your package's pyproject.toml file under the [project.entry-points] section for different plugin groups. ```toml [project.entry-points."optopsy.strategies"] my_strategy = "my_package:register_strategies" [project.entry-points."optopsy.signals"] my_signals = "my_package:register_signals" [project.entry-points."optopsy.providers"] my_provider = "my_package:MyProvider" [project.entry-points."optopsy.tools"] my_tools = "my_package:register_tools" [project.entry-points."optopsy.auth"] my_auth = "my_package:register_auth" ``` -------------------------------- ### Configure Liquidity-Based Slippage Source: https://goldspanlabs.github.io/optopsy/parameters Sets the fill ratio for liquidity-based slippage calculations. ```python results = op.iron_condor( data, slippage='liquidity', fill_ratio=0.3 # More conservative fill (30% through spread) ) ``` -------------------------------- ### POST /optopsy/strategies/collar Source: https://goldspanlabs.github.io/optopsy/api-reference Generates performance statistics for a collar strategy. ```APIDOC ## POST /optopsy/strategies/collar ### Description Generate collar strategy statistics. Consists of a long underlying position, a short 1 OTM call, and a long 1 OTM put. ### Parameters #### Request Body - **data** (DataFrame) - Required - DataFrame containing option chain data - **stock_data** (Optional[DataFrame]) - Optional - Optional DataFrame of stock prices for the underlying - **kwargs** (Unpack[StrategyParamsDict]) - Optional - Optional strategy parameters ### Response #### Success Response (200) - **DataFrame** (DataFrame) - DataFrame with collar strategy performance statistics ``` -------------------------------- ### Execute Put Back Spread Source: https://goldspanlabs.github.io/optopsy/strategies/spreads Calculates a put ratio backspread using the optopsy library. ```python results = op.put_back_spread(data, max_entry_dte=45, exit_dte=21) ``` -------------------------------- ### Backtest Iron Condor Strategy Source: https://goldspanlabs.github.io/optopsy Loads options data from a CSV file and backtests an iron condor strategy with specified DTE and delta parameters. Requires the 'optopsy' library. ```python import optopsy as op # Load your options data data = op.csv_data('SPX_options.csv') # Backtest an iron condor strategy results = op.iron_condor( data, max_entry_dte=45, exit_dte=21, leg2_delta={"target": 0.20, "min": 0.15, "max": 0.25}, leg3_delta={"target": 0.20, "min": 0.15, "max": 0.25}, ) print(results) ``` -------------------------------- ### Configure EODHD API Key Source: https://goldspanlabs.github.io/optopsy/data Set the environment variable to enable the built-in EODHD provider. ```bash export EODHD_API_KEY=your-key-here ``` -------------------------------- ### Combine Signals with Fluent API Source: https://goldspanlabs.github.io/optopsy/entry-signals Create complex entry signals by combining multiple conditions using the fluent API with '&' (AND) operator. Requires stock and option data. ```python import optopsy as op stocks = op.load_cached_stocks("SPY") options = op.load_cached_options("SPY") # Fluent API: oversold + uptrend + low volatility entry = op.signal(op.rsi_below(14, 30)) & op.signal(op.sma_above(50)) & op.signal(op.atr_below(14, 0.75)) entry_dates = op.signal_dates(stocks, entry) results = op.long_calls(options, entry_dates=entry_dates) ``` -------------------------------- ### Implement Short Call Calendar Strategy Source: https://goldspanlabs.github.io/optopsy/strategies/calendars This function helps in setting up short call calendar trades. It takes similar date range parameters as the long call version. The 'data' object must be prepared beforehand. ```python results = op.short_call_calendar( data, front_dte_min=20, front_dte_max=40, back_dte_min=50, back_dte_max=90 ) ``` -------------------------------- ### Simulate Realistic Slippage Source: https://goldspanlabs.github.io/optopsy/examples Enable liquidity-based slippage modeling to obtain more realistic backtesting results. ```python # Use liquidity mode for realistic results results = op.iron_condor( data, slippage='liquidity', fill_ratio=0.5, reference_volume=1000 ) ``` -------------------------------- ### Collar Strategy with Stock Data Source: https://goldspanlabs.github.io/optopsy/strategies/covered Implement a collar strategy using actual stock data. This strategy hedges a stock position by capping upside and protecting downside, suitable for defined risk hedging. ```python import yfinance as yf import optopsy as op # With actual stock data (recommended) stock = yf.download("SPY", start="2023-01-01", end="2023-12-31") results = op.collar(data, stock_data=stock, max_entry_dte=45, exit_dte=21) ``` -------------------------------- ### Download Historical Market Data Source: https://goldspanlabs.github.io/optopsy/data Use the CLI to fetch options or stock data. Requires an EODHD_API_KEY. ```bash # Download options data for one or more symbols (requires EODHD_API_KEY) optopsy-data download SPY optopsy-data download SPY AAPL TSLA # Download stock price history instead of options optopsy-data download SPY --stocks # Verbose output for debugging optopsy-data download SPY -v ``` -------------------------------- ### Compute Risk Metrics from Returns Source: https://goldspanlabs.github.io/optopsy/api-reference Calculate a comprehensive set of risk metrics, including Sharpe ratio, maximum drawdown, and win rate, from a series of periodic returns. An equity curve can optionally be provided for more accurate drawdown calculation. ```python compute_risk_metrics( returns: _ArrayLike, equity: _ArrayLike | None = None, trading_days: int = _TRADING_DAYS, ) -> dict[str, float] ``` -------------------------------- ### Implement Short Put Calendar Strategy Source: https://goldspanlabs.github.io/optopsy/strategies/calendars This function is for short put calendar strategies, profiting from movement away from the strike. Pass the prepared 'data' object to this function. ```python results = op.short_put_calendar(data) ``` -------------------------------- ### Clone Optopsy Repository Source: https://goldspanlabs.github.io/optopsy/contributing Clone the Optopsy repository to your local machine and navigate into the project directory. ```bash git clone https://github.com/goldspanlabs/optopsy.git cd optopsy ``` -------------------------------- ### Combine Signals with OR Logic Source: https://goldspanlabs.github.io/optopsy/entry-signals Create entry signals where any of the specified conditions trigger using the `or_signals` helper. Requires stock and option data. ```python # OR: enter when EITHER condition fires entry = op.or_signals(op.macd_cross_above(), op.bb_below_lower()) entry_dates = op.signal_dates(stocks, entry) results = op.long_call_spread(options, entry_dates=entry_dates) ``` -------------------------------- ### Implement Short Call Condor Strategy Source: https://goldspanlabs.github.io/optopsy/strategies/condors Implement a short call condor strategy with specified entry and exit days to expiration. This strategy profits from large price movements. ```python results = op.short_call_condor(data, max_entry_dte=30, exit_dte=0) ``` -------------------------------- ### Tool Plugin Registrar Function Source: https://goldspanlabs.github.io/optopsy/plugins Implement a callable that returns a dictionary containing tool schemas, handlers, models, and descriptions. Schemas should be OpenAI-compatible. ```python def register_tools(): return { "schemas": [ # OpenAI-compatible tool schema dicts {"type": "function", "function": {"name": "my_tool", ...}}, ], "handlers": {"my_tool": handler_callable}, "models": {"my_tool": PydanticModel}, "descriptions": {"my_tool": "Description of my tool"}, } ``` -------------------------------- ### Reference Calendar and Diagonal Defaults Source: https://goldspanlabs.github.io/optopsy/parameters Default parameter values for calendar and diagonal strategy configurations. ```python calendar_default_params = { "front_dte_min": 20, "front_dte_max": 40, "back_dte_min": 50, "back_dte_max": 90, "exit_dte": 7, "dte_interval": 7, "min_bid_ask": 0.05, "delta_interval": 0.05, "drop_nan": True, "raw": False, "slippage": "mid", "fill_ratio": 0.5, "reference_volume": 1000, "per_leg_slippage": 0.073, } ``` -------------------------------- ### Load Options Data from Pandas DataFrame Source: https://goldspanlabs.github.io/optopsy/getting-started Load options data from an existing pandas DataFrame. Ensure the DataFrame has the required columns and rename them to match Optopsy's expected format before use. ```python import pandas as pd import optopsy as op # Your existing DataFrame df = pd.read_csv('options_data.csv') # Rename columns to match Optopsy's expected format df = df.rename(columns={ 'Symbol': 'underlying_symbol', 'Type': 'option_type', 'Expiration': 'expiration', 'QuoteDate': 'quote_date', 'Strike': 'strike', 'Bid': 'bid', 'Ask': 'ask', 'Delta': 'delta' }) # Now you can use it directly results = op.long_calls(df) ``` -------------------------------- ### Short Puts with Stop Loss and Take Profit Source: https://goldspanlabs.github.io/optopsy/examples Backtests short put options with early exit conditions based on stop loss (percentage loss) and take profit (percentage gain). Analyzes exit types and describes returns by exit type. ```python # Short puts with early exit rules trades = op.short_puts( data, max_entry_dte=45, exit_dte=0, stop_loss=-1.0, # Close if losing 100%+ take_profit=0.50, # Close if gaining 50%+ raw=True ) # Analyze exit types print(trades['exit_type'].value_counts()) # Compare returns by exit type print(trades.groupby('exit_type')['pct_change'].describe()) ``` -------------------------------- ### Test New Strategy Source: https://goldspanlabs.github.io/optopsy/contributing Write a test function for the new strategy in `tests/test_strategies.py`. This includes checking the return type, non-empty results, and specific column presence. ```python def test_new_strategy(sample_data): """Test new strategy returns expected output.""" results = op.new_strategy(sample_data) assert isinstance(results, pd.DataFrame) assert len(results) > 0 assert 'mean' in results.columns # Additional assertions ``` -------------------------------- ### Apply Strategy Filters Source: https://goldspanlabs.github.io/optopsy/examples Improve strategy quality by applying entry and exit constraints to trade execution. ```python # Bad: No filtering results = op.iron_condor(data) # Good: Filtered for quality results = op.iron_condor( data, max_entry_dte=45, exit_dte=21, min_bid_ask=0.10, leg2_delta={"target": 0.20, "min": 0.15, "max": 0.25}, leg3_delta={"target": 0.20, "min": 0.15, "max": 0.25}, ) ``` -------------------------------- ### Collar Strategy (Synthetic) Source: https://goldspanlabs.github.io/optopsy/strategies/covered Implement a collar strategy using synthetic deep ITM calls when actual stock data is unavailable. This strategy hedges a stock position with defined risk. ```python # Without stock data (synthetic approach) results = op.collar(data, max_entry_dte=45, exit_dte=21) ``` -------------------------------- ### Run a Simple Long Calls Backtest Source: https://goldspanlabs.github.io/optopsy/getting-started Execute a basic backtest for a long call strategy using default parameters. This requires loading the data first. ```python import optopsy as op # Load data data = op.csv_data('SPX_2023.csv') # Run backtest with default parameters results = op.long_calls(data) print(results) ``` -------------------------------- ### Filter strategy entries with technical signals Source: https://goldspanlabs.github.io/optopsy/entry-signals Demonstrates how to compute entry dates using RSI thresholds, sustained conditions, and logical signal composition. ```python import optopsy as op # Load stock and options data separately stocks = op.load_cached_stocks("SPY") options = op.load_cached_options("SPY") # Enter only when RSI(14) is below 30 entry_dates = op.signal_dates(stocks, op.rsi_below(14, 30)) results = op.long_calls(options, entry_dates=entry_dates) # Require RSI below 30 for 5 consecutive days entry_dates = op.signal_dates(stocks, op.sustained(op.rsi_below(14, 30), days=5)) results = op.long_calls(options, entry_dates=entry_dates) # Compose signals with & and | sig = op.signal(op.rsi_below(14, 30)) & op.signal(op.day_of_week(3)) # Oversold + Thursday entry_dates = op.signal_dates(stocks, sig) results = op.long_calls(options, entry_dates=entry_dates) ``` -------------------------------- ### Configure Slippage Models Source: https://goldspanlabs.github.io/optopsy/parameters Set the slippage model to determine fill price calculations for trades. ```python results = op.long_calls(data, slippage='liquidity') ``` -------------------------------- ### Load Options Data from CSV Source: https://goldspanlabs.github.io/optopsy/getting-started Use the `csv_data` function to load options data from a CSV file. Column parameters must be integer indices specifying the position of each column. ```python import optopsy as op data = op.csv_data( 'options_data.csv', underlying_symbol=0, # Column index (0-based) option_type=1, expiration=2, quote_date=3, strike=4, bid=5, ask=6, delta=7 ) ``` -------------------------------- ### Reference Standard Strategy Defaults Source: https://goldspanlabs.github.io/optopsy/parameters Default parameter values for standard strategy configurations. ```python default_params = { "dte_interval": 7, "max_entry_dte": 90, "exit_dte": 0, "min_bid_ask": 0.05, "delta_interval": 0.05, "leg1_delta": None, # strategy-specific defaults applied by helpers "leg2_delta": None, "leg3_delta": None, "leg4_delta": None, "drop_nan": True, "raw": False, "slippage": "mid", "fill_ratio": 0.5, "reference_volume": 1000, "per_leg_slippage": 0.073, "stop_loss": None, "take_profit": None, "max_hold_days": None, "commission": None, } ``` -------------------------------- ### Use Liquidity-Based Slippage in Long Calls Source: https://goldspanlabs.github.io/optopsy/strategies/singles Demonstrates how to use liquidity-based slippage for long call options. Specify 'liquidity' as the slippage mode and set parameters like fill_ratio and reference_volume to control execution. ```python results = op.long_calls( data, slippage='liquidity', fill_ratio=0.5, # 50% through the spread reference_volume=1000 # Minimum volume for liquid options ) ``` -------------------------------- ### Export New Strategy Source: https://goldspanlabs.github.io/optopsy/contributing Add the newly defined strategy to the module's exports in `__init__.py` to make it accessible. ```python from .strategies import ( # ... existing strategies new_strategy, ) __all__ = [ # ... existing strategies "new_strategy", ] ``` -------------------------------- ### Basic Test Structure in Python Source: https://goldspanlabs.github.io/optopsy/contributing Illustrates a standard test function structure using pytest, including arrange, act, and assert steps. Ensure your test functions follow this pattern for clarity and maintainability. ```python def test_feature_name(sample_data): """Test that feature behaves correctly.""" # Arrange expected_result = ... # Act actual_result = function_under_test(sample_data) # Assert assert actual_result == expected_result ``` -------------------------------- ### Execute Call Front Spread Source: https://goldspanlabs.github.io/optopsy/strategies/spreads Calculates a call ratio spread using the optopsy library. ```python results = op.call_front_spread(data, max_entry_dte=45, exit_dte=21) ``` -------------------------------- ### Compare Strategies with Shared Parameters Source: https://goldspanlabs.github.io/optopsy/examples Ensure consistent comparison between different strategies by using a shared parameter dictionary. ```python # Use same parameters when comparing strategies params = { 'max_entry_dte': 45, 'exit_dte': 21, } ic_results = op.iron_condor(data, **params) strangle_results = op.short_strangles(data, **params) ``` -------------------------------- ### Covered Call Strategy with Stock Data Source: https://goldspanlabs.github.io/optopsy/strategies/covered Implement a covered call strategy using actual stock data. This approach is recommended for generating income on stock holdings when you are neutral to slightly bullish. ```python import yfinance as yf import optopsy as op # With actual stock data (recommended) stock = yf.download("SPY", start="2023-01-01", end="2023-12-31") results = op.covered_call(data, stock_data=stock, max_entry_dte=45, exit_dte=21) ``` -------------------------------- ### Manage Local Cache Source: https://goldspanlabs.github.io/optopsy/data Commands to inspect or clear the local Parquet cache. ```bash # Show per-symbol disk usage optopsy-data cache size # Clear all cached data optopsy-data cache clear # Clear a specific symbol optopsy-data cache clear SPY ``` -------------------------------- ### Implement Short Put Condor Strategy Source: https://goldspanlabs.github.io/optopsy/strategies/condors Implement a short put condor strategy with specified entry and exit days to expiration. This strategy is suitable for expecting a breakout. ```python results = op.short_put_condor(data, max_entry_dte=30, exit_dte=0) ``` -------------------------------- ### Execute Short Put Spread Source: https://goldspanlabs.github.io/optopsy/strategies/spreads Calculates a bull put spread using the optopsy library. ```python results = op.short_put_spread(data, max_entry_dte=45, exit_dte=21) ``` -------------------------------- ### Manage Cache Source: https://goldspanlabs.github.io/optopsy/chat-ui Commands to inspect or clear cached data. ```bash optopsy-chat cache size # show disk usage optopsy-chat cache clear # clear all cached data optopsy-chat cache clear SPY # clear a specific symbol ``` -------------------------------- ### Cash-Secured Put Strategy Source: https://goldspanlabs.github.io/optopsy/strategies/covered Implement a cash-secured put strategy. This is functionally identical to short_puts and is used for income generation or entering a stock position at a lower price. ```python import optopsy as op results = op.cash_secured_put(data, max_entry_dte=45, exit_dte=21) ``` -------------------------------- ### POST /optopsy/strategies/short_put_condor Source: https://goldspanlabs.github.io/optopsy/api-reference Generates performance statistics for a short put condor strategy, which profits from significant moves away from middle strikes. ```APIDOC ## POST /optopsy/strategies/short_put_condor ### Description Generates short put condor strategy statistics. A short put condor consists of shorting 1 put at the lowest strike, longing 1 put at the lower-middle strike, longing 1 put at the upper-middle strike, and shorting 1 put at the highest strike. ### Parameters #### Request Body - **data** (DataFrame) - Required - DataFrame containing option chain data - **kwargs** (Unpack[StrategyParamsDict]) - Optional - Optional strategy parameters ### Response #### Success Response (200) - **DataFrame** (DataFrame) - DataFrame with short put condor strategy performance statistics ``` -------------------------------- ### Load options data with csv_data Source: https://goldspanlabs.github.io/optopsy/api-reference Imports option chain data from a CSV file into a pandas DataFrame with standardized headers. ```python csv_data( file_path: str, start_date: Optional[str] = None, end_date: Optional[str] = None, underlying_symbol: int = 0, underlying_price: Optional[int] = None, option_type: int = 1, expiration: int = 2, quote_date: int = 3, strike: int = 4, bid: int = 5, ask: int = 6, delta: int = 7, gamma: Optional[int] = None, theta: Optional[int] = None, vega: Optional[int] = None, implied_volatility: Optional[int] = None, volume: Optional[int] = None, open_interest: Optional[int] = None, ) -> pd.DataFrame ``` -------------------------------- ### View Cache Directory Structure Source: https://goldspanlabs.github.io/optopsy/data The default local storage structure for cached Parquet files. ```text ~/.optopsy/cache/ ├── options/ │ ├── SPY.parquet │ └── AAPL.parquet └── stocks/ ├── SPY.parquet └── AAPL.parquet ``` -------------------------------- ### RSI Strategy Implementation Source: https://goldspanlabs.github.io/optopsy/entry-signals Demonstrates entering a long call position on RSI oversold conditions and exiting on overbought conditions. ```python import optopsy as op stocks = op.load_cached_stocks("SPY") options = op.load_cached_options("SPY") entry_dates = op.signal_dates(stocks, op.rsi_below(period=14, threshold=30)) exit_dates = op.signal_dates(stocks, op.rsi_above(period=14, threshold=70)) results = op.long_calls(options, entry_dates=entry_dates, exit_dates=exit_dates) ``` -------------------------------- ### Compare Multiple Strategies Source: https://goldspanlabs.github.io/optopsy/examples Compares the performance of multiple trading strategies (Long Calls, Short Puts, Iron Condor, Long Straddle) and displays a summary DataFrame. ```python strategies = { 'Long Calls': op.long_calls, 'Short Puts': op.short_puts, 'Iron Condor': op.iron_condor, 'Long Straddle': op.long_straddles } comparison = {} for name, strategy_func in strategies.items(): results = strategy_func( data, max_entry_dte=45, exit_dte=21 ) comparison[name] = { 'mean': results['mean'].mean(), 'std': results['std'].mean(), 'max': results['max'].max(), 'min': results['min'].min() } # Display comparison df_comparison = pd.DataFrame(comparison).T print(df_comparison) ``` -------------------------------- ### Backtest Short Straddles Source: https://goldspanlabs.github.io/optopsy/strategies/straddles-strangles Executes a backtest for short straddle positions with liquidity filtering. ```python results = op.short_straddles( data, max_entry_dte=45, exit_dte=21, leg1_delta={"target": 0.50, "min": 0.45, "max": 0.55}, # ATM straddles min_bid_ask=0.20 # Ensure liquid options ) ``` -------------------------------- ### Configure Delta Targeting for Strategies Source: https://goldspanlabs.github.io/optopsy/parameters Define delta ranges for specific legs in option strategies like short puts or iron condors. ```python # Single-leg: target 20-delta puts results = op.short_puts( data, leg1_delta={"target": 0.20, "min": 0.15, "max": 0.25} ) # Iron condor: customize short strike deltas results = op.iron_condor( data, leg2_delta={"target": 0.30, "min": 0.25, "max": 0.35}, # short put leg3_delta={"target": 0.30, "min": 0.25, "max": 0.35}, # short call ) ``` -------------------------------- ### Calculate Tail Ratio Source: https://goldspanlabs.github.io/optopsy/api-reference Calculates the Tail Ratio, which is the ratio of the 95th percentile return to the 5th percentile return. Values greater than 1 suggest that large gains are more probable than large losses, making it useful for options strategies. Requires a series of periodic returns. ```python tail_ratio(returns: _ArrayLike) -> float ``` -------------------------------- ### Load Custom Signals Source: https://goldspanlabs.github.io/optopsy/examples Integrate external indicators or manual flags into the Optopsy workflow using custom signal dataframes. ```python my_flags = pd.DataFrame({ "underlying_symbol": ["SPY"] * 5, "quote_date": pd.date_range("2023-01-02", periods=5, freq="B"), "go": [True, False, True, False, True], }) sig = op.custom_signal(my_flags, flag_col="go") entry_dates = op.signal_dates(my_flags, sig) options = op.csv_data('SPY_2023.csv') results = op.long_calls(options, entry_dates=entry_dates) print(results) ``` -------------------------------- ### Calculate Individual Risk Metrics Source: https://goldspanlabs.github.io/optopsy/examples Calculates various individual risk metrics (Sharpe, Sortino, Win Rate, Profit Factor, VaR, CVaR, Max Drawdown, Calmar, Omega, Tail Ratio) from trade returns. ```python import optopsy as op trades = op.iron_condor(data, raw=True) returns = trades['pct_change'] # Individual metrics print(f"Sharpe: {op.sharpe_ratio(returns):.2f}") print(f"Sortino: {op.sortino_ratio(returns):.2f}") print(f"Win Rate: {op.win_rate(returns):.1%}") print(f"Profit Factor: {op.profit_factor(returns):.2f}") print(f"VaR (95%): {op.value_at_risk(returns, 0.95):.2%}") print(f"CVaR (95%): {op.conditional_value_at_risk(returns, 0.95):.2%}") print(f"Max Drawdown: {op.max_drawdown_from_returns(returns):.2%}") print(f"Calmar: {op.calmar_ratio(returns):.2f}") print(f"Omega: {op.omega_ratio(returns):.2f}") print(f"Tail Ratio: {op.tail_ratio(returns):.2f}") # Or compute all at once all_metrics = op.compute_risk_metrics(returns) print(all_metrics) ``` -------------------------------- ### Calculate Performance Metrics Manually Source: https://goldspanlabs.github.io/optopsy/examples Compute strategy performance statistics from raw trade data. Prefer built-in simulation functions for production use cases. ```python def calculate_metrics(trades_df): """Calculate performance metrics for a strategy.""" returns = trades_df['pct_change'] metrics = { 'Total Trades': len(returns), 'Win Rate': (returns > 0).mean(), 'Mean Return': returns.mean(), 'Median Return': returns.median(), 'Std Dev': returns.std(), 'Max Win': returns.max(), 'Max Loss': returns.min(), 'Profit Factor': returns[returns > 0].sum() / abs(returns[returns < 0].sum()), 'Sharpe Ratio': returns.mean() / returns.std() if returns.std() > 0 else 0 } return pd.Series(metrics) # Apply to strategy trades = op.iron_condor(data, raw=True) metrics = calculate_metrics(trades) print(metrics) ``` -------------------------------- ### Implement Long Put Calendar Strategy Source: https://goldspanlabs.github.io/optopsy/strategies/calendars Use this function for long put calendar strategies. It requires the 'data' object containing option information. This strategy profits from neutral price action at the strike. ```python results = op.long_put_calendar(data) ``` -------------------------------- ### Generate single-leg strategy statistics Source: https://goldspanlabs.github.io/optopsy/api-reference Functions for calculating performance statistics for long/short call and put strategies using option chain data. ```python long_calls( data: DataFrame, **kwargs: Unpack[StrategyParamsDict] ) -> pd.DataFrame ``` ```python short_calls( data: DataFrame, **kwargs: Unpack[StrategyParamsDict] ) -> pd.DataFrame ``` ```python long_puts( data: DataFrame, **kwargs: Unpack[StrategyParamsDict] ) -> pd.DataFrame ```