Skip to main content
ClaudeWave
Skill12k repo starsupdated today

options-strategy

The options-strategy skill provides a backtesting framework for multi-leg option portfolios using Black-Scholes pricing and Greeks analysis. It supports seven common strategies including covered calls, straddles, iron condors, and calendar spreads across cryptocurrency and equity markets. Users implement a signal engine to generate trading instructions that the framework evaluates for profit/loss, Greeks exposure, and exercise outcomes throughout the backtest period.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading /tmp/options-strategy && cp -r /tmp/options-strategy/agent/src/skills/options-strategy ~/.claude/skills/options-strategy
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

## Purpose

Backtesting of option portfolio strategies. Starting from the underlying price, the engine synthesizes theoretical option prices with the Black-Scholes model, then simulates PnL, Greeks exposure, and expiration exercise for multi-leg option portfolios.

Applicable scenarios:
- Hedging strategies (`covered call`, `protective put`)
- Volatility trading (`straddle`, `strangle`)
- Spread strategies (`iron condor`, `butterfly`, `calendar spread`)
- Option pricing analysis and Greeks sensitivity research

## Supported Strategy Types

| Strategy | Structure | Applicable Market View |
|------|------|----------|
| Covered Call | Hold underlying + short call | Mildly bullish, collect premium |
| Protective Put | Hold underlying + long put | Bullish but wants downside protection |
| Straddle | Buy same-strike call + put | Expect large movement, direction uncertain |
| Strangle | Buy different-strike call + put | Expect large movement, lower cost |
| Iron Condor | Sell put spread + sell call spread | Range-bound market, collect premium |
| Butterfly | Buy low call + sell 2 middle calls + buy high call | Expect narrow-range movement |
| Calendar Spread | Sell near-month + buy far-month at same strike | Exploit differences in time decay |

## `OptionsSignalEngine` Interface

Write the strategy in `code/signal_engine.py`, with class name `SignalEngine`, implementing the `generate` method:

```python
class SignalEngine:
    """Option strategy signal engine."""

    def generate(self, data_map: dict) -> list:
        """Generate option trading instructions.

        Args:
            data_map: code -> DataFrame (columns: open, high, low, close, volume)

        Returns:
            List of trading instructions. Each instruction has the format:
            {
                "date": "2024-01-15",        # Trading date
                "action": "open" / "close",  # Open or close position
                "underlying": "BTC-USDT",    # Underlying code
                "legs": [                    # List of option legs
                    {
                        "type": "call" / "put",  # Option type
                        "strike": 50000,          # Strike price
                        "expiry": "2024-02-15",   # Expiration date
                        "qty": 1                  # Quantity (positive = long, negative = short)
                    }
                ]
            }
        """
```

### Multi-Leg Combination Example

Iron Condor opening signal:

```python
{
    "date": "2024-01-15",
    "action": "open",
    "underlying": "000300.SH",
    "legs": [
        {"type": "put",  "strike": 3800, "expiry": "2024-02-15", "qty": -1},  # Sell put
        {"type": "put",  "strike": 3700, "expiry": "2024-02-15", "qty":  1},  # Buy protective put
        {"type": "call", "strike": 4200, "expiry": "2024-02-15", "qty": -1},  # Sell call
        {"type": "call", "strike": 4300, "expiry": "2024-02-15", "qty":  1},  # Buy protective call
    ]
}
```

## `config.json` Format

```json
{
    "codes": ["000300.SH"],
    "start_date": "2020-01-01",
    "end_date": "2024-12-31",
    "source": "tushare",
    "engine": "options",
    "initial_cash": 1000000,
    "commission": 0.001,
    "options_config": {
        "risk_free_rate": 0.05,
        "iv_source": "historical",
        "contract_multiplier": 1.0
    }
}
```

Key fields:
- `engine` must be set to `"options"` so the runner selects the option backtest engine
- `options_config.risk_free_rate`: risk-free rate, default `0.05`
- `options_config.iv_source`: volatility source, currently supports `"historical"` (30-day rolling historical volatility computed from underlying closes)
- `options_config.contract_multiplier`: contract multiplier, default `1.0`

## BS Model Principles

Black-Scholes formula (European options):

```
Call = S * N(d1) - K * e^(-rT) * N(d2)
Put  = K * e^(-rT) * N(-d2) - S * N(-d1)

d1 = [ln(S/K) + (r + sigma^2/2) * T] / (sigma * sqrt(T))
d2 = d1 - sigma * sqrt(T)
```

Where `S` = underlying price, `K` = strike, `T` = time to expiry in years, `r` = risk-free rate, `sigma` = volatility, and `N()` = cumulative distribution function of the standard normal.

This engine starts from the underlying daily price series, substitutes historical volatility for implied volatility, and computes theoretical option prices through the BS formula. This is a synthetic-data mode, meaning no real option market data is required.

## Greeks Meaning and Usage

| Greek | Meaning | Usage |
|-------|------|------|
| Delta | Change in option price for a 1-unit move in the underlying | Directional exposure management, hedge-ratio calculation |
| Gamma | Change in Delta for a 1-unit move in the underlying | Measures hedge stability; high Gamma = frequent rebalancing required |
| Theta | Time decay of option value per day (usually negative) | Time-value management, source of return for short-option strategies |
| Vega | Change in option price for a 1% volatility move | Core metric for volatility trading, measures volatility exposure |

The backtest engine computes portfolio-level Greeks aggregates on each trading day and outputs them to `greeks.csv`.

## Common Pitfalls

### Volatility Smile

The BS model assumes constant volatility, but in real markets implied volatility differs across strikes and expiries (volatility smile / skew). This engine approximates with historical volatility, so pricing may be biased for deep OTM / deep ITM options. Strategy design should avoid over-reliance on pricing precision at extreme strikes.

### Time Decay (Theta Decay)

Theta decay is not linear — the closer the option is to expiry, the faster the decay. The last 30 days decay much faster than the prior 30 days. Short-vol strategies benefit from this, but Gamma risk also rises sharply near expiry.

### Early Exercise

This engine supports European options only (exercise only at expiry), not American options. In scenarios with meaningful early-exercise value (for example, deep ITM p
vibe-tradingSkill

Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 77 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).

adr-hshareSkill

ADR/H-share/A-share cross-listing premium analysis — track pricing gaps between US-listed ADRs, HK-listed H-shares, and A-shares for arbitrage signals, dual-listing valuation, and delisting risk assessment.

akshareSkill

AKShare financial data aggregator (18k+ stars). Free, no API key. Covers A-shares, US, HK, futures, macro, forex. Primary fallback for tushare and yfinance.

alpha-zooSkill

Browse and bench the bundled alpha zoos — prebuilt cross-sectional factor libraries (Kakushadze 101, GTJA 191, Qlib 158, Fama-French / Carhart). Use when the user asks "which alphas exist", wants metadata on a named alpha, or wants to run IC/IR on a whole zoo over a universe.

ashare-pre-st-filterSkill

A 股 ST/*ST 风险预测框架 — 基于最新中报/三季报或业绩预告/快报,预测下一财年是否会因营收、利润、净资产、分红不达标而被风险警示,并将新浪监管处罚记录作为独立证据面纳入风险等级。仅适用于 A 股,不预测财务造假。

asset-allocationSkill

Asset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 4 optimizers and rebalancing rules.

backtest-diagnoseSkill

Diagnose failed or underperforming backtests, locate the root cause, and fix the issue

behavioral-financeSkill

Behavioral finance applications: theories of overreaction and underreaction, behavioral explanations for momentum and reversal, investor sentiment cycles, cognitive-bias checklists, and debiasing quantitative strategies.