API Reference¶
Complete API documentation for Optopsy functions.
Common Parameters
All strategy functions share common parameters. See the Common Parameters section below for detailed documentation of max_entry_dte, exit_dte, leg1_delta–leg4_delta, min_bid_ask, slippage settings, and more.
Data Loading¶
Load options data from CSV file.
optopsy.datafeeds.csv_data ¶
csv_data(
file_path: str,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
underlying_symbol: int = 0,
underlying_price: int = 1,
option_type: int = 2,
expiration: int = 3,
quote_date: int = 4,
strike: int = 5,
bid: int = 6,
ask: int = 7,
delta: int = 8,
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
Import option chain data from CSV files with standardized column names.
Uses pandas DataFrame.read_csv function to import data from CSV files. Automatically generates standardized headers for library use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to CSV file |
required |
start_date
|
Optional[str]
|
Optional start date of dataset to consider (inclusive) |
None
|
end_date
|
Optional[str]
|
Optional end date of dataset to consider (inclusive) |
None
|
underlying_symbol
|
int
|
Column index containing underlying symbol |
0
|
underlying_price
|
int
|
Column index containing underlying stock price |
1
|
quote_date
|
int
|
Column index containing quote date |
4
|
expiration
|
int
|
Column index containing expiration date |
3
|
strike
|
int
|
Column index containing strike price |
5
|
option_type
|
int
|
Column index containing option type (call/put) |
2
|
bid
|
int
|
Column index containing bid price |
6
|
ask
|
int
|
Column index containing ask price |
7
|
delta
|
int
|
Column index containing delta Greek. Required — all strategies use per-leg delta targeting |
8
|
gamma
|
Optional[int]
|
Optional column index containing gamma Greek |
None
|
theta
|
Optional[int]
|
Optional column index containing theta Greek |
None
|
vega
|
Optional[int]
|
Optional column index containing vega Greek |
None
|
implied_volatility
|
Optional[int]
|
Optional column index containing implied volatility |
None
|
volume
|
Optional[int]
|
Optional column index containing trading volume (used by liquidity slippage) |
None
|
open_interest
|
Optional[int]
|
Optional column index containing open interest (reserved for future use) |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with option chains and standardized column names |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If CSV file doesn't exist at specified path |
ValueError
|
If CSV file is empty, has parsing errors, column mapping errors, or other data processing issues |
Single-Leg Strategies¶
Note
All single-leg strategies accept the same parameters. See Common Parameters for full documentation.
optopsy.strategies.long_calls ¶
Generate long call strategy statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters (see StrategyParams) |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long call strategy performance statistics |
optopsy.strategies.short_calls ¶
Generate short call strategy statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short call strategy performance statistics |
optopsy.strategies.long_puts ¶
Generate long put strategy statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long put strategy performance statistics |
optopsy.strategies.short_puts ¶
Generate short put strategy statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short put strategy performance statistics |
Straddles & Strangles¶
Note
All straddle/strangle strategies accept the same parameters. See Common Parameters for full documentation.
optopsy.strategies.long_straddles ¶
Generate long straddle strategy statistics (long call + long put at same strike).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long straddle strategy performance statistics |
optopsy.strategies.short_straddles ¶
Generate short straddle strategy statistics (short call + short put at same strike).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short straddle strategy performance statistics |
optopsy.strategies.long_strangles ¶
Generate long strangle strategy statistics (long call + long put at different strikes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long strangle strategy performance statistics |
optopsy.strategies.short_strangles ¶
Generate short strangle strategy statistics (short call + short put at different strikes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short strangle strategy performance statistics |
Vertical Spreads¶
Note
All vertical spread strategies accept the same parameters. See Common Parameters for full documentation.
optopsy.strategies.long_call_spread ¶
Generate long call spread (bull call spread) statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long call spread strategy performance statistics |
optopsy.strategies.short_call_spread ¶
Generate short call spread (bear call spread) statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short call spread strategy performance statistics |
optopsy.strategies.long_put_spread ¶
Generate long put spread (bear put spread) statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long put spread strategy performance statistics |
optopsy.strategies.short_put_spread ¶
Generate short put spread (bull put spread) statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short put spread strategy performance statistics |
Ratio Spreads¶
Note
Ratio spreads use unequal quantities (1:2 ratio). They accept the same parameters as vertical spreads. See Common Parameters for full documentation.
optopsy.strategies.call_back_spread ¶
Generate call back spread (call ratio backspread) statistics.
A call back spread consists of: - Short 1 ITM call at lower strike - Long 2 OTM calls at higher strike
This is a bullish strategy that profits from a large upward move. The 2:1 ratio provides unlimited upside with limited downside.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with call back spread strategy performance statistics |
optopsy.strategies.put_back_spread ¶
Generate put back spread (put ratio backspread) statistics.
A put back spread consists of: - Short 1 ITM put at higher strike - Long 2 OTM puts at lower strike
This is a bearish strategy that profits from a large downward move. The 2:1 ratio provides large downside profit with limited upside risk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with put back spread strategy performance statistics |
optopsy.strategies.call_front_spread ¶
Generate call front spread (call ratio spread) statistics.
A call front spread consists of: - Long 1 ITM call at lower strike - Short 2 OTM calls at higher strike
This is a neutral-to-slightly-bullish strategy that profits from time decay when the underlying stays near the short strike.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with call front spread strategy performance statistics |
optopsy.strategies.put_front_spread ¶
Generate put front spread (put ratio spread) statistics.
A put front spread consists of: - Long 1 ITM put at higher strike - Short 2 OTM puts at lower strike
This is a neutral-to-slightly-bearish strategy that profits from time decay when the underlying stays near the short strike.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with put front spread strategy performance statistics |
Butterfly Spreads¶
Note
All butterfly strategies accept the same parameters. See Common Parameters for full documentation.
optopsy.strategies.long_call_butterfly ¶
Generate long call butterfly strategy statistics.
A long call butterfly consists of: - Long 1 call at lower strike (wing) - Short 2 calls at middle strike (body) - Long 1 call at upper strike (wing)
This is a neutral strategy that profits when the underlying stays near the middle strike at expiration. Maximum profit occurs at the middle strike.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long call butterfly strategy performance statistics |
optopsy.strategies.short_call_butterfly ¶
Generate short call butterfly strategy statistics.
A short call butterfly consists of: - Short 1 call at lower strike (wing) - Long 2 calls at middle strike (body) - Short 1 call at upper strike (wing)
This strategy profits when the underlying moves significantly away from the middle strike in either direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short call butterfly strategy performance statistics |
optopsy.strategies.long_put_butterfly ¶
Generate long put butterfly strategy statistics.
A long put butterfly consists of: - Long 1 put at lower strike (wing) - Short 2 puts at middle strike (body) - Long 1 put at upper strike (wing)
This is a neutral strategy that profits when the underlying stays near the middle strike at expiration. Maximum profit occurs at the middle strike.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long put butterfly strategy performance statistics |
optopsy.strategies.short_put_butterfly ¶
Generate short put butterfly strategy statistics.
A short put butterfly consists of: - Short 1 put at lower strike (wing) - Long 2 puts at middle strike (body) - Short 1 put at upper strike (wing)
This strategy profits when the underlying moves significantly away from the middle strike in either direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short put butterfly strategy performance statistics |
Iron Strategies¶
Note
All iron strategies accept the same parameters. See Common Parameters for full documentation.
optopsy.strategies.iron_condor ¶
Generate iron condor strategy statistics.
An iron condor consists of: - Long 1 put at lowest strike (protection) - Short 1 put at lower-middle strike (income) - Short 1 call at upper-middle strike (income) - Long 1 call at highest strike (protection)
This is a neutral income strategy that profits when the underlying stays between the two short strikes. Maximum profit is the net credit received.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with iron condor strategy performance statistics |
optopsy.strategies.reverse_iron_condor ¶
Generate reverse iron condor strategy statistics.
A reverse iron condor consists of: - Short 1 put at lowest strike - Long 1 put at lower-middle strike - Long 1 call at upper-middle strike - Short 1 call at highest strike
This strategy profits when the underlying makes a significant move in either direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with reverse iron condor strategy performance statistics |
optopsy.strategies.iron_butterfly ¶
Generate iron butterfly strategy statistics.
An iron butterfly consists of: - Long 1 put at lowest strike (wing) - Short 1 put at middle strike (body) - Short 1 call at middle strike (body) - same strike as short put - Long 1 call at highest strike (wing)
This is a neutral income strategy with higher profit potential than an iron condor, but a narrower profit zone. Maximum profit occurs when the underlying is exactly at the middle strike at expiration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with iron butterfly strategy performance statistics |
optopsy.strategies.reverse_iron_butterfly ¶
Generate reverse iron butterfly strategy statistics.
A reverse iron butterfly consists of: - Short 1 put at lowest strike (wing) - Long 1 put at middle strike (body) - Long 1 call at middle strike (body) - same strike as long put - Short 1 call at highest strike (wing)
This strategy profits when the underlying makes a significant move away from the middle strike in either direction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with reverse iron butterfly strategy performance statistics |
Condor Spreads¶
Note
Condor spreads use four legs of the same option type. They accept the same parameters as iron strategies. See Common Parameters for full documentation.
optopsy.strategies.long_call_condor ¶
Generate long call condor strategy statistics.
A long call condor consists of: - Long 1 call at lowest strike (K1) - Short 1 call at lower-middle strike (K2) - Short 1 call at upper-middle strike (K3) - Long 1 call at highest strike (K4)
This is a neutral strategy that profits when the underlying stays between the two short strikes. Similar to an iron condor but uses only calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long call condor strategy performance statistics |
optopsy.strategies.short_call_condor ¶
Generate short call condor strategy statistics.
A short call condor consists of: - Short 1 call at lowest strike (K1) - Long 1 call at lower-middle strike (K2) - Long 1 call at upper-middle strike (K3) - Short 1 call at highest strike (K4)
This strategy profits when the underlying makes a significant move in either direction away from the middle strikes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short call condor strategy performance statistics |
optopsy.strategies.long_put_condor ¶
Generate long put condor strategy statistics.
A long put condor consists of: - Long 1 put at lowest strike (K1) - Short 1 put at lower-middle strike (K2) - Short 1 put at upper-middle strike (K3) - Long 1 put at highest strike (K4)
This is a neutral strategy that profits when the underlying stays between the two short strikes. Similar to an iron condor but uses only puts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long put condor strategy performance statistics |
optopsy.strategies.short_put_condor ¶
Generate short put condor strategy statistics.
A short put condor consists of: - Short 1 put at lowest strike (K1) - Long 1 put at lower-middle strike (K2) - Long 1 put at upper-middle strike (K3) - Short 1 put at highest strike (K4)
This strategy profits when the underlying makes a significant move in either direction away from the middle strikes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short put condor strategy performance statistics |
Covered & Collar Strategies¶
Note
Covered and collar strategies accept all Common Parameters plus an optional stock_data parameter for actual stock prices. We recommend yfinance (pip install yfinance) — pass yf.download() output directly as stock_data. When omitted, a synthetic deep ITM call is used.
optopsy.strategies.covered_call ¶
covered_call(
data: DataFrame,
*,
stock_data: Optional[DataFrame] = None,
**kwargs: Unpack[StrategyParamsDict],
) -> pd.DataFrame
Generate covered call strategy statistics.
A covered call consists of: - Long underlying position + short 1 OTM call at higher strike
When stock_data is provided the underlying leg uses actual stock close prices. Otherwise a long deep ITM call (default delta ~0.80) is used as a synthetic stock position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
stock_data
|
Optional[DataFrame]
|
Optional DataFrame of stock prices for the underlying.
Accepts output from |
None
|
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with covered call strategy performance statistics |
optopsy.strategies.protective_put ¶
protective_put(
data: DataFrame,
*,
stock_data: Optional[DataFrame] = None,
**kwargs: Unpack[StrategyParamsDict],
) -> pd.DataFrame
Generate protective put (married put) strategy statistics.
A protective put consists of: - Long underlying position + long 1 OTM put at lower strike for protection
When stock_data is provided the underlying leg uses actual stock close prices. Otherwise a long deep ITM call (default delta ~0.80) is used as a synthetic stock position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
stock_data
|
Optional[DataFrame]
|
Optional DataFrame of stock prices for the underlying.
Accepts output from |
None
|
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with protective put strategy performance statistics |
optopsy.strategies.collar ¶
collar(
data: DataFrame,
*,
stock_data: Optional[DataFrame] = None,
**kwargs: Unpack[StrategyParamsDict],
) -> pd.DataFrame
Generate collar strategy statistics.
A collar consists of: - Long underlying position + short 1 OTM call + long 1 OTM put
When stock_data is provided the underlying leg uses actual stock close prices. Otherwise a long deep ITM call (default delta ~0.80) is used as a synthetic stock position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
stock_data
|
Optional[DataFrame]
|
Optional DataFrame of stock prices for the underlying. |
None
|
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with collar strategy performance statistics |
optopsy.strategies.cash_secured_put ¶
Generate cash-secured put strategy statistics.
A cash-secured put is functionally identical to a short put — the
trader sells a put while holding enough cash to buy the underlying
if assigned. This is an alias for short_puts provided for
convenience with common retail terminology.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with cash-secured put strategy performance statistics |
Calendar Spreads¶
Note
Calendar spreads have additional timing parameters (front_dte_min, front_dte_max, back_dte_min, back_dte_max) in addition to common parameters. See Common Parameters and Calendar/Diagonal Parameters for full documentation.
optopsy.strategies.long_call_calendar ¶
Generate long call calendar spread strategy statistics.
A long call calendar consists of: - Short 1 front-month call (near-term expiration) - Long 1 back-month call (longer-term expiration) - Both at the same strike
This is a neutral strategy that profits from time decay differential between the two expirations. Maximum profit occurs when the underlying is at the strike price at front-month expiration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters including: - front_dte_min: Minimum DTE for front leg (default: 20) - front_dte_max: Maximum DTE for front leg (default: 40) - back_dte_min: Minimum DTE for back leg (default: 50) - back_dte_max: Maximum DTE for back leg (default: 90) - exit_dte: Days before front expiration to exit (default: 7) |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long call calendar spread strategy performance statistics |
optopsy.strategies.short_call_calendar ¶
Generate short call calendar spread strategy statistics.
A short call calendar consists of: - Long 1 front-month call (near-term expiration) - Short 1 back-month call (longer-term expiration) - Both at the same strike
This strategy profits when the underlying moves significantly away from the strike price before front-month expiration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short call calendar spread strategy performance statistics |
optopsy.strategies.long_put_calendar ¶
Generate long put calendar spread strategy statistics.
A long put calendar consists of: - Short 1 front-month put (near-term expiration) - Long 1 back-month put (longer-term expiration) - Both at the same strike
This is a neutral strategy that profits from time decay differential between the two expirations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long put calendar spread strategy performance statistics |
optopsy.strategies.short_put_calendar ¶
Generate short put calendar spread strategy statistics.
A short put calendar consists of: - Long 1 front-month put (near-term expiration) - Short 1 back-month put (longer-term expiration) - Both at the same strike
This strategy profits when the underlying moves significantly away from the strike price before front-month expiration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short put calendar spread strategy performance statistics |
Diagonal Spreads¶
Note
Diagonal spreads have additional timing parameters (front_dte_min, front_dte_max, back_dte_min, back_dte_max) in addition to common parameters. See Common Parameters and Calendar/Diagonal Parameters for full documentation.
optopsy.strategies.long_call_diagonal ¶
Generate long call diagonal spread strategy statistics.
A long call diagonal consists of: - Short 1 front-month call (near-term expiration) - Long 1 back-month call (longer-term expiration) - Different strikes for each leg
This strategy combines elements of a calendar spread and a vertical spread. All strike combinations are evaluated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long call diagonal spread strategy performance statistics |
optopsy.strategies.short_call_diagonal ¶
Generate short call diagonal spread strategy statistics.
A short call diagonal consists of: - Long 1 front-month call (near-term expiration) - Short 1 back-month call (longer-term expiration) - Different strikes for each leg
This strategy combines elements of a calendar spread and a vertical spread. All strike combinations are evaluated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short call diagonal spread strategy performance statistics |
optopsy.strategies.long_put_diagonal ¶
Generate long put diagonal spread strategy statistics.
A long put diagonal consists of: - Short 1 front-month put (near-term expiration) - Long 1 back-month put (longer-term expiration) - Different strikes for each leg
This strategy combines elements of a calendar spread and a vertical spread. All strike combinations are evaluated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with long put diagonal spread strategy performance statistics |
optopsy.strategies.short_put_diagonal ¶
Generate short put diagonal spread strategy statistics.
A short put diagonal consists of: - Long 1 front-month put (near-term expiration) - Short 1 back-month put (longer-term expiration) - Different strikes for each leg
This strategy combines elements of a calendar spread and a vertical spread. All strike combinations are evaluated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing option chain data |
required |
**kwargs
|
Unpack[StrategyParamsDict]
|
Optional strategy parameters |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with short put diagonal spread strategy performance statistics |
Common Parameters¶
All strategy functions accept these common parameters:
Timing Parameters¶
- max_entry_dte (int, default=90): Maximum days to expiration at entry
- exit_dte (int, default=0): Days to expiration at exit
- dte_interval (int, default=7): Grouping interval for DTE ranges
Filtering Parameters¶
- min_bid_ask (float, default=0.05): Minimum bid-ask spread filter
- delta_interval (float, default=0.05): Grouping interval for delta ranges
Per-Leg Delta Targeting¶
- leg1_delta (TargetRange, optional): Delta target for leg 1
- leg2_delta (TargetRange, optional): Delta target for leg 2
- leg3_delta (TargetRange, optional): Delta target for leg 3
- leg4_delta (TargetRange, optional): Delta target for leg 4
Each TargetRange has target, min, and max fields. Can be passed as a dict: {"target": 0.30, "min": 0.20, "max": 0.40}. Strategy helpers apply sensible defaults when not specified.
Early Exit Parameters¶
- stop_loss (float, optional): Close early if unrealized P&L ≤ this value (must be negative, e.g.
-0.50) - take_profit (float, optional): Close early if unrealized P&L ≥ this value (must be positive, e.g.
0.50) - max_hold_days (int, optional): Close after this many calendar days regardless of P&L
Commission Parameters¶
- commission (Commission | float, optional): Commission fees. Pass a float for per-contract fee, or a
Commission(per_contract=..., base_fee=..., min_fee=..., per_share=...)for full fee structure.
Slippage Parameters¶
- slippage (str, default='mid'): Slippage mode - 'mid', 'spread', 'liquidity', or 'per_leg'
- fill_ratio (float, default=0.5): Fill ratio for liquidity mode (0.0-1.0)
- reference_volume (int, default=1000): Volume threshold for liquid options
Output Parameters¶
- raw (bool, default=False): Return raw trade data instead of aggregated stats
- drop_nan (bool, default=True): Drop rows with NaN values
Calendar/Diagonal Parameters¶
These strategies have additional timing parameters:
- front_dte_min (int, default=20): Minimum DTE for front leg
- front_dte_max (int, default=40): Maximum DTE for front leg
- back_dte_min (int, default=50): Minimum DTE for back leg
- back_dte_max (int, default=90): Maximum DTE for back leg
Return Values¶
Aggregated Results (default)¶
When raw=False (default), strategies return aggregated statistics:
Columns:
- dte_range: DTE interval group
- delta_range: Delta interval group
- count: Number of trades in group
- mean: Mean return
- std: Standard deviation of returns
- min: Minimum return
- 25%: 25th percentile
- 50%: Median return
- 75%: 75th percentile
- max: Maximum return
Raw Trade Data¶
When raw=True, strategies return individual trade details:
Columns (vary by strategy):
- underlying_symbol: Ticker symbol
- expiration: Option expiration date
- dte_entry: Days to expiration at entry
- strike / strike_leg1, strike_leg2, etc.: Strike prices
- entry: Entry price/cost
- exit: Exit price/proceeds
- pct_change: Percentage return
- exit_type: How the trade was closed (when early exits are enabled): stop_loss, take_profit, max_hold, or expiration
- Additional strategy-specific columns
Entry Signals¶
Functions for filtering strategy entries/exits using technical analysis or custom conditions. See the Entry Signals page for full usage examples.
optopsy.signals.apply_signal ¶
Run a signal function on data and return valid (symbol, date) pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame with at least |
required |
signal_func
|
SignalFunc
|
Callable that takes a DataFrame and returns a boolean Series. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns |
DataFrame
|
dates where the signal is True. |
optopsy.signals.custom_signal ¶
Create a signal function from a DataFrame with a boolean flag column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with at least |
required |
flag_col
|
str
|
Name of the column whose truthy values mark valid signal dates. |
'signal'
|
optopsy.signals.iv_rank_above ¶
True when IV rank exceeds a threshold.
optopsy.signals.iv_rank_below ¶
True when IV rank is below a threshold.
Simulation¶
Run chronological strategy simulations with capital tracking, position limits, and equity curve generation.
optopsy.simulator.simulate ¶
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
Run a chronological simulation of an options strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Option chain DataFrame (same format as strategy functions expect). |
required |
strategy
|
Callable[..., DataFrame]
|
Any optopsy strategy function (e.g. |
required |
capital
|
float
|
Starting capital in dollars. |
100000.0
|
quantity
|
int
|
Number of contracts per trade. |
1
|
max_positions
|
int
|
Maximum concurrent open positions. |
1
|
multiplier
|
int
|
Contract multiplier (100 for standard equity options). |
100
|
selector
|
Union[Literal['nearest', 'highest_premium', 'lowest_premium', 'first'], Callable[[DataFrame], Series]]
|
How to pick one trade when multiple candidates exist for a
date. One of |
'nearest'
|
**strategy_kwargs
|
Any
|
Passed through to the strategy function. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
SimulationResult
|
class: |
optopsy.simulator.SimulationResult
dataclass
¶
Container for simulation output.
Attributes:
| Name | Type | Description |
|---|---|---|
trade_log |
DataFrame
|
One row per completed trade with P&L details. |
equity_curve |
Series
|
Indexed by exit date; value is equity after each trade close. |
summary |
dict[str, Any]
|
Flat dict of performance metrics. |
optopsy.simulator.simulate_portfolio ¶
Run a weighted portfolio simulation across multiple strategy legs.
Each leg runs independently via :func:simulate with its share of capital.
Results are combined into a single portfolio equity curve and trade log.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
legs
|
list[dict]
|
List of leg dicts. Each must contain |
required |
capital
|
float
|
Total starting capital in dollars. |
100000.0
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PortfolioResult
|
class: |
Example::
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,
)
optopsy.simulator.PortfolioResult
dataclass
¶
Container for multi-leg portfolio simulation output.
Attributes:
| Name | Type | Description |
|---|---|---|
trade_log |
DataFrame
|
Combined trade log across all legs, with a |
equity_curve |
Series
|
Daily portfolio equity (sum of per-leg equity curves). |
summary |
dict[str, Any]
|
Portfolio-level performance metrics (same keys as single sim). |
leg_results |
dict[str, SimulationResult]
|
Per-leg :class: |
Risk Metrics¶
Performance metrics for strategy evaluation. Used by simulate() internally and available for standalone use.
optopsy.metrics.compute_risk_metrics ¶
compute_risk_metrics(
returns: _ArrayLike,
equity: _ArrayLike | None = None,
trading_days: int = _TRADING_DAYS,
) -> dict[str, float]
Compute all risk metrics from a returns series.
Convenience function that returns a flat dict of all metrics. Used by both the simulation and aggregated strategy output paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
_ArrayLike
|
Series of periodic returns (per-trade pct_change). |
required |
equity
|
_ArrayLike | None
|
Optional equity curve. If not provided, drawdown is computed from returns. |
None
|
trading_days
|
int
|
Annualisation factor. |
_TRADING_DAYS
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dict with keys: sharpe_ratio, sortino_ratio, max_drawdown, var_95, |
dict[str, float]
|
cvar_95, win_rate, profit_factor, calmar_ratio, omega_ratio, |
dict[str, float]
|
tail_ratio. |
optopsy.metrics.sharpe_ratio ¶
sharpe_ratio(
returns: _ArrayLike,
trading_days: int = _TRADING_DAYS,
risk_free_rate: float = 0.0,
) -> float
Annualised Sharpe ratio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
_ArrayLike
|
Series of periodic returns (e.g. per-trade or daily). |
required |
trading_days
|
int
|
Annualisation factor. |
_TRADING_DAYS
|
risk_free_rate
|
float
|
Annual risk-free rate (default 0). |
0.0
|
Returns:
| Type | Description |
|---|---|
float
|
Sharpe ratio as a float, or 0.0 if std is zero or data is empty. |
optopsy.metrics.sortino_ratio ¶
sortino_ratio(
returns: _ArrayLike,
trading_days: int = _TRADING_DAYS,
risk_free_rate: float = 0.0,
) -> float
Annualised Sortino ratio (penalises only downside deviation).
More appropriate than Sharpe for asymmetric options payoffs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
_ArrayLike
|
Series of periodic returns. |
required |
trading_days
|
int
|
Annualisation factor. |
_TRADING_DAYS
|
risk_free_rate
|
float
|
Annual risk-free rate (default 0). |
0.0
|
Returns:
| Type | Description |
|---|---|
float
|
Sortino ratio as a float, or 0.0 if downside deviation is zero. |
optopsy.metrics.max_drawdown ¶
Maximum peak-to-trough drawdown as a negative fraction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
equity
|
_ArrayLike
|
Equity curve series (absolute values, not returns). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Max drawdown as a negative float (e.g. -0.15 for 15% drawdown), |
float
|
or 0.0 if the equity curve is empty or monotonically increasing. |
optopsy.metrics.value_at_risk ¶
Historical Value at Risk (VaR).
The loss threshold at the given confidence level. For example, at 95% confidence, VaR is the 5th percentile of returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
_ArrayLike
|
Series of periodic returns. |
required |
confidence
|
float
|
Confidence level (default 0.95). |
0.95
|
Returns:
| Type | Description |
|---|---|
float
|
VaR as a float (typically negative, representing a loss). |
float
|
Returns 0.0 if data is empty. |
optopsy.metrics.conditional_value_at_risk ¶
Conditional VaR (CVaR), also known as Expected Shortfall.
Mean of returns that fall at or below the VaR threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
_ArrayLike
|
Series of periodic returns. |
required |
confidence
|
float
|
Confidence level (default 0.95). |
0.95
|
Returns:
| Type | Description |
|---|---|
float
|
CVaR as a float (typically negative). Returns 0.0 if data is empty. |
optopsy.metrics.win_rate ¶
Fraction of trades with positive P&L.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pnl
|
_ArrayLike
|
Series of P&L values (absolute or percentage). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Win rate as a float between 0 and 1. Returns 0.0 if empty. |
optopsy.metrics.profit_factor ¶
Ratio of gross profits to gross losses.
sum(winning_trades) / abs(sum(losing_trades))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pnl
|
_ArrayLike
|
Series of P&L values. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Profit factor as a float. Returns inf if no losses, 0.0 if no wins |
float
|
or empty. |
optopsy.metrics.calmar_ratio ¶
calmar_ratio(
returns: _ArrayLike,
trading_days: int = _TRADING_DAYS,
initial_capital: float = 1.0,
) -> float
Calmar ratio: annualised return divided by max drawdown.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
_ArrayLike
|
Series of periodic returns. |
required |
trading_days
|
int
|
Number of trading days per year for annualisation. |
_TRADING_DAYS
|
initial_capital
|
float
|
Unused, kept for API compatibility. |
1.0
|
Returns:
| Type | Description |
|---|---|
float
|
Calmar ratio as a float, or 0.0 if max drawdown is zero or data |
float
|
is insufficient. |
optopsy.metrics.omega_ratio ¶
omega_ratio(
returns: _ArrayLike,
trading_days: int = _TRADING_DAYS,
risk_free_rate: float = 0.0,
) -> float
Omega ratio — captures full return distribution, not just mean/variance.
Ratio of probability-weighted gains to probability-weighted losses relative to a threshold return. Values > 1 indicate gains outweigh losses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
_ArrayLike
|
Series of periodic returns. |
required |
trading_days
|
int
|
Annualisation factor. |
_TRADING_DAYS
|
risk_free_rate
|
float
|
Annual risk-free rate (default 0). |
0.0
|
Returns:
| Type | Description |
|---|---|
float
|
Omega ratio as a float, or 0.0 if data is insufficient. |
optopsy.metrics.tail_ratio ¶
Ratio of right tail (95th percentile) to left tail (5th percentile).
Values > 1 indicate the right tail is fatter, meaning large gains are more likely than large losses. Particularly useful for options strategies where tail behaviour drives performance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
returns
|
_ArrayLike
|
Series of periodic returns. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Tail ratio as a float, or 0.0 if data is insufficient. |
Examples¶
See the Examples page for detailed usage examples.
Type Hints and Validation¶
All strategy functions use Pydantic-based validation for parameters. Type errors produce clear, field-specific error messages.
import pandas as pd
from typing_extensions import Unpack
from optopsy import StrategyParamsDict
def long_calls(data: pd.DataFrame, **kwargs: Unpack[StrategyParamsDict]) -> pd.DataFrame:
...
Exported Types¶
| Type | Description |
|---|---|
StrategyParamsDict |
TypedDict for Unpack[] annotations on standard strategies |
StrategyParams |
Pydantic model for runtime validation of standard strategy parameters |
CalendarStrategyParamsDict |
TypedDict for Unpack[] annotations on calendar/diagonal strategies |
CalendarStrategyParams |
Pydantic model for calendar/diagonal parameters with cross-field validation |
TargetRange |
Per-leg delta target with target, min, max fields |
Commission |
Commission fee structure with per_contract, per_share, base_fee, min_fee fields |
SimulationResult |
Dataclass with trade_log, equity_curve, and summary |
PortfolioResult |
Dataclass with combined portfolio results and per-leg SimulationResult |
Using Type Hints¶
Import StrategyParamsDict or CalendarStrategyParamsDict for better IDE support:
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
)
Strict Type Validation
Parameters are now validated with Pydantic. Boolean parameters like raw must be actual bool values — raw=1 will be rejected. Use raw=True instead. Similarly, float parameters like min_bid_ask must be float — min_bid_ask=5 will be rejected, use min_bid_ask=5.0.